Remove commented methods/fields in APPC
[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          * This default constructor is used as a work around because the activator
219          * wasnt getting called
220          */
221         public ChefAdapterImpl() {
222                 initialize();
223
224         }
225
226         /**
227          * This constructor is used primarily in the test cases to bypass
228          * initialization of the adapter for isolated, disconnected testing
229          * 
230          * @param initialize
231          *            True if the adapter is to be initialized, can false if not
232          */
233         public ChefAdapterImpl(boolean initialize) {
234                 configuration = ConfigurationFactory.getConfiguration();
235                 if (initialize) {
236                         initialize();
237
238                 }
239         }
240
241         /**
242          * @param props
243          *            not used
244          */
245         public ChefAdapterImpl(Properties props) {
246                 initialize();
247
248         }
249
250         public ChefAdapterImpl(String key) {
251                 initialize(key);
252
253         }
254         
255         /**
256          * Returns the symbolic name of the adapter
257          * 
258          * @return The adapter name
259          * @see org.openecomp.appc.adapter.chef.ChefAdapter#getAdapterName()
260          */
261         @Override
262         public String getAdapterName() {
263                 return configuration.getProperty(Constants.PROPERTY_ADAPTER_NAME);
264         }
265
266         private void X__________________________________X() {
267         }
268
269         /**
270          * @see org.openecomp.appc.adapter.chef.ChefAdapter#evacuateServer(java.util.Map,
271          *      org.openecomp.sdnc.sli.SvcLogicContext)
272          */
273
274         private void X___________________________________X() {
275         }
276
277         /**
278          * @see org.openecomp.appc.adapter.chef.ProviderAdapter#rebuildServer(java.util.Map,
279          *      org.openecomp.sdnc.sli.SvcLogicContext)
280          */
281
282         /**
283          * Send GET request to chef server
284          */
285
286         @SuppressWarnings("nls")
287         @Override
288         public void chefGet(Map<String, String> params, SvcLogicContext ctx) {
289                 logger.info("chef get method");
290                 String chefAction= params.get("org.openecomp.appc.instance.chefAction");
291                 RequestContext rc = new RequestContext(ctx);
292                 rc.isAlive();
293                 //should load pem from somewhere else
294                 ChefApiClient cac = new ChefApiClient(clientName,clientPrivatekey,chefserver,organizations);
295                 // need pass path into it
296                 //"/nodes"
297                 ApiMethod am = cac.get(chefAction);
298                 am.execute();
299                 int code = am.getReturnCode();
300                 String message = am.getResponseBodyAsString();
301                 logger.info(code + "   " + message);
302                 chefServerResult(rc,Integer.toString(code),message);
303         }
304
305         /**
306          * Send PUT request to chef server
307          */
308
309         @SuppressWarnings("nls")
310         @Override
311         public void chefPut(Map<String, String> params, SvcLogicContext ctx) {
312
313                 logger.info("chef PUT method");
314                 logger.info(clientName+" "+clientPrivatekey+" "+chefserver+" "+organizations);
315                 String chefAction= params.get("org.openecomp.appc.instance.chefAction");
316                 String runList= params.get("org.openecomp.appc.instance.runList");
317                 String attributes= params.get("org.openecomp.appc.instance.attributes");
318                 logger.info(attributes);
319                 String CHEF_NODE_STR = "{\"json_class\":\"Chef::Node\",\"default\":{},\"chef_type\":\"node\",\"run_list\":[\""+runList+"\"],\"override\":{},\"automatic\":{},\"normal\":{"+attributes+"},\"name\":\"testnode\",\"chef_environment\":\"_default\"}";
320                 RequestContext rc = new RequestContext(ctx);
321                 rc.isAlive();
322                 //should load pem from somewhere else
323                 ChefApiClient cac = new ChefApiClient(clientName,clientPrivatekey,chefserver,organizations);
324                 
325                 // need pass path into it
326                 //"/nodes/testnode"
327                 ApiMethod am = cac.put(chefAction).body(CHEF_NODE_STR);
328                 am.execute();
329                 int code = am.getReturnCode();
330                 String message = am.getResponseBodyAsString();
331                 logger.info(code + "   " + message);
332                 chefServerResult(rc,Integer.toString(code),message);
333         }
334         
335         
336         
337         /**
338          * Trigger target vm run chef
339          */
340
341         @SuppressWarnings("nls")
342         @Override
343         public void trigger(Map<String, String> params, SvcLogicContext ctx) {
344                 logger.info("Run trigger method");
345                 String tVmIp = params.get("org.openecomp.appc.instance.ip");
346                 RequestContext rc = new RequestContext(ctx);
347                 rc.isAlive();
348
349                 try {
350                         HttpGet httpGet = new HttpGet(tVmIp);
351                         HttpClient httpClient = HttpClients.createDefault();
352                         HttpResponse response = null;
353                         response = httpClient.execute(httpGet);
354                         int responseCode=response.getStatusLine().getStatusCode();
355                         HttpEntity entity = response.getEntity();
356                         String responseOutput=EntityUtils.toString(entity);
357                         chefClientResult(rc,Integer.toString(responseCode),responseOutput);
358                         doSuccess(rc);
359                 } catch (Exception ex) {
360                         doFailure(rc, 500 , ex.toString());
361                 }
362         }
363         
364
365
366         
367         @SuppressWarnings("static-method")
368         private void doFailure(RequestContext rc, int code, String message) {
369                 SvcLogicContext svcLogic = rc.getSvcLogicContext();
370                 String msg = (message == null) ? Integer.toString(code) : message;
371                 if (msg.contains("\n")) {
372                         msg = msg.substring(msg.indexOf("\n"));
373                 }
374
375                 String status;
376                 try {
377                         status = Integer.toString(code);
378                 } catch (Exception e) {
379                         status = "500";
380                 }
381                 svcLogic.setAttribute("org.openecomp.appc.chefAgent.code", status);
382                 svcLogic.setAttribute("org.openecomp.appc.chefAgent.message", msg);
383         }
384
385         /**
386          * @param rc
387          *            The request context that manages the state and recovery of the
388          *            request for the life of its processing.
389          */
390
391         @SuppressWarnings("static-method")
392         private void doSuccess(RequestContext rc) {
393                 SvcLogicContext svcLogic = rc.getSvcLogicContext();
394                 svcLogic.setAttribute("org.openecomp.appc.chefAgent.code", "200");
395         }
396         
397         
398         @SuppressWarnings("static-method")
399         private void chefServerResult(RequestContext rc, String code ,String message) {
400                 String msg = (message == null) ? " " : message;
401                 SvcLogicContext svcLogic = rc.getSvcLogicContext();
402                 svcLogic.setStatus(OUTCOME_SUCCESS);
403                 svcLogic.setAttribute("org.openecomp.appc.chefServerResult.code", code);
404                 svcLogic.setAttribute("org.openecomp.appc.chefServerResult.message", message);
405         }
406
407         @SuppressWarnings("static-method")
408         private void chefClientResult(RequestContext rc, String code ,String message) {
409                 String msg = (message == null) ? " " : message;
410                 SvcLogicContext svcLogic = rc.getSvcLogicContext();
411                 svcLogic.setStatus(OUTCOME_SUCCESS);
412                 svcLogic.setAttribute("org.openecomp.appc.chefClientResult.code", code);
413                 svcLogic.setAttribute("org.openecomp.appc.chefClientResult.message", message);
414         }
415
416         /**
417          * initialize the provider adapter by building the context cache
418          */
419         private void initialize() {
420                 configuration = ConfigurationFactory.getConfiguration();
421                 //need to fetch data from appc configurator or form some file in the appc vms
422                 clientName="testnode";
423             clientPrivatekey="/etc/chef/client.pem";
424             serverAddress="http://example.com";
425             organizations="test";    
426                 chefserver=serverAddress+"/organizations/"+organizations;       
427                 logger.info("Initialize Chef Adapter");
428         }
429         
430         private void initialize(String key) {
431                 configuration = ConfigurationFactory.getConfiguration();
432                 //need to fetch data from appc configurator or form some file in the appc vms
433                 clientName="testnode";
434             clientPrivatekey=key;
435             serverAddress="http://example.com";
436             organizations="test";    
437                 chefserver=serverAddress+"/organizations/"+organizations;       
438                 logger.info("Initialize Chef Adapter");
439         }
440
441 }