2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights
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=========================================================
22 package org.openecomp.appc.adapter.chef.impl;
25 import java.util.ArrayList;
26 import java.util.HashMap;
27 import java.util.List;
29 import java.util.Properties;
31 import java.util.regex.Pattern;
33 import org.glassfish.grizzly.http.util.HttpStatus;
34 import org.openecomp.appc.Constants;
35 import org.openecomp.appc.adapter.chef.ChefAdapter;
36 import org.openecomp.appc.adapter.chef.chefapi.*;
37 import org.openecomp.appc.adapter.chef.chefclient.*;
38 import org.openecomp.appc.configuration.Configuration;
39 import org.openecomp.appc.configuration.ConfigurationFactory;
40 import org.openecomp.appc.exceptions.APPCException;
41 import org.openecomp.appc.exceptions.UnknownProviderException;
42 import org.openecomp.appc.i18n.Msg;
43 import org.openecomp.appc.pool.Pool;
44 import org.openecomp.appc.pool.PoolExtensionException;
45 import org.openecomp.appc.util.StructuredPropertyHelper;
46 import org.openecomp.appc.util.StructuredPropertyHelper.Node;
47 import com.att.cdp.exceptions.ContextConnectionException;
48 import com.att.cdp.exceptions.ResourceNotFoundException;
49 import com.att.cdp.exceptions.TimeoutException;
50 import com.att.cdp.exceptions.ZoneException;
51 import com.att.cdp.pal.util.StringHelper;
52 import com.att.cdp.zones.ComputeService;
53 import com.att.cdp.zones.Context;
54 import com.att.cdp.zones.ImageService;
55 import com.att.cdp.zones.Provider;
56 import com.att.cdp.zones.model.Image;
57 import com.att.cdp.zones.model.Server;
58 import com.att.cdp.zones.model.ServerBootSource;
59 import com.att.cdp.zones.model.Server.Status;
60 import com.att.eelf.configuration.EELFLogger;
61 import com.att.eelf.configuration.EELFManager;
62 import com.att.eelf.i18n.EELFResourceManager;
63 import org.openecomp.sdnc.sli.SvcLogicContext;
66 import java.net.InetAddress;
67 import java.util.Locale;
68 import java.util.UUID;
70 import org.apache.http.*;
71 import org.apache.http.client.*;
72 import org.apache.http.client.methods.*;
73 import org.apache.http.impl.client.*;
74 import org.apache.http.util.EntityUtils;
76 import static com.att.eelf.configuration.Configuration.*;
78 import java.io.IOException;
80 import java.net.InetAddress;
82 * This class implements the {@link ChefAdapter} interface. This interface
83 * defines the behaviors that our service provides.
85 public class ChefAdapterImpl implements ChefAdapter {
88 * The constant used to define the adapter name in the mapped diagnostic
92 //chef server Initialize variable
93 public String clientName="";
94 public String clientPrivatekey="";
95 public String chefserver="";
96 public String serverAddress="";
97 public String organizations="";
98 @SuppressWarnings("nls")
99 public static final String MDC_ADAPTER = "adapter";
102 * The constant used to define the service name in the mapped diagnostic
105 @SuppressWarnings("nls")
106 public static final String MDC_SERVICE = "service";
109 * The constant for the status code for a failed outcome
111 @SuppressWarnings("nls")
112 public static final String OUTCOME_FAILURE = "failure";
115 * The constant for the status code for a successful outcome
117 @SuppressWarnings("nls")
118 public static final String OUTCOME_SUCCESS = "success";
121 * A constant for the property token "provider" used in the structured
122 * property specifications
124 @SuppressWarnings("nls")
125 public static final String PROPERTY_PROVIDER = "provider";
128 * A constant for the property token "identity" used in the structured
129 * property specifications
131 @SuppressWarnings("nls")
132 public static final String PROPERTY_PROVIDER_IDENTITY = "identity";
135 * A constant for the property token "name" used in the structured property
138 @SuppressWarnings("nls")
139 public static final String PROPERTY_PROVIDER_NAME = "name";
142 * A constant for the property token "tenant" used in the structured
143 * property specifications
145 @SuppressWarnings("nls")
146 public static final String PROPERTY_PROVIDER_TENANT = "tenant";
149 * A constant for the property token "tenant name" used in the structured
150 * property specifications
152 @SuppressWarnings("nls")
153 public static final String PROPERTY_PROVIDER_TENANT_NAME = "name";
156 * A constant for the property token "password" used in the structured
157 * property specifications
159 @SuppressWarnings("nls")
160 public static final String PROPERTY_PROVIDER_TENANT_PASSWORD = "password"; // NOSONAR
163 * A constant for the property token "userid" used in the structured
164 * property specifications
166 @SuppressWarnings("nls")
167 public static final String PROPERTY_PROVIDER_TENANT_USERID = "userid";
170 * A constant for the property token "type" used in the structured property
173 @SuppressWarnings("nls")
174 public static final String PROPERTY_PROVIDER_TYPE = "type";
177 * The name of the service to restart a server
179 @SuppressWarnings("nls")
180 public static final String PING_SERVICE = "pingServer";
183 * The logger to be used
185 private static final EELFLogger logger = EELFManager.getInstance().getLogger(ChefAdapterImpl.class);
188 * The constant for a left parenthesis
190 private static final char LPAREN = '(';
193 * The constant for a new line control code
195 private static final char NL = '\n';
198 * The constant for a single quote
200 private static final char QUOTE = '\'';
203 * The constant for a right parenthesis
205 private static final char RPAREN = ')';
208 * The constant for a space
210 private static final char SPACE = ' ';
213 * A reference to the adapter configuration object.
215 private Configuration configuration;
218 * A cache of providers that are predefined.
220 // private Map<String /* provider name */, ProviderCache> providerCache;
223 * This default constructor is used as a work around because the activator
224 * wasnt getting called
226 public ChefAdapterImpl() {
232 * This constructor is used primarily in the test cases to bypass
233 * initialization of the adapter for isolated, disconnected testing
236 * True if the adapter is to be initialized, can false if not
238 public ChefAdapterImpl(boolean initialize) {
239 configuration = ConfigurationFactory.getConfiguration();
250 public ChefAdapterImpl(Properties props) {
255 public ChefAdapterImpl(String key) {
261 * Returns the symbolic name of the adapter
263 * @return The adapter name
264 * @see org.openecomp.appc.adapter.chef.ChefAdapter#getAdapterName()
267 public String getAdapterName() {
268 return configuration.getProperty(Constants.PROPERTY_ADAPTER_NAME);
271 private void X__________________________________X() {
275 * @see org.openecomp.appc.adapter.chef.ChefAdapter#evacuateServer(java.util.Map,
276 * org.openecomp.sdnc.sli.SvcLogicContext)
279 private void X___________________________________X() {
283 * @see org.openecomp.appc.adapter.chef.ProviderAdapter#rebuildServer(java.util.Map,
284 * org.openecomp.sdnc.sli.SvcLogicContext)
288 * Send GET request to chef server
291 @SuppressWarnings("nls")
293 public void chefGet(Map<String, String> params, SvcLogicContext ctx) {
294 logger.info("chef get method");
295 String chefAction= params.get("org.openecomp.appc.instance.chefAction");
296 // logger.info(vm_url);
297 RequestContext rc = new RequestContext(ctx);
299 //should load pem from somewhere else
300 ChefApiClient cac = new ChefApiClient(clientName,clientPrivatekey,chefserver,organizations);
301 // need pass path into it
303 ApiMethod am = cac.get(chefAction);
305 int code = am.getReturnCode();
306 String message = am.getResponseBodyAsString();
307 logger.info(code + " " + message);
308 chefServerResult(rc,Integer.toString(code),message);
309 /* if (code == 200) {
312 String errorcode=code+" ";
313 doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, errorcode);
319 * Send PUT request to chef server
322 @SuppressWarnings("nls")
324 public void chefPut(Map<String, String> params, SvcLogicContext ctx) {
326 //String tVmIp = params.get("org.openecomp.appc.instance.ip");
327 //logger.info(tVmIp);
328 logger.info("chef PUT method");
329 logger.info(clientName+" "+clientPrivatekey+" "+chefserver+" "+organizations);
330 //String CHEF_NODE_STR= params.get("org.openecomp.appc.instance.chefRequestBody");
331 String chefAction= params.get("org.openecomp.appc.instance.chefAction");
332 String runList= params.get("org.openecomp.appc.instance.runList");
333 String attributes= params.get("org.openecomp.appc.instance.attributes");
334 logger.info(attributes);
335 //attributes="\"reconfig-test\":{\"secret\":\"newpass2\"}";
336 String CHEF_NODE_STR = "{\"json_class\":\"Chef::Node\",\"default\":{},\"chef_type\":\"node\",\"run_list\":[\""+runList+"\"],\"override\":{},\"automatic\":{},\"normal\":{"+attributes+"},\"name\":\"testnode\",\"chef_environment\":\"_default\"}";
337 //String CHEF_NODE_STR = "{\"json_class\":\"Chef::Node\"}";
338 // logger.info(vm_url);
339 RequestContext rc = new RequestContext(ctx);
341 //should load pem from somewhere else
342 ChefApiClient cac = new ChefApiClient(clientName,clientPrivatekey,chefserver,organizations);
344 // need pass path into it
346 ApiMethod am = cac.put(chefAction).body(CHEF_NODE_STR);
348 int code = am.getReturnCode();
349 String message = am.getResponseBodyAsString();
350 logger.info(code + " " + message);
351 chefServerResult(rc,Integer.toString(code),message);
352 /* if (code == 200) {
353 logger.info("chef PUT method success");
356 String errorcode=code+" ";
357 logger.info("chef PUT method failure");
358 doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, errorcode);
366 * Trigger target vm run chef
369 @SuppressWarnings("nls")
371 public void trigger(Map<String, String> params, SvcLogicContext ctx) {
372 logger.info("Run trigger method");
373 String tVmIp = params.get("org.openecomp.appc.instance.ip");
374 //String tUrl = "http://" + tVmIp;
375 RequestContext rc = new RequestContext(ctx);
379 HttpGet httpGet = new HttpGet(tVmIp);
380 HttpClient httpClient = HttpClients.createDefault();
381 HttpResponse response = null;
382 response = httpClient.execute(httpGet);
383 int responseCode=response.getStatusLine().getStatusCode();
384 HttpEntity entity = response.getEntity();
385 String responseOutput=EntityUtils.toString(entity);
386 chefClientResult(rc,Integer.toString(responseCode),responseOutput);
388 } catch (Exception ex) {
389 doFailure(rc, 500 , ex.toString());
396 @SuppressWarnings("static-method")
397 private void doFailure(RequestContext rc, int code, String message) {
398 SvcLogicContext svcLogic = rc.getSvcLogicContext();
399 String msg = (message == null) ? Integer.toString(code) : message;
400 if (msg.contains("\n")) {
401 msg = msg.substring(msg.indexOf("\n"));
406 status = Integer.toString(code);
407 } catch (Exception e) {
410 svcLogic.setAttribute("org.openecomp.appc.chefAgent.code", status);
411 svcLogic.setAttribute("org.openecomp.appc.chefAgent.message", msg);
416 * The request context that manages the state and recovery of the
417 * request for the life of its processing.
420 @SuppressWarnings("static-method")
421 private void doSuccess(RequestContext rc) {
422 SvcLogicContext svcLogic = rc.getSvcLogicContext();
423 svcLogic.setAttribute("org.openecomp.appc.chefAgent.code", "200");
427 @SuppressWarnings("static-method")
428 private void chefServerResult(RequestContext rc, String code ,String message) {
429 String msg = (message == null) ? " " : message;
430 SvcLogicContext svcLogic = rc.getSvcLogicContext();
431 svcLogic.setStatus(OUTCOME_SUCCESS);
432 svcLogic.setAttribute("org.openecomp.appc.chefServerResult.code", code);
433 svcLogic.setAttribute("org.openecomp.appc.chefServerResult.message", message);
436 @SuppressWarnings("static-method")
437 private void chefClientResult(RequestContext rc, String code ,String message) {
438 String msg = (message == null) ? " " : message;
439 SvcLogicContext svcLogic = rc.getSvcLogicContext();
440 svcLogic.setStatus(OUTCOME_SUCCESS);
441 svcLogic.setAttribute("org.openecomp.appc.chefClientResult.code", code);
442 svcLogic.setAttribute("org.openecomp.appc.chefClientResult.message", message);
446 * initialize the provider adapter by building the context cache
448 private void initialize() {
449 configuration = ConfigurationFactory.getConfiguration();
450 //need to fetch data from appc configurator or form some file in the appc vms
451 clientName="testnode";
452 clientPrivatekey="/etc/chef/client.pem";
453 serverAddress="http://example.com";
454 organizations="test";
455 chefserver=serverAddress+"/organizations/"+organizations;
456 logger.info("Initialize Chef Adapter");
459 private void initialize(String key) {
460 configuration = ConfigurationFactory.getConfiguration();
461 //need to fetch data from appc configurator or form some file in the appc vms
462 clientName="testnode";
463 clientPrivatekey=key;
464 serverAddress="http://example.com";
465 organizations="test";
466 chefserver=serverAddress+"/organizations/"+organizations;
467 logger.info("Initialize Chef Adapter");