Moving all files to root directory
[appc.git] / appc-adapters / appc-chef-adapter / appc-chef-adapter-bundle / src / main / java / org / openecomp / appc / adapter / chef / impl / ChefAdapterImpl.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * openECOMP : APP-C
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights
6  *                                              reserved.
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
11  * 
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  * 
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  */
21
22 package org.openecomp.appc.adapter.chef.impl;
23
24 import java.net.URI;
25 import java.util.ArrayList;
26 import java.util.HashMap;
27 import java.util.List;
28 import java.util.Map;
29 import java.util.Properties;
30 import java.util.Set;
31 import java.util.regex.Pattern;
32
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;
64 import org.slf4j.MDC;
65
66 import java.net.InetAddress;
67 import java.util.Locale;
68 import java.util.UUID;
69
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;
75
76 import static com.att.eelf.configuration.Configuration.*;
77
78 import java.io.IOException;
79
80 import java.net.InetAddress;
81 /**
82  * This class implements the {@link ChefAdapter} interface. This interface
83  * defines the behaviors that our service provides.
84  */
85 public class ChefAdapterImpl implements ChefAdapter {
86
87         /**
88          * The constant used to define the adapter name in the mapped diagnostic
89          * context
90          */
91         
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";
100
101         /**
102          * The constant used to define the service name in the mapped diagnostic
103          * context
104          */
105         @SuppressWarnings("nls")
106         public static final String MDC_SERVICE = "service";
107
108         /**
109          * The constant for the status code for a failed outcome
110          */
111         @SuppressWarnings("nls")
112         public static final String OUTCOME_FAILURE = "failure";
113
114         /**
115          * The constant for the status code for a successful outcome
116          */
117         @SuppressWarnings("nls")
118         public static final String OUTCOME_SUCCESS = "success";
119
120         /**
121          * A constant for the property token "provider" used in the structured
122          * property specifications
123          */
124         @SuppressWarnings("nls")
125         public static final String PROPERTY_PROVIDER = "provider";
126
127         /**
128          * A constant for the property token "identity" used in the structured
129          * property specifications
130          */
131         @SuppressWarnings("nls")
132         public static final String PROPERTY_PROVIDER_IDENTITY = "identity";
133
134         /**
135          * A constant for the property token "name" used in the structured property
136          * specifications
137          */
138         @SuppressWarnings("nls")
139         public static final String PROPERTY_PROVIDER_NAME = "name";
140
141         /**
142          * A constant for the property token "tenant" used in the structured
143          * property specifications
144          */
145         @SuppressWarnings("nls")
146         public static final String PROPERTY_PROVIDER_TENANT = "tenant";
147
148         /**
149          * A constant for the property token "tenant name" used in the structured
150          * property specifications
151          */
152         @SuppressWarnings("nls")
153         public static final String PROPERTY_PROVIDER_TENANT_NAME = "name";
154
155         /**
156          * A constant for the property token "password" used in the structured
157          * property specifications
158          */
159         @SuppressWarnings("nls")
160         public static final String PROPERTY_PROVIDER_TENANT_PASSWORD = "password"; // NOSONAR
161
162         /**
163          * A constant for the property token "userid" used in the structured
164          * property specifications
165          */
166         @SuppressWarnings("nls")
167         public static final String PROPERTY_PROVIDER_TENANT_USERID = "userid";
168
169         /**
170          * A constant for the property token "type" used in the structured property
171          * specifications
172          */
173         @SuppressWarnings("nls")
174         public static final String PROPERTY_PROVIDER_TYPE = "type";
175
176         /**
177          * The name of the service to restart a server
178          */
179         @SuppressWarnings("nls")
180         public static final String PING_SERVICE = "pingServer";
181
182         /**
183          * The logger to be used
184          */
185         private static final EELFLogger logger = EELFManager.getInstance().getLogger(ChefAdapterImpl.class);
186
187         /**
188          * The constant for a left parenthesis
189          */
190         private static final char LPAREN = '(';
191
192         /**
193          * The constant for a new line control code
194          */
195         private static final char NL = '\n';
196
197         /**
198          * The constant for a single quote
199          */
200         private static final char QUOTE = '\'';
201
202         /**
203          * The constant for a right parenthesis
204          */
205         private static final char RPAREN = ')';
206
207         /**
208          * The constant for a space
209          */
210         private static final char SPACE = ' ';
211
212         /**
213          * A reference to the adapter configuration object.
214          */
215         private Configuration configuration;
216
217         /**
218          * A cache of providers that are predefined.
219          */
220         // private Map<String /* provider name */, ProviderCache> providerCache;
221
222         /**
223          * This default constructor is used as a work around because the activator
224          * wasnt getting called
225          */
226         public ChefAdapterImpl() {
227                 initialize();
228
229         }
230
231         /**
232          * This constructor is used primarily in the test cases to bypass
233          * initialization of the adapter for isolated, disconnected testing
234          * 
235          * @param initialize
236          *            True if the adapter is to be initialized, can false if not
237          */
238         public ChefAdapterImpl(boolean initialize) {
239                 configuration = ConfigurationFactory.getConfiguration();
240                 if (initialize) {
241                         initialize();
242
243                 }
244         }
245
246         /**
247          * @param props
248          *            not used
249          */
250         public ChefAdapterImpl(Properties props) {
251                 initialize();
252
253         }
254
255         public ChefAdapterImpl(String key) {
256                 initialize(key);
257
258         }
259         
260         /**
261          * Returns the symbolic name of the adapter
262          * 
263          * @return The adapter name
264          * @see org.openecomp.appc.adapter.chef.ChefAdapter#getAdapterName()
265          */
266         @Override
267         public String getAdapterName() {
268                 return configuration.getProperty(Constants.PROPERTY_ADAPTER_NAME);
269         }
270
271         private void X__________________________________X() {
272         }
273
274         /**
275          * @see org.openecomp.appc.adapter.chef.ChefAdapter#evacuateServer(java.util.Map,
276          *      org.openecomp.sdnc.sli.SvcLogicContext)
277          */
278
279         private void X___________________________________X() {
280         }
281
282         /**
283          * @see org.openecomp.appc.adapter.chef.ProviderAdapter#rebuildServer(java.util.Map,
284          *      org.openecomp.sdnc.sli.SvcLogicContext)
285          */
286
287         /**
288          * Send GET request to chef server
289          */
290
291         @SuppressWarnings("nls")
292         @Override
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);
298                 rc.isAlive();
299                 //should load pem from somewhere else
300                 ChefApiClient cac = new ChefApiClient(clientName,clientPrivatekey,chefserver,organizations);
301                 // need pass path into it
302                 //"/nodes"
303                 ApiMethod am = cac.get(chefAction);
304                 am.execute();
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) {
310                         doSuccess(rc);
311                 } else {
312                         String errorcode=code+" ";
313                         doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, errorcode);
314                 }*/
315
316         }
317
318         /**
319          * Send PUT request to chef server
320          */
321
322         @SuppressWarnings("nls")
323         @Override
324         public void chefPut(Map<String, String> params, SvcLogicContext ctx) {
325
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);
340                 rc.isAlive();
341                 //should load pem from somewhere else
342                 ChefApiClient cac = new ChefApiClient(clientName,clientPrivatekey,chefserver,organizations);
343                 
344                 // need pass path into it
345                 //"/nodes/testnode"
346                 ApiMethod am = cac.put(chefAction).body(CHEF_NODE_STR);
347                 am.execute();
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");
354                         doSuccess(rc);
355                 } else {
356                         String errorcode=code+" ";      
357                         logger.info("chef PUT method failure");
358                         doFailure(rc, HttpStatus.INTERNAL_SERVER_ERROR_500, errorcode);
359                 }*/
360
361         }
362         
363         
364         
365         /**
366          * Trigger target vm run chef
367          */
368
369         @SuppressWarnings("nls")
370         @Override
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);
376                 rc.isAlive();
377
378                 try {
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);
387                         doSuccess(rc);
388                 } catch (Exception ex) {
389                         doFailure(rc, 500 , ex.toString());
390                 }
391         }
392         
393
394
395         
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"));
402                 }
403
404                 String status;
405                 try {
406                         status = Integer.toString(code);
407                 } catch (Exception e) {
408                         status = "500";
409                 }
410                 svcLogic.setAttribute("org.openecomp.appc.chefAgent.code", status);
411                 svcLogic.setAttribute("org.openecomp.appc.chefAgent.message", msg);
412         }
413
414         /**
415          * @param rc
416          *            The request context that manages the state and recovery of the
417          *            request for the life of its processing.
418          */
419
420         @SuppressWarnings("static-method")
421         private void doSuccess(RequestContext rc) {
422                 SvcLogicContext svcLogic = rc.getSvcLogicContext();
423                 svcLogic.setAttribute("org.openecomp.appc.chefAgent.code", "200");
424         }
425         
426         
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);
434         }
435
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);
443         }
444
445         /**
446          * initialize the provider adapter by building the context cache
447          */
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");
457         }
458         
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");
468         }
469
470 }