2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Copyright (C) 2017 Amdocs
8 * =============================================================================
9 * Licensed under the Apache License, Version 2.0 (the "License");
10 * you may not use this file except in compliance with the License.
11 * You may obtain a copy of the License at
13 * http://www.apache.org/licenses/LICENSE-2.0
15 * Unless required by applicable law or agreed to in writing, software
16 * distributed under the License is distributed on an "AS IS" BASIS,
17 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18 * See the License for the specific language governing permissions and
19 * limitations under the License.
21 * ECOMP is a trademark and service mark of AT&T Intellectual Property.
22 * ============LICENSE_END=========================================================
25 package org.openecomp.appc.adapter.chef.impl;
28 import java.util.ArrayList;
29 import java.util.HashMap;
30 import java.util.List;
32 import java.util.Properties;
34 import java.util.regex.Pattern;
38 import org.openecomp.appc.Constants;
39 import org.openecomp.appc.adapter.chef.ChefAdapter;
40 import org.openecomp.appc.adapter.chef.chefapi.*;
41 import org.openecomp.appc.adapter.chef.chefclient.*;
42 import org.openecomp.appc.configuration.Configuration;
43 import org.openecomp.appc.configuration.ConfigurationFactory;
44 import org.openecomp.appc.exceptions.APPCException;
45 import org.openecomp.appc.exceptions.UnknownProviderException;
46 import org.openecomp.appc.i18n.Msg;
47 import org.openecomp.appc.pool.Pool;
48 import org.openecomp.appc.pool.PoolExtensionException;
49 import org.openecomp.appc.util.StructuredPropertyHelper;
50 import org.openecomp.appc.util.StructuredPropertyHelper.Node;
51 import com.att.cdp.exceptions.ContextConnectionException;
52 import com.att.cdp.exceptions.ResourceNotFoundException;
53 import com.att.cdp.exceptions.TimeoutException;
54 import com.att.cdp.exceptions.ZoneException;
55 import com.att.cdp.pal.util.StringHelper;
56 import com.att.cdp.zones.ComputeService;
57 import com.att.cdp.zones.Context;
58 import com.att.cdp.zones.ImageService;
59 import com.att.cdp.zones.Provider;
60 import com.att.cdp.zones.model.Image;
61 import com.att.cdp.zones.model.Server;
62 import com.att.cdp.zones.model.ServerBootSource;
63 import com.att.cdp.zones.model.Server.Status;
64 import com.att.eelf.configuration.EELFLogger;
65 import com.att.eelf.configuration.EELFManager;
66 import com.att.eelf.i18n.EELFResourceManager;
67 import org.openecomp.sdnc.sli.SvcLogicContext;
70 import java.net.InetAddress;
71 import java.util.Locale;
72 import java.util.UUID;
74 import org.apache.http.*;
75 import org.apache.http.client.*;
76 import org.apache.http.client.methods.*;
77 import org.apache.http.impl.client.*;
78 import org.apache.http.util.EntityUtils;
80 import static com.att.eelf.configuration.Configuration.*;
82 import java.io.IOException;
84 import java.net.InetAddress;
86 import java.io.BufferedInputStream;
88 import java.io.FileInputStream;
89 import java.io.FileOutputStream;
90 import java.io.IOException;
91 import java.io.InputStream;
92 import java.io.OutputStream;
93 import java.util.Properties;
95 import org.openecomp.appc.adapter.chef.chefapi.*;
96 import org.openecomp.appc.adapter.chef.chefclient.*;
99 import org.json.JSONArray;
100 import org.json.JSONException;
101 import org.json.JSONObject;
103 * This class implements the {@link ChefAdapter} interface. This interface
104 * defines the behaviors that our service provides.
106 public class ChefAdapterImpl implements ChefAdapter {
108 // chef server Initialize variable
109 public String username = "";
110 public String clientPrivatekey = "";
111 public String chefserver = "";
112 public String serverAddress = "";
113 public String organizations = "";
114 @SuppressWarnings("nls")
115 public static final String MDC_ADAPTER = "adapter";
117 @SuppressWarnings("nls")
118 public static final String MDC_SERVICE = "service";
120 @SuppressWarnings("nls")
121 public static final String OUTCOME_FAILURE = "failure";
123 @SuppressWarnings("nls")
124 public static final String OUTCOME_SUCCESS = "success";
126 @SuppressWarnings("nls")
127 public static final String PROPERTY_PROVIDER = "provider";
129 @SuppressWarnings("nls")
130 public static final String PROPERTY_PROVIDER_IDENTITY = "identity";
132 @SuppressWarnings("nls")
133 public static final String PROPERTY_PROVIDER_NAME = "name";
135 @SuppressWarnings("nls")
136 public static final String PROPERTY_PROVIDER_TENANT = "tenant";
138 @SuppressWarnings("nls")
139 public static final String PROPERTY_PROVIDER_TENANT_NAME = "name";
141 @SuppressWarnings("nls")
142 public static final String PROPERTY_PROVIDER_TENANT_PASSWORD = "password"; // NOSONAR
144 @SuppressWarnings("nls")
145 public static final String PROPERTY_PROVIDER_TENANT_USERID = "userid";
147 @SuppressWarnings("nls")
148 public static final String PROPERTY_PROVIDER_TYPE = "type";
151 private static final EELFLogger logger = EELFManager.getInstance().getLogger(ChefAdapterImpl.class);
153 private static final char LPAREN = '(';
155 private static final char NL = '\n';
157 private static final char QUOTE = '\'';
159 private static final char RPAREN = ')';
161 private static final char SPACE = ' ';
163 public ChefAdapterImpl() {
168 public ChefAdapterImpl(boolean initialize) {
176 public ChefAdapterImpl(Properties props) {
181 public ChefAdapterImpl(String key) {
188 public String getAdapterName() {
189 return "chef adapter";
193 @SuppressWarnings("nls")
195 public void VnfcEnvironment(Map<String, String> params, SvcLogicContext ctx) {
196 logger.info("environment of VNF-C");
198 RequestContext rc = new RequestContext(ctx);
200 String env = params.get("Environment");
202 chefServerResult(rc, "200", "Skip Environment block ");}
204 JSONObject env_J = new JSONObject(env);
205 String envName = env_J.getString("name");
207 String message = null;
208 if (privateKeyCheck()) {
209 // update the details of an environment on the Chef server.
210 ChefApiClient cac = new ChefApiClient(username, clientPrivatekey, chefserver, organizations);
211 ApiMethod am = cac.put("/environments/"+envName).body(env);
213 code = am.getReturnCode();
214 message = am.getResponseBodyAsString();
216 //need create a new environment
217 am = cac.post("/environments").body(env);
219 code = am.getReturnCode();
220 message = am.getResponseBodyAsString();
225 message = "Cannot find the private key in the APPC file system, please load the private key to "
228 chefServerResult(rc, Integer.toString(code), message);
233 @SuppressWarnings("nls")
235 public void VnfcNodeobjects(Map<String, String> params, SvcLogicContext ctx) {
236 logger.info("update the nodeObjects of VNF-C");
238 String nodeList_S = params.get("NodeList");
239 String node_S = params.get("Node");
240 nodeList_S = nodeList_S.replace("[","");
241 nodeList_S = nodeList_S.replace("]","");
242 nodeList_S = nodeList_S.replace("\"","");
243 nodeList_S = nodeList_S.replace(" ","");
244 List<String> nodes = Arrays.asList(nodeList_S.split("\\s*,\\s*"));
245 RequestContext rc = new RequestContext(ctx);
248 String message = null;
249 if (privateKeyCheck()) {
250 ChefApiClient cac = new ChefApiClient(username, clientPrivatekey, chefserver, organizations);
252 for(int i = 0; i < nodes.size(); i++){
253 String nodeName=nodes.get(i);
254 JSONObject node_J = new JSONObject(node_S);
255 node_J.remove("name");
256 node_J.put("name",nodeName);
257 String nodeObject=node_J.toString();
258 logger.info(nodeObject);
259 ApiMethod am = cac.put("/nodes/"+nodeName).body(nodeObject);
261 code = am.getReturnCode();
262 message = am.getResponseBodyAsString();
270 message = "Cannot find the private key in the APPC file system, please load the private key to "
273 chefServerResult(rc, Integer.toString(code), message);
277 @SuppressWarnings("nls")
279 public void VnfcPushJob(Map<String, String> params, SvcLogicContext ctx) {
281 String nodeList = params.get("NodeList");
282 String isCallback = params.get("CallbackCapable");
283 String chefAction = "/pushy/jobs";
285 String pushRequest="";
286 if(isCallback.equals("true")){
287 String requestId = params.get("RequestId");
288 String callbackUrl = params.get("CallbackUrl");
290 "\"command\": \"chef-client\","+
291 "\"run_timeout\": 300,"+
292 "\"nodes\":" +nodeList +","+
293 "\"env\": {\"RequestId\": \""+ requestId +"\", \"CallbackUrl\": \""+ callbackUrl +"\"},"+
294 "\"capture_output\": true"+
298 "\"command\": \"chef-client\","+
299 "\"run_timeout\": 300,"+
300 "\"nodes\":" +nodeList +","+
302 "\"capture_output\": true"+
305 RequestContext rc = new RequestContext(ctx);
308 SvcLogicContext svcLogic = rc.getSvcLogicContext();
309 ChefApiClient cac = new ChefApiClient(username, clientPrivatekey, chefserver, organizations);
310 ApiMethod am = cac.post(chefAction).body(pushRequest);
313 int code = am.getReturnCode();
314 String message = am.getResponseBodyAsString();
316 int startIndex = message.indexOf("jobs") + 5;
317 int endIndex = message.length() - 2;
318 String jobID = message.substring(startIndex, endIndex);
319 svcLogic.setAttribute("jobID", jobID);
322 chefServerResult(rc, Integer.toString(code), message);
326 @SuppressWarnings("nls")
328 public void fetchResults (Map<String, String> params, SvcLogicContext ctx) {
330 String nodeList_S = params.get("NodeList");
331 nodeList_S = nodeList_S.replace("[","");
332 nodeList_S = nodeList_S.replace("]","");
333 nodeList_S = nodeList_S.replace("\"","");
334 nodeList_S = nodeList_S.replace(" ","");
335 List<String> nodes = Arrays.asList(nodeList_S.split("\\s*,\\s*"));
336 JSONObject Result = new JSONObject();
337 String returnCode= "200";
338 String returnMessage="";
339 for (int i = 0; i < nodes.size(); i++){
340 String node=nodes.get(i);
341 String chefAction="/nodes/"+node;
343 String message = null;
344 if (privateKeyCheck()) {
345 ChefApiClient cac = new ChefApiClient(username, clientPrivatekey, chefserver, organizations);
346 ApiMethod am = cac.get(chefAction);
348 code = am.getReturnCode();
349 message = am.getResponseBodyAsString();
352 message = "Cannot find the private key in the APPC file system, please load the private key to "
356 JSONObject nodeResult = new JSONObject();
357 JSONObject allNodeData = new JSONObject(message);
358 String attribute= "PushJobOutput";
360 allNodeData=allNodeData.getJSONObject("normal");
362 resultData = allNodeData.getString(attribute);
363 } catch (Exception exc1) {
365 resultData = allNodeData.getJSONObject(attribute).toString();
366 } catch (Exception exc2) {
368 resultData = allNodeData.getJSONArray(attribute).toString();
369 }catch (Exception exc3){
371 returnMessage="cannot find "+attribute;
376 nodeResult.put(attribute,resultData);
378 Result.put(node,nodeResult);
381 returnMessage = message+" Cannot access: "+ node;
386 RequestContext rc = new RequestContext(ctx);
388 if (!returnCode.equals("500")){
389 returnMessage=Result.toString();
392 chefServerResult(rc, returnCode, returnMessage);
396 @SuppressWarnings("nls")
398 public void nodeObejctBuilder(Map<String, String> params, SvcLogicContext ctx) {
399 logger.info("nodeObejctBuilder");
400 String name = params.get("nodeobject.name");
401 String normal = params.get("nodeobject.normal");
402 String overrides = params.get("nodeobject.overrides");
403 String defaults = params.get("nodeobject.defaults");
404 String run_list = params.get("nodeobject.run_list");
405 String chef_environment = params.get("nodeobject.chef_environment");
406 String nodeObject = "{\"json_class\":\"Chef::Node\",\"default\":{" + defaults
407 + "},\"chef_type\":\"node\",\"run_list\":[" + run_list + "],\"override\":{" + overrides
408 + "},\"normal\": {" + normal + "},\"automatic\":{},\"name\":\"" + name + "\",\"chef_environment\":\""
409 + chef_environment + "\"}";
410 logger.info(nodeObject);
412 RequestContext rc = new RequestContext(ctx);
414 SvcLogicContext svcLogic = rc.getSvcLogicContext();
415 svcLogic.setAttribute("chef.nodeObject", nodeObject);
420 public void chefInfo(Map<String, String> params) {
421 username = params.get("username");
422 serverAddress = params.get("serverAddress");
423 organizations = params.get("organizations");
424 chefserver = "https://" + serverAddress + "/organizations/" + organizations;
425 clientPrivatekey = "/opt/app/bvc/chef/" + serverAddress + "/" + organizations + "/" + username + ".pem";
428 public Boolean privateKeyCheck() {
429 File f = new File(clientPrivatekey);
437 @SuppressWarnings("nls")
439 public void retrieveData(Map<String, String> params, SvcLogicContext ctx) {
440 String contextData = "someValue";
441 String allConfigData = params.get("allConfig");
442 String key = params.get("key");
443 String dgContext = params.get("dgContext");
444 JSONObject josnConfig = new JSONObject(allConfigData);
446 contextData = josnConfig.getString(key);
447 } catch (Exception ex) {
449 contextData = josnConfig.getJSONObject(key).toString();
450 } catch (Exception exc) {
451 contextData = josnConfig.getJSONArray(key).toString();
455 RequestContext rc = new RequestContext(ctx);
457 SvcLogicContext svcLogic = rc.getSvcLogicContext();
458 svcLogic.setAttribute(dgContext, contextData);
461 @SuppressWarnings("nls")
463 public void combineStrings(Map<String, String> params, SvcLogicContext ctx) {
465 String String1 = params.get("String1");
466 String String2 = params.get("String2");
467 String dgContext = params.get("dgContext");
468 String contextData = String1 + String2;
469 RequestContext rc = new RequestContext(ctx);
471 SvcLogicContext svcLogic = rc.getSvcLogicContext();
472 svcLogic.setAttribute(dgContext, contextData);
475 @SuppressWarnings("nls")
477 public void chefGet(Map<String, String> params, SvcLogicContext ctx) {
478 logger.info("chef get method");
480 String chefAction = params.get("chefAction");
481 RequestContext rc = new RequestContext(ctx);
484 String message = null;
485 if (privateKeyCheck()) {
486 ChefApiClient cac = new ChefApiClient(username, clientPrivatekey, chefserver, organizations);
487 ApiMethod am = cac.get(chefAction);
489 code = am.getReturnCode();
490 message = am.getResponseBodyAsString();
493 message = "Cannot find the private key in the APPC file system, please load the private key to "
496 chefServerResult(rc, Integer.toString(code), message);
501 * send put request to chef server
504 @SuppressWarnings("nls")
506 public void chefPut(Map<String, String> params, SvcLogicContext ctx) {
508 String chefAction = params.get("chefAction");
509 String CHEF_NODE_STR = params.get("chefRequestBody");
510 RequestContext rc = new RequestContext(ctx);
513 String message = null;
514 if (privateKeyCheck()) {
515 ChefApiClient cac = new ChefApiClient(username, clientPrivatekey, chefserver, organizations);
517 ApiMethod am = cac.put(chefAction).body(CHEF_NODE_STR);
519 code = am.getReturnCode();
520 message = am.getResponseBodyAsString();
523 message = "Cannot find the private key in the APPC file system, please load the private key to "
526 logger.info(code + " " + message);
527 chefServerResult(rc, Integer.toString(code), message);
531 * send Post request to chef server
534 @SuppressWarnings("nls")
536 public void chefPost(Map<String, String> params, SvcLogicContext ctx) {
538 logger.info("chef Post method");
539 logger.info(username + " " + clientPrivatekey + " " + chefserver + " " + organizations);
540 String CHEF_NODE_STR = params.get("chefRequestBody");
541 String chefAction = params.get("chefAction");
542 RequestContext rc = new RequestContext(ctx);
545 String message = null;
546 if (privateKeyCheck()) {
547 ChefApiClient cac = new ChefApiClient(username, clientPrivatekey, chefserver, organizations);
548 ApiMethod am = cac.post(chefAction).body(CHEF_NODE_STR);
550 code = am.getReturnCode();
551 message = am.getResponseBodyAsString();
554 message = "Cannot find the private key in the APPC file system, please load the private key to "
557 logger.info(code + " " + message);
558 chefServerResult(rc, Integer.toString(code), message);
562 @SuppressWarnings("nls")
564 public void chefDelete(Map<String, String> params, SvcLogicContext ctx) {
565 logger.info("chef delete method");
567 String chefAction = params.get("chefAction");
568 RequestContext rc = new RequestContext(ctx);
571 String message = null;
572 if (privateKeyCheck()) {
573 ChefApiClient cac = new ChefApiClient(username, clientPrivatekey, chefserver, organizations);
574 ApiMethod am = cac.delete(chefAction);
576 code = am.getReturnCode();
577 message = am.getResponseBodyAsString();
580 message = "Cannot find the private key in the APPC file system, please load the private key to "
583 logger.info(code + " " + message);
584 chefServerResult(rc, Integer.toString(code), message);
588 @SuppressWarnings("nls")
590 public void trigger(Map<String, String> params, SvcLogicContext ctx) {
591 logger.info("Run trigger method");
592 String tVmIp = params.get("ip");
593 // String tUrl = "http://" + tVmIp;
594 RequestContext rc = new RequestContext(ctx);
598 HttpGet httpGet = new HttpGet(tVmIp);
599 HttpClient httpClient = HttpClients.createDefault();
600 HttpResponse response = null;
601 response = httpClient.execute(httpGet);
602 int responseCode = response.getStatusLine().getStatusCode();
603 HttpEntity entity = response.getEntity();
604 String responseOutput = EntityUtils.toString(entity);
605 chefClientResult(rc, Integer.toString(responseCode), responseOutput);
607 } catch (Exception ex) {
608 doFailure(rc, 500, ex.toString());
612 @SuppressWarnings("nls")
614 public void checkPushJob(Map<String, String> params, SvcLogicContext ctx) {
616 String jobID = params.get("jobid");
617 int retryTimes = Integer.parseInt(params.get("retryTimes"));
618 int retryInterval = Integer.parseInt(params.get("retryInterval"));
619 String chefAction = "/pushy/jobs/" + jobID;
621 RequestContext rc = new RequestContext(ctx);
623 SvcLogicContext svcLogic = rc.getSvcLogicContext();
626 for (int i = 0; i < retryTimes; i++) {
628 Thread.sleep(retryInterval); // 1000 milliseconds is one second.
629 } catch (InterruptedException ex) {
630 Thread.currentThread().interrupt();
632 ChefApiClient cac = new ChefApiClient(username, clientPrivatekey, chefserver, organizations);
633 ApiMethod am = cac.get(chefAction);
635 int code = am.getReturnCode();
636 message = am.getResponseBodyAsString();
637 JSONObject obj = new JSONObject(message);
638 status = obj.getString("status");
639 if (!status.equals("running")) {
640 logger.info(i + " time " + code + " " + status);
645 if (status.equals("complete")) {
646 svcLogic.setAttribute("chefServerResult.code", "200");
647 svcLogic.setAttribute("chefServerResult.message", message);
649 if (status.equals("running")) {
650 svcLogic.setAttribute("chefServerResult.code", "202");
651 svcLogic.setAttribute("chefServerResult.message", "chef client runtime out");
653 svcLogic.setAttribute("chefServerResult.code", "500");
654 svcLogic.setAttribute("chefServerResult.message", message);
660 @SuppressWarnings("nls")
662 public void pushJob(Map<String, String> params, SvcLogicContext ctx) {
664 String pushRequest = params.get("pushRequest");
665 String chefAction = "/pushy/jobs";
666 RequestContext rc = new RequestContext(ctx);
668 SvcLogicContext svcLogic = rc.getSvcLogicContext();
669 ChefApiClient cac = new ChefApiClient(username, clientPrivatekey, chefserver, organizations);
670 ApiMethod am = cac.post(chefAction).body(pushRequest);
673 int code = am.getReturnCode();
674 String message = am.getResponseBodyAsString();
676 int startIndex = message.indexOf("jobs") + 6;
677 int endIndex = message.length() - 2;
678 String jobID = message.substring(startIndex, endIndex);
679 svcLogic.setAttribute("jobID", jobID);
682 chefServerResult(rc, Integer.toString(code), message);
686 @SuppressWarnings("static-method")
687 private void doFailure(RequestContext rc, int code, String message) {
688 SvcLogicContext svcLogic = rc.getSvcLogicContext();
689 String msg = (message == null) ? Integer.toString(code) : message;
690 if (msg.contains("\n")) {
691 msg = msg.substring(msg.indexOf("\n"));
696 status = Integer.toString(code);
697 } catch (Exception e) {
700 svcLogic.setAttribute("chefAgent.code", status);
701 svcLogic.setAttribute("chefAgent.message", msg);
705 @SuppressWarnings("static-method")
706 private void doSuccess(RequestContext rc) {
707 SvcLogicContext svcLogic = rc.getSvcLogicContext();
708 svcLogic.setAttribute("chefAgent.code", "200");
711 @SuppressWarnings("static-method")
712 private void chefServerResult(RequestContext rc, String code, String message) {
713 String msg = (message == null) ? " " : message;
714 SvcLogicContext svcLogic = rc.getSvcLogicContext();
715 svcLogic.setStatus(OUTCOME_SUCCESS);
716 svcLogic.setAttribute("chefServerResult.code", code);
717 svcLogic.setAttribute("chefServerResult.message", message);
720 @SuppressWarnings("static-method")
721 private void chefClientResult(RequestContext rc, String code, String message) {
722 String msg = (message == null) ? " " : message;
723 SvcLogicContext svcLogic = rc.getSvcLogicContext();
724 svcLogic.setStatus(OUTCOME_SUCCESS);
725 svcLogic.setAttribute("chefClientResult.code", code);
726 svcLogic.setAttribute("chefClientResult.message", message);
730 private void initialize() {
732 logger.info("init chef adapter!!!!!");