2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * Copyright (C) 2017 Amdocs
7 * ================================================================================
8 * Licensed under the Apache License, Version 2.0 (the "License");
9 * you may not use this file except in compliance with the License.
10 * You may obtain a copy of the License at
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing, software
15 * distributed under the License is distributed on an "AS IS" BASIS,
16 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 * See the License for the specific language governing permissions and
18 * limitations under the License.
19 * ============LICENSE_END=========================================================
20 * ECOMP is a trademark and service mark of AT&T Intellectual Property.
23 package org.openecomp.appc.adapter.chef.impl;
26 import java.util.ArrayList;
27 import java.util.HashMap;
28 import java.util.List;
30 import java.util.Properties;
32 import java.util.regex.Pattern;
36 import org.openecomp.appc.Constants;
37 import org.openecomp.appc.adapter.chef.ChefAdapter;
38 import org.openecomp.appc.adapter.chef.chefapi.*;
39 import org.openecomp.appc.adapter.chef.chefclient.*;
40 import org.openecomp.appc.configuration.Configuration;
41 import org.openecomp.appc.configuration.ConfigurationFactory;
42 import org.openecomp.appc.exceptions.APPCException;
43 import org.openecomp.appc.exceptions.UnknownProviderException;
44 import org.openecomp.appc.i18n.Msg;
45 import org.openecomp.appc.pool.Pool;
46 import org.openecomp.appc.pool.PoolExtensionException;
47 import org.openecomp.appc.util.StructuredPropertyHelper;
48 import org.openecomp.appc.util.StructuredPropertyHelper.Node;
49 import com.att.cdp.exceptions.ContextConnectionException;
50 import com.att.cdp.exceptions.ResourceNotFoundException;
51 import com.att.cdp.exceptions.TimeoutException;
52 import com.att.cdp.exceptions.ZoneException;
53 import com.att.cdp.pal.util.StringHelper;
54 import com.att.cdp.zones.ComputeService;
55 import com.att.cdp.zones.Context;
56 import com.att.cdp.zones.ImageService;
57 import com.att.cdp.zones.Provider;
58 import com.att.cdp.zones.model.Image;
59 import com.att.cdp.zones.model.Server;
60 import com.att.cdp.zones.model.ServerBootSource;
61 import com.att.cdp.zones.model.Server.Status;
62 import com.att.eelf.configuration.EELFLogger;
63 import com.att.eelf.configuration.EELFManager;
64 import com.att.eelf.i18n.EELFResourceManager;
65 import org.openecomp.sdnc.sli.SvcLogicContext;
68 import java.net.InetAddress;
69 import java.util.Locale;
70 import java.util.UUID;
72 import org.apache.http.*;
73 import org.apache.http.client.*;
74 import org.apache.http.client.methods.*;
75 import org.apache.http.impl.client.*;
76 import org.apache.http.util.EntityUtils;
78 import static com.att.eelf.configuration.Configuration.*;
80 import java.io.IOException;
82 import java.net.InetAddress;
84 import java.io.BufferedInputStream;
86 import java.io.FileInputStream;
87 import java.io.FileOutputStream;
88 import java.io.IOException;
89 import java.io.InputStream;
90 import java.io.OutputStream;
91 import java.util.Properties;
93 import org.openecomp.appc.adapter.chef.chefapi.*;
94 import org.openecomp.appc.adapter.chef.chefclient.*;
97 import org.json.JSONArray;
98 import org.json.JSONException;
99 import org.json.JSONObject;
101 * This class implements the {@link ChefAdapter} interface. This interface
102 * defines the behaviors that our service provides.
104 public class ChefAdapterImpl implements ChefAdapter {
106 // chef server Initialize variable
107 public String username = "";
108 public String clientPrivatekey = "";
109 public String chefserver = "";
110 public String serverAddress = "";
111 public String organizations = "";
112 @SuppressWarnings("nls")
113 public static final String MDC_ADAPTER = "adapter";
115 @SuppressWarnings("nls")
116 public static final String MDC_SERVICE = "service";
118 @SuppressWarnings("nls")
119 public static final String OUTCOME_FAILURE = "failure";
121 @SuppressWarnings("nls")
122 public static final String OUTCOME_SUCCESS = "success";
124 @SuppressWarnings("nls")
125 public static final String PROPERTY_PROVIDER = "provider";
127 @SuppressWarnings("nls")
128 public static final String PROPERTY_PROVIDER_IDENTITY = "identity";
130 @SuppressWarnings("nls")
131 public static final String PROPERTY_PROVIDER_NAME = "name";
133 @SuppressWarnings("nls")
134 public static final String PROPERTY_PROVIDER_TENANT = "tenant";
136 @SuppressWarnings("nls")
137 public static final String PROPERTY_PROVIDER_TENANT_NAME = "name";
139 @SuppressWarnings("nls")
140 public static final String PROPERTY_PROVIDER_TENANT_PASSWORD = "password"; // NOSONAR
142 @SuppressWarnings("nls")
143 public static final String PROPERTY_PROVIDER_TENANT_USERID = "userid";
145 @SuppressWarnings("nls")
146 public static final String PROPERTY_PROVIDER_TYPE = "type";
149 private static final EELFLogger logger = EELFManager.getInstance().getLogger(ChefAdapterImpl.class);
151 private static final char LPAREN = '(';
153 private static final char NL = '\n';
155 private static final char QUOTE = '\'';
157 private static final char RPAREN = ')';
159 private static final char SPACE = ' ';
161 public ChefAdapterImpl() {
166 public ChefAdapterImpl(boolean initialize) {
174 public ChefAdapterImpl(Properties props) {
179 public ChefAdapterImpl(String key) {
186 public String getAdapterName() {
187 return "chef adapter";
191 @SuppressWarnings("nls")
193 public void VnfcEnvironment(Map<String, String> params, SvcLogicContext ctx) {
194 logger.info("environment of VNF-C");
196 RequestContext rc = new RequestContext(ctx);
198 String env = params.get("Environment");
200 chefServerResult(rc, "200", "Skip Environment block ");}
202 JSONObject env_J = new JSONObject(env);
203 String envName = env_J.getString("name");
205 String message = null;
206 if (privateKeyCheck()) {
207 // update the details of an environment on the Chef server.
208 ChefApiClient cac = new ChefApiClient(username, clientPrivatekey, chefserver, organizations);
209 ApiMethod am = cac.put("/environments/"+envName).body(env);
211 code = am.getReturnCode();
212 message = am.getResponseBodyAsString();
214 //need create a new environment
215 am = cac.post("/environments").body(env);
217 code = am.getReturnCode();
218 message = am.getResponseBodyAsString();
223 message = "Cannot find the private key in the APPC file system, please load the private key to "
226 chefServerResult(rc, Integer.toString(code), message);
231 @SuppressWarnings("nls")
233 public void VnfcNodeobjects(Map<String, String> params, SvcLogicContext ctx) {
234 logger.info("update the nodeObjects of VNF-C");
236 String nodeList_S = params.get("NodeList");
237 String node_S = params.get("Node");
238 nodeList_S = nodeList_S.replace("[","");
239 nodeList_S = nodeList_S.replace("]","");
240 nodeList_S = nodeList_S.replace("\"","");
241 nodeList_S = nodeList_S.replace(" ","");
242 List<String> nodes = Arrays.asList(nodeList_S.split("\\s*,\\s*"));
243 RequestContext rc = new RequestContext(ctx);
246 String message = null;
247 if (privateKeyCheck()) {
248 ChefApiClient cac = new ChefApiClient(username, clientPrivatekey, chefserver, organizations);
250 for(int i = 0; i < nodes.size(); i++){
251 String nodeName=nodes.get(i);
252 JSONObject node_J = new JSONObject(node_S);
253 node_J.remove("name");
254 node_J.put("name",nodeName);
255 String nodeObject=node_J.toString();
256 logger.info(nodeObject);
257 ApiMethod am = cac.put("/nodes/"+nodeName).body(nodeObject);
259 code = am.getReturnCode();
260 message = am.getResponseBodyAsString();
268 message = "Cannot find the private key in the APPC file system, please load the private key to "
271 chefServerResult(rc, Integer.toString(code), message);
275 @SuppressWarnings("nls")
277 public void VnfcPushJob(Map<String, String> params, SvcLogicContext ctx) {
279 String nodeList = params.get("NodeList");
280 String isCallback = params.get("CallbackCapable");
281 String chefAction = "/pushy/jobs";
283 String pushRequest="";
284 if(isCallback.equals("true")){
285 String requestId = params.get("RequestId");
286 String callbackUrl = params.get("CallbackUrl");
288 "\"command\": \"chef-client\","+
289 "\"run_timeout\": 300,"+
290 "\"nodes\":" +nodeList +","+
291 "\"env\": {\"RequestId\": \""+ requestId +"\", \"CallbackUrl\": \""+ callbackUrl +"\"},"+
292 "\"capture_output\": true"+
296 "\"command\": \"chef-client\","+
297 "\"run_timeout\": 300,"+
298 "\"nodes\":" +nodeList +","+
300 "\"capture_output\": true"+
303 RequestContext rc = new RequestContext(ctx);
306 SvcLogicContext svcLogic = rc.getSvcLogicContext();
307 ChefApiClient cac = new ChefApiClient(username, clientPrivatekey, chefserver, organizations);
308 ApiMethod am = cac.post(chefAction).body(pushRequest);
311 int code = am.getReturnCode();
312 String message = am.getResponseBodyAsString();
314 int startIndex = message.indexOf("jobs") + 5;
315 int endIndex = message.length() - 2;
316 String jobID = message.substring(startIndex, endIndex);
317 svcLogic.setAttribute("jobID", jobID);
320 chefServerResult(rc, Integer.toString(code), message);
324 @SuppressWarnings("nls")
326 public void fetchResults (Map<String, String> params, SvcLogicContext ctx) {
328 String nodeList_S = params.get("NodeList");
329 nodeList_S = nodeList_S.replace("[","");
330 nodeList_S = nodeList_S.replace("]","");
331 nodeList_S = nodeList_S.replace("\"","");
332 nodeList_S = nodeList_S.replace(" ","");
333 List<String> nodes = Arrays.asList(nodeList_S.split("\\s*,\\s*"));
334 JSONObject Result = new JSONObject();
335 String returnCode= "200";
336 String returnMessage="";
337 for (int i = 0; i < nodes.size(); i++){
338 String node=nodes.get(i);
339 String chefAction="/nodes/"+node;
341 String message = null;
342 if (privateKeyCheck()) {
343 ChefApiClient cac = new ChefApiClient(username, clientPrivatekey, chefserver, organizations);
344 ApiMethod am = cac.get(chefAction);
346 code = am.getReturnCode();
347 message = am.getResponseBodyAsString();
350 message = "Cannot find the private key in the APPC file system, please load the private key to "
354 JSONObject nodeResult = new JSONObject();
355 JSONObject allNodeData = new JSONObject(message);
356 String attribute= "PushJobOutput";
358 allNodeData=allNodeData.getJSONObject("normal");
360 resultData = allNodeData.getString(attribute);
361 } catch (Exception exc1) {
363 resultData = allNodeData.getJSONObject(attribute).toString();
364 } catch (Exception exc2) {
366 resultData = allNodeData.getJSONArray(attribute).toString();
367 }catch (Exception exc3){
369 returnMessage="cannot find "+attribute;
374 nodeResult.put(attribute,resultData);
376 Result.put(node,nodeResult);
379 returnMessage = message+" Cannot access: "+ node;
384 RequestContext rc = new RequestContext(ctx);
386 if (!returnCode.equals("500")){
387 returnMessage=Result.toString();
390 chefServerResult(rc, returnCode, returnMessage);
394 @SuppressWarnings("nls")
396 public void nodeObejctBuilder(Map<String, String> params, SvcLogicContext ctx) {
397 logger.info("nodeObejctBuilder");
398 String name = params.get("nodeobject.name");
399 String normal = params.get("nodeobject.normal");
400 String overrides = params.get("nodeobject.overrides");
401 String defaults = params.get("nodeobject.defaults");
402 String run_list = params.get("nodeobject.run_list");
403 String chef_environment = params.get("nodeobject.chef_environment");
404 String nodeObject = "{\"json_class\":\"Chef::Node\",\"default\":{" + defaults
405 + "},\"chef_type\":\"node\",\"run_list\":[" + run_list + "],\"override\":{" + overrides
406 + "},\"normal\": {" + normal + "},\"automatic\":{},\"name\":\"" + name + "\",\"chef_environment\":\""
407 + chef_environment + "\"}";
408 logger.info(nodeObject);
410 RequestContext rc = new RequestContext(ctx);
412 SvcLogicContext svcLogic = rc.getSvcLogicContext();
413 svcLogic.setAttribute("chef.nodeObject", nodeObject);
418 public void chefInfo(Map<String, String> params) {
419 username = params.get("username");
420 serverAddress = params.get("serverAddress");
421 organizations = params.get("organizations");
422 chefserver = "https://" + serverAddress + "/organizations/" + organizations;
423 clientPrivatekey = "/opt/app/bvc/chef/" + serverAddress + "/" + organizations + "/" + username + ".pem";
426 public Boolean privateKeyCheck() {
427 File f = new File(clientPrivatekey);
435 @SuppressWarnings("nls")
437 public void retrieveData(Map<String, String> params, SvcLogicContext ctx) {
438 String contextData = "someValue";
439 String allConfigData = params.get("allConfig");
440 String key = params.get("key");
441 String dgContext = params.get("dgContext");
442 JSONObject josnConfig = new JSONObject(allConfigData);
444 contextData = josnConfig.getString(key);
445 } catch (Exception ex) {
447 contextData = josnConfig.getJSONObject(key).toString();
448 } catch (Exception exc) {
449 contextData = josnConfig.getJSONArray(key).toString();
453 RequestContext rc = new RequestContext(ctx);
455 SvcLogicContext svcLogic = rc.getSvcLogicContext();
456 svcLogic.setAttribute(dgContext, contextData);
459 @SuppressWarnings("nls")
461 public void combineStrings(Map<String, String> params, SvcLogicContext ctx) {
463 String String1 = params.get("String1");
464 String String2 = params.get("String2");
465 String dgContext = params.get("dgContext");
466 String contextData = String1 + String2;
467 RequestContext rc = new RequestContext(ctx);
469 SvcLogicContext svcLogic = rc.getSvcLogicContext();
470 svcLogic.setAttribute(dgContext, contextData);
473 @SuppressWarnings("nls")
475 public void chefGet(Map<String, String> params, SvcLogicContext ctx) {
476 logger.info("chef get method");
478 String chefAction = params.get("chefAction");
479 RequestContext rc = new RequestContext(ctx);
482 String message = null;
483 if (privateKeyCheck()) {
484 ChefApiClient cac = new ChefApiClient(username, clientPrivatekey, chefserver, organizations);
485 ApiMethod am = cac.get(chefAction);
487 code = am.getReturnCode();
488 message = am.getResponseBodyAsString();
491 message = "Cannot find the private key in the APPC file system, please load the private key to "
494 chefServerResult(rc, Integer.toString(code), message);
499 * send put request to chef server
502 @SuppressWarnings("nls")
504 public void chefPut(Map<String, String> params, SvcLogicContext ctx) {
506 String chefAction = params.get("chefAction");
507 String CHEF_NODE_STR = params.get("chefRequestBody");
508 RequestContext rc = new RequestContext(ctx);
511 String message = null;
512 if (privateKeyCheck()) {
513 ChefApiClient cac = new ChefApiClient(username, clientPrivatekey, chefserver, organizations);
515 ApiMethod am = cac.put(chefAction).body(CHEF_NODE_STR);
517 code = am.getReturnCode();
518 message = am.getResponseBodyAsString();
521 message = "Cannot find the private key in the APPC file system, please load the private key to "
524 logger.info(code + " " + message);
525 chefServerResult(rc, Integer.toString(code), message);
529 * send Post request to chef server
532 @SuppressWarnings("nls")
534 public void chefPost(Map<String, String> params, SvcLogicContext ctx) {
536 logger.info("chef Post method");
537 logger.info(username + " " + clientPrivatekey + " " + chefserver + " " + organizations);
538 String CHEF_NODE_STR = params.get("chefRequestBody");
539 String chefAction = params.get("chefAction");
540 RequestContext rc = new RequestContext(ctx);
543 String message = null;
544 if (privateKeyCheck()) {
545 ChefApiClient cac = new ChefApiClient(username, clientPrivatekey, chefserver, organizations);
546 ApiMethod am = cac.post(chefAction).body(CHEF_NODE_STR);
548 code = am.getReturnCode();
549 message = am.getResponseBodyAsString();
552 message = "Cannot find the private key in the APPC file system, please load the private key to "
555 logger.info(code + " " + message);
556 chefServerResult(rc, Integer.toString(code), message);
560 @SuppressWarnings("nls")
562 public void chefDelete(Map<String, String> params, SvcLogicContext ctx) {
563 logger.info("chef delete method");
565 String chefAction = params.get("chefAction");
566 RequestContext rc = new RequestContext(ctx);
569 String message = null;
570 if (privateKeyCheck()) {
571 ChefApiClient cac = new ChefApiClient(username, clientPrivatekey, chefserver, organizations);
572 ApiMethod am = cac.delete(chefAction);
574 code = am.getReturnCode();
575 message = am.getResponseBodyAsString();
578 message = "Cannot find the private key in the APPC file system, please load the private key to "
581 logger.info(code + " " + message);
582 chefServerResult(rc, Integer.toString(code), message);
586 @SuppressWarnings("nls")
588 public void trigger(Map<String, String> params, SvcLogicContext ctx) {
589 logger.info("Run trigger method");
590 String tVmIp = params.get("ip");
591 // String tUrl = "http://" + tVmIp;
592 RequestContext rc = new RequestContext(ctx);
596 HttpGet httpGet = new HttpGet(tVmIp);
597 HttpClient httpClient = HttpClients.createDefault();
598 HttpResponse response = null;
599 response = httpClient.execute(httpGet);
600 int responseCode = response.getStatusLine().getStatusCode();
601 HttpEntity entity = response.getEntity();
602 String responseOutput = EntityUtils.toString(entity);
603 chefClientResult(rc, Integer.toString(responseCode), responseOutput);
605 } catch (Exception ex) {
606 doFailure(rc, 500, ex.toString());
610 @SuppressWarnings("nls")
612 public void checkPushJob(Map<String, String> params, SvcLogicContext ctx) {
614 String jobID = params.get("jobid");
615 int retryTimes = Integer.parseInt(params.get("retryTimes"));
616 int retryInterval = Integer.parseInt(params.get("retryInterval"));
617 String chefAction = "/pushy/jobs/" + jobID;
619 RequestContext rc = new RequestContext(ctx);
621 SvcLogicContext svcLogic = rc.getSvcLogicContext();
624 for (int i = 0; i < retryTimes; i++) {
626 Thread.sleep(retryInterval); // 1000 milliseconds is one second.
627 } catch (InterruptedException ex) {
628 Thread.currentThread().interrupt();
630 ChefApiClient cac = new ChefApiClient(username, clientPrivatekey, chefserver, organizations);
631 ApiMethod am = cac.get(chefAction);
633 int code = am.getReturnCode();
634 message = am.getResponseBodyAsString();
635 JSONObject obj = new JSONObject(message);
636 status = obj.getString("status");
637 if (!status.equals("running")) {
638 logger.info(i + " time " + code + " " + status);
643 if (status.equals("complete")) {
644 svcLogic.setAttribute("chefServerResult.code", "200");
645 svcLogic.setAttribute("chefServerResult.message", message);
647 if (status.equals("running")) {
648 svcLogic.setAttribute("chefServerResult.code", "202");
649 svcLogic.setAttribute("chefServerResult.message", "chef client runtime out");
651 svcLogic.setAttribute("chefServerResult.code", "500");
652 svcLogic.setAttribute("chefServerResult.message", message);
658 @SuppressWarnings("nls")
660 public void pushJob(Map<String, String> params, SvcLogicContext ctx) {
662 String pushRequest = params.get("pushRequest");
663 String chefAction = "/pushy/jobs";
664 RequestContext rc = new RequestContext(ctx);
666 SvcLogicContext svcLogic = rc.getSvcLogicContext();
667 ChefApiClient cac = new ChefApiClient(username, clientPrivatekey, chefserver, organizations);
668 ApiMethod am = cac.post(chefAction).body(pushRequest);
671 int code = am.getReturnCode();
672 String message = am.getResponseBodyAsString();
674 int startIndex = message.indexOf("jobs") + 6;
675 int endIndex = message.length() - 2;
676 String jobID = message.substring(startIndex, endIndex);
677 svcLogic.setAttribute("jobID", jobID);
680 chefServerResult(rc, Integer.toString(code), message);
684 @SuppressWarnings("static-method")
685 private void doFailure(RequestContext rc, int code, String message) {
686 SvcLogicContext svcLogic = rc.getSvcLogicContext();
687 String msg = (message == null) ? Integer.toString(code) : message;
688 if (msg.contains("\n")) {
689 msg = msg.substring(msg.indexOf("\n"));
694 status = Integer.toString(code);
695 } catch (Exception e) {
698 svcLogic.setAttribute("chefAgent.code", status);
699 svcLogic.setAttribute("chefAgent.message", msg);
703 @SuppressWarnings("static-method")
704 private void doSuccess(RequestContext rc) {
705 SvcLogicContext svcLogic = rc.getSvcLogicContext();
706 svcLogic.setAttribute("chefAgent.code", "200");
709 @SuppressWarnings("static-method")
710 private void chefServerResult(RequestContext rc, String code, String message) {
711 String msg = (message == null) ? " " : message;
712 SvcLogicContext svcLogic = rc.getSvcLogicContext();
713 svcLogic.setStatus(OUTCOME_SUCCESS);
714 svcLogic.setAttribute("chefServerResult.code", code);
715 svcLogic.setAttribute("chefServerResult.message", message);
718 @SuppressWarnings("static-method")
719 private void chefClientResult(RequestContext rc, String code, String message) {
720 String msg = (message == null) ? " " : message;
721 SvcLogicContext svcLogic = rc.getSvcLogicContext();
722 svcLogic.setStatus(OUTCOME_SUCCESS);
723 svcLogic.setAttribute("chefClientResult.code", code);
724 svcLogic.setAttribute("chefClientResult.message", message);
728 private void initialize() {
730 logger.info("init chef adapter!!!!!");