2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Copyright (C) 2017 Amdocs
8 * =============================================================================
9 * Modifications Copyright (C) 2019 IBM
10 * =============================================================================
11 * Licensed under the Apache License, Version 2.0 (the "License");
12 * you may not use this file except in compliance with the License.
13 * You may obtain a copy of the License at
15 * http://www.apache.org/licenses/LICENSE-2.0
17 * Unless required by applicable law or agreed to in writing, software
18 * distributed under the License is distributed on an "AS IS" BASIS,
19 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20 * See the License for the specific language governing permissions and
21 * limitations under the License.
22 * ============LICENSE_END=========================================================
24 package org.onap.appc.adapter.chef.impl;
26 import com.att.eelf.configuration.EELFLogger;
27 import com.att.eelf.configuration.EELFManager;
28 import java.util.Arrays;
29 import java.util.List;
31 import java.util.Optional;
32 import org.apache.commons.lang.StringUtils;
33 import org.json.JSONException;
34 import org.json.JSONObject;
35 import org.onap.appc.adapter.chef.ChefAdapter;
36 import org.onap.appc.adapter.chef.chefclient.ChefApiClientFactory;
37 import org.onap.appc.adapter.chef.chefclient.api.ChefApiClient;
38 import org.onap.appc.adapter.chef.chefclient.api.ChefResponse;
39 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
40 import org.onap.ccsdk.sli.core.sli.SvcLogicException;
43 * This class implements the {@link ChefAdapter} interface. This interface
44 * defines the behaviors that our service provides.
46 public class ChefAdapterImpl implements ChefAdapter {
48 // chef server Initialize variable
49 private String username = StringUtils.EMPTY;
50 private String clientPrivatekey = StringUtils.EMPTY;
51 private String chefserver = StringUtils.EMPTY;
52 private String serverAddress = StringUtils.EMPTY;
53 private String organizations = StringUtils.EMPTY;
55 @SuppressWarnings("nls")
56 public static final String MDC_ADAPTER = "adapter";
58 @SuppressWarnings("nls")
59 public static final String MDC_SERVICE = "service";
61 @SuppressWarnings("nls")
62 public static final String OUTCOME_FAILURE = "failure";
64 @SuppressWarnings("nls")
65 public static final String OUTCOME_SUCCESS = "success";
67 @SuppressWarnings("nls")
68 public static final String PROPERTY_PROVIDER = "provider";
70 @SuppressWarnings("nls")
71 public static final String PROPERTY_PROVIDER_IDENTITY = "identity";
73 @SuppressWarnings("nls")
74 public static final String PROPERTY_PROVIDER_NAME = "name";
76 @SuppressWarnings("nls")
77 public static final String PROPERTY_PROVIDER_TENANT = "tenant";
79 @SuppressWarnings("nls")
80 public static final String PROPERTY_PROVIDER_TENANT_NAME = "name";
82 @SuppressWarnings("nls")
83 public static final String PROPERTY_PROVIDER_TENANT_PASSWORD = "password"; // NOSONAR
85 @SuppressWarnings("nls")
86 public static final String PROPERTY_PROVIDER_TENANT_USERID = "userid";
88 @SuppressWarnings("nls")
89 public static final String PROPERTY_PROVIDER_TYPE = "type";
91 private static final EELFLogger logger = EELFManager.getInstance().getLogger(ChefAdapterImpl.class);
93 private static final String CANNOT_FIND_PRIVATE_KEY_STR = "Cannot find the private key in the APPC file system, please load the private key to ";
95 private static final String POSTING_REQUEST_JSON_ERROR_STR = "Error posting request due to invalid JSON block: ";
96 private static final String POSTING_REQUEST_ERROR_STR = "Error posting request: ";
97 private static final String CHEF_CLIENT_RESULT_CODE_STR = "chefClientResult.code";
98 private static final String CHEF_SERVER_RESULT_CODE_STR = "chefServerResult.code";
99 private static final String CHEF_CLIENT_RESULT_MSG_STR = "chefClientResult.message";
100 private static final String CHEF_SERVER_RESULT_MSG_STR = "chefServerResult.message";
101 private static final String CHEF_ACTION_STR = "chefAction";
102 private static final String NODE_LIST_STR = "NodeList";
103 private static final Integer STATUS_OK = 200;
104 private static final Integer STATUS_PUSHJOBCHECK = 201;
105 private static final Integer PUSHJOBSTATUS= 202;
106 private static final Integer KEY_NOTFOUND = 500;
107 private static final Integer NO_ENVIRONMENT = 404;
108 private static final Integer APPC_ERRORCODE = 401;
110 private final ChefApiClientFactory chefApiClientFactory;
111 private final PrivateKeyChecker privateKeyChecker;
113 ChefAdapterImpl(ChefApiClientFactory chefApiClientFactory, PrivateKeyChecker privateKeyChecker) {
114 this.chefApiClientFactory = chefApiClientFactory;
115 this.privateKeyChecker = privateKeyChecker;
116 logger.info("Initialize Chef Adapter");
119 @SuppressWarnings("nls")
121 public void vnfcEnvironment(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException {
123 logger.info("environment of VNF-C");
124 chefInfo(params, ctx);
125 String env = params.get("Environment");
126 logger.info("Environmnet" + env);
127 if (env.equals(StringUtils.EMPTY)) {
128 chefServerResult(ctx, STATUS_OK, "Skip Environment block ");
131 if (privateKeyChecker.doesExist(clientPrivatekey)) {
133 JSONObject envJ = new JSONObject(env);
134 String envName = envJ.getString("name");
135 // update the details of an environment on the Chef server.
136 ChefApiClient chefApiClient = chefApiClientFactory.create(chefserver, organizations, username,
138 ChefResponse chefResponse = chefApiClient.put("/environments/" + envName, env);
139 code = chefResponse.getStatusCode();
140 message = chefResponse.getBody();
141 if (code == NO_ENVIRONMENT) {
142 // need create a new environment
143 chefResponse = chefApiClient.post("/environments", env);
144 code = chefResponse.getStatusCode();
145 message = chefResponse.getBody();
146 logger.info("requestbody {}", chefResponse.getBody());
148 chefServerResult(ctx, code, message);
149 } catch (JSONException e) {
150 code = APPC_ERRORCODE;
151 logger.error(POSTING_REQUEST_JSON_ERROR_STR, e);
152 doFailure(ctx, code, POSTING_REQUEST_JSON_ERROR_STR + e.getMessage());
153 } catch (Exception e) {
154 code = APPC_ERRORCODE;
155 logger.error(POSTING_REQUEST_ERROR_STR + "vnfcEnvironment", e);
156 doFailure(ctx, code, POSTING_REQUEST_ERROR_STR + "vnfcEnvironment" + e.getMessage());
160 message = CANNOT_FIND_PRIVATE_KEY_STR + clientPrivatekey;
161 doFailure(ctx, code, message);
166 @SuppressWarnings("nls")
168 public void vnfcNodeobjects(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException {
169 logger.info("update the nodeObjects of VNF-C");
172 chefInfo(params, ctx);
173 String nodeListS = params.get(NODE_LIST_STR);
174 String nodeS = params.get("Node");
175 if (StringUtils.isNotBlank(nodeListS) && StringUtils.isNotBlank(nodeS)) {
176 nodeListS = nodeListS.replace("[", StringUtils.EMPTY);
177 nodeListS = nodeListS.replace("]", StringUtils.EMPTY);
178 nodeListS = nodeListS.replace("\"", StringUtils.EMPTY);
179 nodeListS = nodeListS.replace(" ", StringUtils.EMPTY);
180 List<String> nodes = Arrays.asList(nodeListS.split("\\s*,\\s*"));
182 String message = null;
183 if (privateKeyChecker.doesExist(clientPrivatekey)) {
184 ChefApiClient cac = chefApiClientFactory.create(chefserver, organizations, username,
187 for (String nodeName : nodes) {
188 JSONObject nodeJ = new JSONObject(nodeS);
189 nodeJ.remove("name");
190 nodeJ.put("name", nodeName);
191 String nodeObject = nodeJ.toString();
192 logger.info(nodeObject);
193 ChefResponse chefResponse = cac.put("/nodes/" + nodeName, nodeObject);
194 code = chefResponse.getStatusCode();
195 message = chefResponse.getBody();
196 if (code != STATUS_OK) {
202 message = CANNOT_FIND_PRIVATE_KEY_STR + clientPrivatekey;
203 doFailure(ctx, code, message);
205 chefServerResult(ctx, code, message);
207 throw new SvcLogicException("Missing Mandatory param(s) Node , NodeList ");
209 } catch (JSONException e) {
210 code = APPC_ERRORCODE;
211 logger.error(POSTING_REQUEST_JSON_ERROR_STR + "vnfcNodeobjects", e);
212 doFailure(ctx, code, POSTING_REQUEST_JSON_ERROR_STR + "vnfcNodeobjects" + e.getMessage());
213 } catch (Exception e) {
214 code = APPC_ERRORCODE;
215 logger.error(POSTING_REQUEST_ERROR_STR + "vnfcNodeobjects", e);
216 doFailure(ctx, code, POSTING_REQUEST_ERROR_STR + "vnfcNodeobjects" + e.getMessage());
221 public void vnfcPushJob(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException {
224 chefInfo(params, ctx);
225 String nodeList = params.get(NODE_LIST_STR);
226 if (StringUtils.isNotBlank(nodeList)) {
227 String isCallback = params.get("CallbackCapable");
228 String chefAction = "/pushy/jobs";
231 if ("true".equals(isCallback)) {
232 String requestId = params.get("RequestId");
233 String callbackUrl = params.get("CallbackUrl");
234 pushRequest = "{" + "\"command\": \"chef-client\"," + "\"run_timeout\": 300," + "\"nodes\":"
235 + nodeList + "," + "\"env\": {\"RequestId\": \"" + requestId + "\", \"CallbackUrl\": \""
236 + callbackUrl + "\"}," + "\"capture_output\": true" + "}";
238 pushRequest = "{" + "\"command\": \"chef-client\"," + "\"run_timeout\": 300," + "\"nodes\":"
239 + nodeList + "," + "\"env\": {}," + "\"capture_output\": true" + "}";
241 ChefApiClient cac = chefApiClientFactory.create(chefserver, organizations, username, clientPrivatekey);
242 ChefResponse chefResponse = cac.post(chefAction, pushRequest);
243 code = chefResponse.getStatusCode();
244 logger.info("pushRequest:" + pushRequest);
245 logger.info("requestbody: {}", chefResponse.getBody());
246 String message = chefResponse.getBody();
247 if (code == STATUS_PUSHJOBCHECK) {
248 int startIndex = message.indexOf("jobs") + 5;
249 int endIndex = message.length() - 2;
250 String jobID = message.substring(startIndex, endIndex);
251 ctx.setAttribute("jobID", jobID);
254 chefServerResult(ctx, code, message);
256 throw new SvcLogicException("Missing Mandatory param(s) NodeList ");
258 } catch (Exception e) {
259 code = APPC_ERRORCODE;
260 logger.error(POSTING_REQUEST_ERROR_STR + "vnfcPushJob", e);
261 doFailure(ctx, code, POSTING_REQUEST_ERROR_STR + "vnfcPushJob" + e.getMessage());
265 @SuppressWarnings("nls")
267 public void fetchResults(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException {
268 int code = STATUS_OK;
270 chefInfo(params, ctx);
271 String nodeListS = params.get(NODE_LIST_STR);
272 if (StringUtils.isNotBlank(nodeListS)) {
273 nodeListS = nodeListS.replace("[", StringUtils.EMPTY);
274 nodeListS = nodeListS.replace("]", StringUtils.EMPTY);
275 nodeListS = nodeListS.replace("\"", StringUtils.EMPTY);
276 nodeListS = nodeListS.replace(" ", StringUtils.EMPTY);
277 List<String> nodes = Arrays.asList(nodeListS.split("\\s*,\\s*"));
278 JSONObject result = new JSONObject();
279 String returnMessage = StringUtils.EMPTY;
281 for (String node : nodes) {
282 String chefAction = "/nodes/" + node;
284 if (privateKeyChecker.doesExist(clientPrivatekey)) {
285 ChefResponse chefResponse = getApiMethod(chefAction);
286 code = chefResponse.getStatusCode();
287 message = chefResponse.getBody();
290 message = CANNOT_FIND_PRIVATE_KEY_STR + clientPrivatekey;
291 doFailure(ctx, code, message);
293 if (code == STATUS_OK) {
294 JSONObject nodeResult = new JSONObject();
295 JSONObject allNodeData = new JSONObject(message);
296 allNodeData = allNodeData.getJSONObject("normal");
297 String attribute = "PushJobOutput";
299 String resultData = allNodeData.optString(attribute, null);
300 if (resultData == null) {
301 resultData = Optional.ofNullable(allNodeData.optJSONObject(attribute))
302 .map(p -> p.toString()).orElse(null);
303 if (resultData == null) {
304 resultData = Optional.ofNullable(allNodeData.optJSONArray(attribute))
305 .map(p -> p.toString()).orElse(null);
307 if (resultData == null) {
309 returnMessage = "Cannot find " + attribute;
314 nodeResult.put(attribute, resultData);
315 result.put(node, nodeResult);
316 returnMessage = result.toString();
319 returnMessage = message + " Cannot access: " + node;
320 doFailure(ctx, code, message);
325 chefServerResult(ctx, code, returnMessage);
327 throw new SvcLogicException("Missing Mandatory param(s) NodeList ");
329 } catch (JSONException e) {
330 code = APPC_ERRORCODE;
331 logger.error(POSTING_REQUEST_JSON_ERROR_STR + "fetchResults", e);
332 doFailure(ctx, code, POSTING_REQUEST_JSON_ERROR_STR + "fetchResults" + e.getMessage());
333 } catch (Exception e) {
334 code = APPC_ERRORCODE;
335 logger.error(POSTING_REQUEST_ERROR_STR + "fetchResults", e);
336 doFailure(ctx, code, POSTING_REQUEST_ERROR_STR + "fetchResults" + e.getMessage());
340 private ChefResponse getApiMethod(String chefAction) {
341 ChefApiClient cac = chefApiClientFactory.create(chefserver, organizations, username, clientPrivatekey);
342 return cac.get(chefAction);
348 @SuppressWarnings("nls")
350 public void nodeObejctBuilder(Map<String, String> params, SvcLogicContext ctx) {
351 logger.info("nodeObejctBuilder");
352 String name = params.get("nodeobject.name");
353 String normal = params.get("nodeobject.normal");
354 String overrides = params.get("nodeobject.overrides");
355 String defaults = params.get("nodeobject.defaults");
356 String runList = params.get("nodeobject.run_list");
357 String chefEnvironment = params.get("nodeobject.chef_environment");
358 String nodeObject = "{\"json_class\":\"Chef::Node\",\"default\":{" + defaults
359 + "},\"chef_type\":\"node\",\"run_list\":[" + runList + "],\"override\":{" + overrides
360 + "},\"normal\": {" + normal + "},\"automatic\":{},\"name\":\"" + name + "\",\"chef_environment\":\""
361 + chefEnvironment + "\",}";
362 logger.info(nodeObject);
363 ctx.setAttribute("chef.nodeObject", nodeObject);
367 * send get request to chef server
369 private void chefInfo(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException {
371 username = params.get("username");
372 serverAddress = params.get("serverAddress");
373 organizations = params.get("organizations");
374 if (StringUtils.isNotBlank(username) && StringUtils.isNotBlank(serverAddress)
375 && StringUtils.isNotBlank(organizations)) {
376 chefserver = "https://" + serverAddress + "/organizations/" + organizations;
377 clientPrivatekey = "/opt/onap/appc/chef/" + serverAddress + "/" + organizations + "/" + username + ".pem";
378 logger.info(" clientPrivatekey " + clientPrivatekey);
380 doFailure(ctx, APPC_ERRORCODE, "Missing mandatory param(s) such as username, serverAddress, organizations");
384 @SuppressWarnings("nls")
386 public void retrieveData(Map<String, String> params, SvcLogicContext ctx) {
387 String allConfigData = params.get("allConfig");
388 String key = params.get("key");
389 String dgContext = params.get("dgContext");
390 JSONObject jsonConfig = new JSONObject(allConfigData);
391 String contextData = fetchContextData(key, jsonConfig);
392 ctx.setAttribute(dgContext, contextData);
395 private String fetchContextData(String key, JSONObject jsonConfig) {
397 return jsonConfig.getString(key);
398 } catch (Exception e) {
399 logger.error("Failed getting string value corresponding to " + key + ". Trying to fetch nested json object",
402 return jsonConfig.getJSONObject(key).toString();
403 } catch (Exception ex) {
404 logger.error("Failed getting json object corresponding to " + key + ". Trying to fetch array", ex);
405 return jsonConfig.getJSONArray(key).toString();
410 @SuppressWarnings("nls")
412 public void combineStrings(Map<String, String> params, SvcLogicContext ctx) {
413 String string1 = params.get("String1");
414 String string2 = params.get("String2");
415 String dgContext = params.get("dgContext");
416 String contextData = string1 + string2;
417 ctx.setAttribute(dgContext, contextData);
421 * Send GET request to chef server
423 @SuppressWarnings("nls")
426 public void chefGet(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException {
427 logger.info("chef get method");
428 chefInfo(params, ctx);
429 String chefAction = params.get(CHEF_ACTION_STR);
432 if (privateKeyChecker.doesExist(clientPrivatekey)) {
433 ChefResponse chefResponse = getApiMethod(chefAction);
434 code = chefResponse.getStatusCode();
435 message = chefResponse.getBody();
438 message = CANNOT_FIND_PRIVATE_KEY_STR + clientPrivatekey;
440 chefServerResult(ctx, code, message);
444 * Send PUT request to chef server
446 @SuppressWarnings("nls")
449 public void chefPut(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException {
450 chefInfo(params, ctx);
451 String chefAction = params.get(CHEF_ACTION_STR);
452 String chefNodeStr = params.get("chefRequestBody");
455 if (privateKeyChecker.doesExist(clientPrivatekey)) {
456 ChefApiClient chefApiClient = chefApiClientFactory.create(chefserver, organizations, username,
458 ChefResponse chefResponse = chefApiClient.put(chefAction, chefNodeStr);
459 code = chefResponse.getStatusCode();
460 message = chefResponse.getBody();
463 message = CANNOT_FIND_PRIVATE_KEY_STR + clientPrivatekey;
465 logger.info(code + " " + message);
466 chefServerResult(ctx, code, message);
470 * send Post request to chef server
473 public void chefPost(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException {
474 chefInfo(params, ctx);
475 logger.info("chef Post method");
476 logger.info(username + " " + clientPrivatekey + " " + chefserver + " " + organizations);
477 String chefNodeStr = params.get("chefRequestBody");
478 String chefAction = params.get(CHEF_ACTION_STR);
481 // should load pem from somewhere else
482 if (privateKeyChecker.doesExist(clientPrivatekey)) {
483 ChefApiClient chefApiClient = chefApiClientFactory.create(chefserver, organizations, username,
485 // need pass path into it
487 ChefResponse chefResponse = chefApiClient.post(chefAction, chefNodeStr);
488 code = chefResponse.getStatusCode();
489 message = chefResponse.getBody();
492 message = CANNOT_FIND_PRIVATE_KEY_STR + clientPrivatekey;
494 logger.info(code + " " + message);
495 chefServerResult(ctx, code, message);
499 * send delete request to chef server
502 public void chefDelete(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException {
503 logger.info("chef delete method");
504 chefInfo(params, ctx);
505 String chefAction = params.get(CHEF_ACTION_STR);
508 if (privateKeyChecker.doesExist(clientPrivatekey)) {
509 ChefApiClient chefApiClient = chefApiClientFactory.create(chefserver, organizations, username,
511 ChefResponse chefResponse = chefApiClient.delete(chefAction);
512 code = chefResponse.getStatusCode();
513 message = chefResponse.getBody();
516 message = CANNOT_FIND_PRIVATE_KEY_STR + clientPrivatekey;
518 logger.info(code + " " + message);
519 chefServerResult(ctx, code, message);
523 * Trigger target vm run chef
526 public void trigger(Map<String, String> params, SvcLogicContext svcLogicContext) {
527 logger.info("Run trigger method");
528 String tVmIp = params.get("ip");
530 ChefResponse chefResponse = chefApiClientFactory.create(tVmIp, organizations).get("");
531 chefClientResult(svcLogicContext, chefResponse.getStatusCode(), chefResponse.getBody());
532 svcLogicContext.setAttribute("chefAgent.code", STATUS_OK.toString());
533 } catch (Exception e) {
534 logger.error("An error occurred when executing trigger method", e);
535 svcLogicContext.setAttribute("chefAgent.code", KEY_NOTFOUND.toString());
536 svcLogicContext.setAttribute("chefAgent.message", e.toString());
540 @SuppressWarnings("nls")
542 public void checkPushJob(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException {
545 chefInfo(params, ctx);
546 String jobID = params.get("jobid");
547 String retry = params.get("retryTimes");
548 String intrva = params.get("retryInterval");
549 if (StringUtils.isNotBlank(jobID) && StringUtils.isNotBlank(retry) && StringUtils.isNotBlank(intrva)) {
551 int retryTimes = Integer.parseInt(params.get("retryTimes"));
552 int retryInterval = Integer.parseInt(params.get("retryInterval"));
553 String chefAction = "/pushy/jobs/" + jobID;
554 String message = StringUtils.EMPTY;
555 String status = StringUtils.EMPTY;
556 for (int i = 0; i < retryTimes; i++) {
557 sleepFor(retryInterval);
558 ChefResponse chefResponse = getApiMethod(chefAction);
559 code = chefResponse.getStatusCode();
560 message = chefResponse.getBody();
561 JSONObject obj = new JSONObject(message);
562 status = obj.getString("status");
563 if (!"running".equals(status)) {
564 logger.info(i + " time " + code + " " + status);
568 resolveSvcLogicAttributes(ctx, message, status);
570 throw new SvcLogicException("Missing Mandatory param(s) retryTimes , retryInterval ");
572 } catch (Exception e) {
573 code = APPC_ERRORCODE;
574 logger.error("An error occurred when executing checkPushJob method", e);
575 doFailure(ctx, code, e.getMessage());
579 private void resolveSvcLogicAttributes(SvcLogicContext svcLogic, String message, String status) {
580 if ("complete".equals(status)) {
581 if (hasFailedNode(message)) {
582 String finalMessage = "PushJob Status Complete but check failed nodes in the message :" + message;
583 svcLogic.setAttribute(CHEF_SERVER_RESULT_CODE_STR, APPC_ERRORCODE.toString());
584 svcLogic.setAttribute(CHEF_SERVER_RESULT_MSG_STR, finalMessage);
586 svcLogic.setAttribute(CHEF_SERVER_RESULT_CODE_STR, STATUS_OK.toString());
587 svcLogic.setAttribute(CHEF_SERVER_RESULT_MSG_STR, message);
589 } else if ("running".equals(status)) {
590 svcLogic.setAttribute(CHEF_SERVER_RESULT_CODE_STR, PUSHJOBSTATUS.toString());
591 svcLogic.setAttribute(CHEF_SERVER_RESULT_MSG_STR, "chef client runtime out");
593 svcLogic.setAttribute(CHEF_SERVER_RESULT_CODE_STR, KEY_NOTFOUND.toString());
594 svcLogic.setAttribute(CHEF_SERVER_RESULT_MSG_STR, message);
598 private Boolean hasFailedNode(String message) throws JSONException {
600 JSONObject messageJson = new JSONObject(message);
601 JSONObject node = messageJson.getJSONObject("nodes");
603 logger.debug("Status Complete but node details in the message is null : " + message);
606 if (node.has("failed") && !(node.isNull("failed")) && (node.getJSONArray("failed").length() != 0)) {
607 logger.debug("Status Complete but one or more Failed nodes ....FAILURE " + message);
610 logger.debug("Status Complete and no failed nodes ....SUCCESS " + message);
611 return Boolean.FALSE;
612 } catch (JSONException e) {
613 logger.error("Exception occured in hasFailedNode", e);
614 throw new JSONException("Exception occured in hasFailedNode" + e.getMessage());
619 private void sleepFor(int retryInterval) {
621 Thread.sleep(retryInterval); // 1000 milliseconds is one second.
622 } catch (InterruptedException ex) {
623 Thread.currentThread().interrupt();
627 @SuppressWarnings("nls")
629 public void pushJob(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException {
632 chefInfo(params, ctx);
633 String pushRequest = params.get("pushRequest");
634 String chefAction = "/pushy/jobs";
635 ChefApiClient chefApiClient = chefApiClientFactory.create(chefserver, organizations, username,
637 ChefResponse chefResponse = chefApiClient.post(chefAction, pushRequest);
638 code = chefResponse.getStatusCode();
639 String message = chefResponse.getBody();
640 if (code == STATUS_PUSHJOBCHECK) {
641 int startIndex = message.indexOf("jobs") + 6;
642 int endIndex = message.length() - 2;
643 String jobID = message.substring(startIndex, endIndex);
644 ctx.setAttribute("jobID", jobID);
647 chefServerResult(ctx, code, message);
648 } catch (Exception e) {
649 code = APPC_ERRORCODE;
650 logger.error("An error occurred when executing pushJob method", e);
651 doFailure(ctx, code, e.getMessage());
655 @SuppressWarnings("static-method")
656 private void chefServerResult(SvcLogicContext svcLogicContext, int code, String message) {
657 initSvcLogic(svcLogicContext, code, message, "server");
660 @SuppressWarnings("static-method")
661 private void chefClientResult(SvcLogicContext svcLogicContext, int code, String message) {
662 initSvcLogic(svcLogicContext, code, message, "client");
665 private void initSvcLogic(SvcLogicContext svcLogicContext, int code, String message, String target) {
667 String codeStr = "server".equals(target) ? CHEF_SERVER_RESULT_CODE_STR : CHEF_CLIENT_RESULT_CODE_STR;
668 String messageStr = "client".equals(target) ? CHEF_CLIENT_RESULT_MSG_STR : CHEF_SERVER_RESULT_MSG_STR;
669 svcLogicContext.setStatus(OUTCOME_SUCCESS);
670 svcLogicContext.setAttribute(codeStr, Integer.toString(code));
671 svcLogicContext.setAttribute(messageStr, message);
672 logger.info(codeStr + ": " + svcLogicContext.getAttribute(codeStr));
673 logger.info(messageStr + ": " + svcLogicContext.getAttribute(messageStr));
676 @SuppressWarnings("static-method")
677 private void doFailure(SvcLogicContext svcLogic, int code, String message) throws SvcLogicException {
679 String cutMessage = message.contains("\n") ? message.substring(message.indexOf('\n')) : message;
680 svcLogic.setStatus(OUTCOME_FAILURE);
681 svcLogic.setAttribute(CHEF_SERVER_RESULT_CODE_STR, Integer.toString(code));
682 svcLogic.setAttribute(CHEF_SERVER_RESULT_MSG_STR, cutMessage);
683 throw new SvcLogicException("Chef Adapter error:" + cutMessage);