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;
269 final String LOG_STR = "fetchResults";
271 chefInfo(params, ctx);
272 String nodeListS = params.get(NODE_LIST_STR);
273 if (StringUtils.isNotBlank(nodeListS)) {
274 nodeListS = nodeListS.replace("[", StringUtils.EMPTY);
275 nodeListS = nodeListS.replace("]", StringUtils.EMPTY);
276 nodeListS = nodeListS.replace("\"", StringUtils.EMPTY);
277 nodeListS = nodeListS.replace(" ", StringUtils.EMPTY);
278 List<String> nodes = Arrays.asList(nodeListS.split("\\s*,\\s*"));
279 JSONObject result = new JSONObject();
280 String returnMessage = StringUtils.EMPTY;
282 for (String node : nodes) {
283 String chefAction = "/nodes/" + node;
285 if (privateKeyChecker.doesExist(clientPrivatekey)) {
286 ChefResponse chefResponse = getApiMethod(chefAction);
287 code = chefResponse.getStatusCode();
288 message = chefResponse.getBody();
291 message = CANNOT_FIND_PRIVATE_KEY_STR + clientPrivatekey;
292 doFailure(ctx, code, message);
294 if (code == STATUS_OK) {
295 JSONObject nodeResult = new JSONObject();
296 JSONObject allNodeData = new JSONObject(message);
297 allNodeData = allNodeData.getJSONObject("normal");
298 String attribute = "PushJobOutput";
300 String resultData = allNodeData.optString(attribute, null);
301 if (resultData == null) {
302 resultData = Optional.ofNullable(allNodeData.optJSONObject(attribute))
303 .map(p -> p.toString()).orElse(null);
304 if (resultData == null) {
305 resultData = Optional.ofNullable(allNodeData.optJSONArray(attribute))
306 .map(p -> p.toString()).orElse(null);
308 if (resultData == null) {
310 returnMessage = "Cannot find " + attribute;
315 nodeResult.put(attribute, resultData);
316 result.put(node, nodeResult);
317 returnMessage = result.toString();
320 returnMessage = message + " Cannot access: " + node;
321 doFailure(ctx, code, message);
326 chefServerResult(ctx, code, returnMessage);
328 throw new SvcLogicException("Missing Mandatory param(s) NodeList ");
330 } catch (JSONException e) {
331 code = APPC_ERRORCODE;
332 logger.error(POSTING_REQUEST_JSON_ERROR_STR + LOG_STR, e);
333 doFailure(ctx, code, POSTING_REQUEST_JSON_ERROR_STR + LOG_STR + e.getMessage());
334 } catch (Exception e) {
335 code = APPC_ERRORCODE;
336 logger.error(POSTING_REQUEST_ERROR_STR + LOG_STR, e);
337 doFailure(ctx, code, POSTING_REQUEST_ERROR_STR + LOG_STR + e.getMessage());
341 private ChefResponse getApiMethod(String chefAction) {
342 ChefApiClient cac = chefApiClientFactory.create(chefserver, organizations, username, clientPrivatekey);
343 return cac.get(chefAction);
349 @SuppressWarnings("nls")
351 public void nodeObejctBuilder(Map<String, String> params, SvcLogicContext ctx) {
352 logger.info("nodeObejctBuilder");
353 String name = params.get("nodeobject.name");
354 String normal = params.get("nodeobject.normal");
355 String overrides = params.get("nodeobject.overrides");
356 String defaults = params.get("nodeobject.defaults");
357 String runList = params.get("nodeobject.run_list");
358 String chefEnvironment = params.get("nodeobject.chef_environment");
359 String nodeObject = "{\"json_class\":\"Chef::Node\",\"default\":{" + defaults
360 + "},\"chef_type\":\"node\",\"run_list\":[" + runList + "],\"override\":{" + overrides
361 + "},\"normal\": {" + normal + "},\"automatic\":{},\"name\":\"" + name + "\",\"chef_environment\":\""
362 + chefEnvironment + "\",}";
363 logger.info(nodeObject);
364 ctx.setAttribute("chef.nodeObject", nodeObject);
368 * send get request to chef server
370 private void chefInfo(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException {
372 username = params.get("username");
373 serverAddress = params.get("serverAddress");
374 organizations = params.get("organizations");
375 if (StringUtils.isNotBlank(username) && StringUtils.isNotBlank(serverAddress)
376 && StringUtils.isNotBlank(organizations)) {
377 chefserver = "https://" + serverAddress + "/organizations/" + organizations;
378 clientPrivatekey = "/opt/onap/appc/chef/" + serverAddress + "/" + organizations + "/" + username + ".pem";
379 logger.info(" clientPrivatekey " + clientPrivatekey);
381 doFailure(ctx, APPC_ERRORCODE, "Missing mandatory param(s) such as username, serverAddress, organizations");
385 @SuppressWarnings("nls")
387 public void retrieveData(Map<String, String> params, SvcLogicContext ctx) {
388 String allConfigData = params.get("allConfig");
389 String key = params.get("key");
390 String dgContext = params.get("dgContext");
391 JSONObject jsonConfig = new JSONObject(allConfigData);
392 String contextData = fetchContextData(key, jsonConfig);
393 ctx.setAttribute(dgContext, contextData);
396 private String fetchContextData(String key, JSONObject jsonConfig) {
398 return jsonConfig.getString(key);
399 } catch (Exception e) {
400 logger.error("Failed getting string value corresponding to " + key + ". Trying to fetch nested json object",
403 return jsonConfig.getJSONObject(key).toString();
404 } catch (Exception ex) {
405 logger.error("Failed getting json object corresponding to " + key + ". Trying to fetch array", ex);
406 return jsonConfig.getJSONArray(key).toString();
411 @SuppressWarnings("nls")
413 public void combineStrings(Map<String, String> params, SvcLogicContext ctx) {
414 String string1 = params.get("String1");
415 String string2 = params.get("String2");
416 String dgContext = params.get("dgContext");
417 String contextData = string1 + string2;
418 ctx.setAttribute(dgContext, contextData);
422 * Send GET request to chef server
424 @SuppressWarnings("nls")
427 public void chefGet(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException {
428 logger.info("chef get method");
429 chefInfo(params, ctx);
430 String chefAction = params.get(CHEF_ACTION_STR);
433 if (privateKeyChecker.doesExist(clientPrivatekey)) {
434 ChefResponse chefResponse = getApiMethod(chefAction);
435 code = chefResponse.getStatusCode();
436 message = chefResponse.getBody();
439 message = CANNOT_FIND_PRIVATE_KEY_STR + clientPrivatekey;
441 chefServerResult(ctx, code, message);
445 * Send PUT request to chef server
447 @SuppressWarnings("nls")
450 public void chefPut(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException {
451 chefInfo(params, ctx);
452 String chefAction = params.get(CHEF_ACTION_STR);
453 String chefNodeStr = params.get("chefRequestBody");
456 if (privateKeyChecker.doesExist(clientPrivatekey)) {
457 ChefApiClient chefApiClient = chefApiClientFactory.create(chefserver, organizations, username,
459 ChefResponse chefResponse = chefApiClient.put(chefAction, chefNodeStr);
460 code = chefResponse.getStatusCode();
461 message = chefResponse.getBody();
464 message = CANNOT_FIND_PRIVATE_KEY_STR + clientPrivatekey;
466 logger.info(code + " " + message);
467 chefServerResult(ctx, code, message);
471 * send Post request to chef server
474 public void chefPost(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException {
475 chefInfo(params, ctx);
476 logger.info("chef Post method");
477 logger.info(username + " " + clientPrivatekey + " " + chefserver + " " + organizations);
478 String chefNodeStr = params.get("chefRequestBody");
479 String chefAction = params.get(CHEF_ACTION_STR);
482 // should load pem from somewhere else
483 if (privateKeyChecker.doesExist(clientPrivatekey)) {
484 ChefApiClient chefApiClient = chefApiClientFactory.create(chefserver, organizations, username,
486 // need pass path into it
488 ChefResponse chefResponse = chefApiClient.post(chefAction, chefNodeStr);
489 code = chefResponse.getStatusCode();
490 message = chefResponse.getBody();
493 message = CANNOT_FIND_PRIVATE_KEY_STR + clientPrivatekey;
495 logger.info(code + " " + message);
496 chefServerResult(ctx, code, message);
500 * send delete request to chef server
503 public void chefDelete(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException {
504 logger.info("chef delete method");
505 chefInfo(params, ctx);
506 String chefAction = params.get(CHEF_ACTION_STR);
509 if (privateKeyChecker.doesExist(clientPrivatekey)) {
510 ChefApiClient chefApiClient = chefApiClientFactory.create(chefserver, organizations, username,
512 ChefResponse chefResponse = chefApiClient.delete(chefAction);
513 code = chefResponse.getStatusCode();
514 message = chefResponse.getBody();
517 message = CANNOT_FIND_PRIVATE_KEY_STR + clientPrivatekey;
519 logger.info(code + " " + message);
520 chefServerResult(ctx, code, message);
524 * Trigger target vm run chef
527 public void trigger(Map<String, String> params, SvcLogicContext svcLogicContext) {
528 logger.info("Run trigger method");
529 String tVmIp = params.get("ip");
531 ChefResponse chefResponse = chefApiClientFactory.create(tVmIp, organizations).get("");
532 chefClientResult(svcLogicContext, chefResponse.getStatusCode(), chefResponse.getBody());
533 svcLogicContext.setAttribute("chefAgent.code", STATUS_OK.toString());
534 } catch (Exception e) {
535 logger.error("An error occurred when executing trigger method", e);
536 svcLogicContext.setAttribute("chefAgent.code", KEY_NOTFOUND.toString());
537 svcLogicContext.setAttribute("chefAgent.message", e.toString());
541 @SuppressWarnings("nls")
543 public void checkPushJob(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException {
546 chefInfo(params, ctx);
547 String jobID = params.get("jobid");
548 String retry = params.get("retryTimes");
549 String intrva = params.get("retryInterval");
550 if (StringUtils.isNotBlank(jobID) && StringUtils.isNotBlank(retry) && StringUtils.isNotBlank(intrva)) {
552 int retryTimes = Integer.parseInt(params.get("retryTimes"));
553 int retryInterval = Integer.parseInt(params.get("retryInterval"));
554 String chefAction = "/pushy/jobs/" + jobID;
555 String message = StringUtils.EMPTY;
556 String status = StringUtils.EMPTY;
557 for (int i = 0; i < retryTimes; i++) {
558 sleepFor(retryInterval);
559 ChefResponse chefResponse = getApiMethod(chefAction);
560 code = chefResponse.getStatusCode();
561 message = chefResponse.getBody();
562 JSONObject obj = new JSONObject(message);
563 status = obj.getString("status");
564 if (!"running".equals(status)) {
565 logger.info(i + " time " + code + " " + status);
569 resolveSvcLogicAttributes(ctx, message, status);
571 throw new SvcLogicException("Missing Mandatory param(s) retryTimes , retryInterval ");
573 } catch (Exception e) {
574 code = APPC_ERRORCODE;
575 logger.error("An error occurred when executing checkPushJob method", e);
576 doFailure(ctx, code, e.getMessage());
580 private void resolveSvcLogicAttributes(SvcLogicContext svcLogic, String message, String status) {
581 if ("complete".equals(status)) {
582 if (hasFailedNode(message)) {
583 String finalMessage = "PushJob Status Complete but check failed nodes in the message :" + message;
584 svcLogic.setAttribute(CHEF_SERVER_RESULT_CODE_STR, APPC_ERRORCODE.toString());
585 svcLogic.setAttribute(CHEF_SERVER_RESULT_MSG_STR, finalMessage);
587 svcLogic.setAttribute(CHEF_SERVER_RESULT_CODE_STR, STATUS_OK.toString());
588 svcLogic.setAttribute(CHEF_SERVER_RESULT_MSG_STR, message);
590 } else if ("running".equals(status)) {
591 svcLogic.setAttribute(CHEF_SERVER_RESULT_CODE_STR, PUSHJOBSTATUS.toString());
592 svcLogic.setAttribute(CHEF_SERVER_RESULT_MSG_STR, "chef client runtime out");
594 svcLogic.setAttribute(CHEF_SERVER_RESULT_CODE_STR, KEY_NOTFOUND.toString());
595 svcLogic.setAttribute(CHEF_SERVER_RESULT_MSG_STR, message);
599 private Boolean hasFailedNode(String message) throws JSONException {
601 JSONObject messageJson = new JSONObject(message);
602 JSONObject node = messageJson.getJSONObject("nodes");
604 logger.debug("Status Complete but node details in the message is null : " + message);
607 if (node.has("failed") && !(node.isNull("failed")) && (node.getJSONArray("failed").length() != 0)) {
608 logger.debug("Status Complete but one or more Failed nodes ....FAILURE " + message);
611 logger.debug("Status Complete and no failed nodes ....SUCCESS " + message);
612 return Boolean.FALSE;
613 } catch (JSONException e) {
614 logger.error("Exception occured in hasFailedNode", e);
615 throw new JSONException("Exception occured in hasFailedNode" + e.getMessage());
620 private void sleepFor(int retryInterval) {
622 Thread.sleep(retryInterval); // 1000 milliseconds is one second.
623 } catch (InterruptedException ex) {
624 Thread.currentThread().interrupt();
628 @SuppressWarnings("nls")
630 public void pushJob(Map<String, String> params, SvcLogicContext ctx) throws SvcLogicException {
633 chefInfo(params, ctx);
634 String pushRequest = params.get("pushRequest");
635 String chefAction = "/pushy/jobs";
636 ChefApiClient chefApiClient = chefApiClientFactory.create(chefserver, organizations, username,
638 ChefResponse chefResponse = chefApiClient.post(chefAction, pushRequest);
639 code = chefResponse.getStatusCode();
640 String message = chefResponse.getBody();
641 if (code == STATUS_PUSHJOBCHECK) {
642 int startIndex = message.indexOf("jobs") + 6;
643 int endIndex = message.length() - 2;
644 String jobID = message.substring(startIndex, endIndex);
645 ctx.setAttribute("jobID", jobID);
648 chefServerResult(ctx, code, message);
649 } catch (Exception e) {
650 code = APPC_ERRORCODE;
651 logger.error("An error occurred when executing pushJob method", e);
652 doFailure(ctx, code, e.getMessage());
656 @SuppressWarnings("static-method")
657 private void chefServerResult(SvcLogicContext svcLogicContext, int code, String message) {
658 initSvcLogic(svcLogicContext, code, message, "server");
661 @SuppressWarnings("static-method")
662 private void chefClientResult(SvcLogicContext svcLogicContext, int code, String message) {
663 initSvcLogic(svcLogicContext, code, message, "client");
666 private void initSvcLogic(SvcLogicContext svcLogicContext, int code, String message, String target) {
668 String codeStr = "server".equals(target) ? CHEF_SERVER_RESULT_CODE_STR : CHEF_CLIENT_RESULT_CODE_STR;
669 String messageStr = "client".equals(target) ? CHEF_CLIENT_RESULT_MSG_STR : CHEF_SERVER_RESULT_MSG_STR;
670 svcLogicContext.setStatus(OUTCOME_SUCCESS);
671 svcLogicContext.setAttribute(codeStr, Integer.toString(code));
672 svcLogicContext.setAttribute(messageStr, message);
673 logger.info(codeStr + ": " + svcLogicContext.getAttribute(codeStr));
674 logger.info(messageStr + ": " + svcLogicContext.getAttribute(messageStr));
677 @SuppressWarnings("static-method")
678 private void doFailure(SvcLogicContext svcLogic, int code, String message) throws SvcLogicException {
680 String cutMessage = message.contains("\n") ? message.substring(message.indexOf('\n')) : message;
681 svcLogic.setStatus(OUTCOME_FAILURE);
682 svcLogic.setAttribute(CHEF_SERVER_RESULT_CODE_STR, Integer.toString(code));
683 svcLogic.setAttribute(CHEF_SERVER_RESULT_MSG_STR, cutMessage);
684 throw new SvcLogicException("Chef Adapter error:" + cutMessage);