Merge of new rebased code
[appc.git] / appc-provider / appc-provider-bundle / src / main / java / org / openecomp / appc / provider / topology / TopologyService.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.provider.topology;
23
24 import static com.att.eelf.configuration.Configuration.MDC_ALERT_SEVERITY;
25 import static com.att.eelf.configuration.Configuration.MDC_INSTANCE_UUID;
26 import static com.att.eelf.configuration.Configuration.MDC_KEY_REQUEST_ID;
27 import static com.att.eelf.configuration.Configuration.MDC_REMOTE_HOST;
28 import static com.att.eelf.configuration.Configuration.MDC_SERVER_FQDN;
29 import static com.att.eelf.configuration.Configuration.MDC_SERVER_IP_ADDRESS;
30 import static com.att.eelf.configuration.Configuration.MDC_SERVICE_INSTANCE_ID;
31 import static com.att.eelf.configuration.Configuration.MDC_SERVICE_NAME;
32
33 import java.net.InetAddress;
34 import java.text.DateFormat;
35 import java.text.SimpleDateFormat;
36 import java.util.Date;
37 import java.util.Properties;
38 import java.util.TimeZone;
39
40 import org.opendaylight.yang.gen.v1.org.openecomp.appc.rev160104.MigrateOutput;
41 import org.opendaylight.yang.gen.v1.org.openecomp.appc.rev160104.ModifyConfigOutput;
42 import org.opendaylight.yang.gen.v1.org.openecomp.appc.rev160104.ModifyConfigOutputBuilder;
43 import org.opendaylight.yang.gen.v1.org.openecomp.appc.rev160104.MigrateOutputBuilder;
44 import org.opendaylight.yang.gen.v1.org.openecomp.appc.rev160104.RebuildOutput;
45 import org.opendaylight.yang.gen.v1.org.openecomp.appc.rev160104.RebuildOutputBuilder;
46 import org.opendaylight.yang.gen.v1.org.openecomp.appc.rev160104.RestartOutput;
47 import org.opendaylight.yang.gen.v1.org.openecomp.appc.rev160104.RestartOutputBuilder;
48 import org.opendaylight.yang.gen.v1.org.openecomp.appc.rev160104.SnapshotOutput;
49 import org.opendaylight.yang.gen.v1.org.openecomp.appc.rev160104.SnapshotOutputBuilder;
50 import org.opendaylight.yang.gen.v1.org.openecomp.appc.rev160104.UUID;
51 import org.opendaylight.yang.gen.v1.org.openecomp.appc.rev160104.common.request.header.CommonRequestHeader;
52 import org.opendaylight.yang.gen.v1.org.openecomp.appc.rev160104.vnf.resource.VnfResource;
53 import org.opendaylight.yang.gen.v1.org.openecomp.appc.rev160104.config.payload.ConfigPayload;
54 import org.opendaylight.yang.gen.v1.org.openecomp.appc.rev160104.VmstatuscheckOutput;
55 import org.opendaylight.yang.gen.v1.org.openecomp.appc.rev160104.VmstatuscheckOutputBuilder;
56 import org.opendaylight.yangtools.yang.common.RpcResult;
57 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
58 import org.openecomp.appc.Constants;
59 import org.openecomp.appc.configuration.Configuration;
60 import org.openecomp.appc.configuration.ConfigurationFactory;
61 import org.openecomp.appc.i18n.Msg;
62 import org.openecomp.appc.provider.AppcProvider;
63 import org.openecomp.appc.provider.AppcProviderClient;
64 import org.openecomp.appc.provider.ResponseHeaderBuilder;
65 import com.att.eelf.configuration.EELFLogger;
66 import com.att.eelf.configuration.EELFManager;
67 import com.att.eelf.i18n.EELFResourceManager;
68 import org.slf4j.MDC;
69
70 /**
71  * This class is used to implement the topology services API and invoke the appropriate directed graphs based on the
72  * service being requested.
73  * 
74  */
75 public class TopologyService {
76
77     /**
78      * The loggers we are using
79      */
80     // private static EELFLogger logger = LoggerFactory.getLogger(TopologyService.class);
81     private static EELFLogger logger = EELFManager.getInstance().getApplicationLogger();
82     private static EELFLogger securityLogger = EELFManager.getInstance().getSecurityLogger();
83     private static EELFLogger auditLogger = EELFManager.getInstance().getAuditLogger();
84     private static EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger();
85     private static EELFLogger performanceLogger = EELFManager.getInstance().getPerformanceLogger();
86
87     /**
88      * The provider we are servicing
89      */
90     private AppcProvider provider;
91
92     /**
93      * The reason associated with the last DG call
94      */
95     private String reason;
96
97     /**
98      * The APPC configuration properties
99      */
100     private Configuration configuration = ConfigurationFactory.getConfiguration();
101
102     /**
103      * Create the topology services implementation for the specific appc provider (api) implementation
104      * 
105      * @param provider
106      *            The provider we are servicing
107      */
108     public TopologyService(AppcProvider provider) {
109         this.provider = provider;
110     }
111
112     // /**
113     // * Processes the topology request
114     // *
115     // * @param input
116     // * The request to be processed
117     // * @return The result of processing
118     // */
119     // public RpcResult<TopologyOperationOutput> process(TopologyOperationInput input) {
120     // RpcResult<TopologyOperationOutput> response;
121     //
122     // String appName = configuration.getProperty(Constants.PROPERTY_APPLICATION_NAME);
123     // logger.info(String.format("%s:topology operations called...", appName));
124     //
125     // /*
126     // * Properties used to pass information to the DG
127     // */
128     // Properties properties = new Properties();
129     //
130     // if (input == null || input.getTopologyRequest().getVmId() == null) {
131     // String msg =
132     // String.format("%s: topology operation failed, invalid input. Null or empty argument '%s'", appName,
133     // "vm_id");
134     // logger.debug(msg);
135     // response = generateTopologyOperationResponse(Boolean.FALSE, "UNKNOWN", msg, "UNDEFINED");
136     // } else {
137     // // CommonRequestHeader crh = input.getCommonRequestHeader();
138     // TopologyHeader hdr = input.getTopologyHeader();
139     // TopologyRequest req = input.getTopologyRequest();
140     //
141     // // String requestId = crh.getServiceRequestId();
142     // String requestId = hdr.getSvcRequestId();
143     // properties.put(Constants.CONTEXT_REQID, requestId);
144     //
145     // String infomsg = String.format("Topology request '%s' (%s) received.", requestId, hdr.getSvcAction());
146     //
147     // // switch (req.getSvcAction()) {
148     // switch (hdr.getSvcAction()) {
149     // case Restart:
150     // properties.put(Constants.CONTEXT_SERVICE, Constants.SERVICE_RESTART);
151     // response = restart(input, properties);
152     // logger.info(infomsg);
153     // break;
154     //
155     // case Rebuild:
156     // properties.put(Constants.CONTEXT_SERVICE, Constants.SERVICE_REBUILD);
157     // response = rebuild(input, properties);
158     // logger.info(infomsg);
159     // break;
160     //
161     // default:
162     // String msg = String.format("Invalid request type [%s] for request id [%s]", req, requestId);
163     // response = generateTopologyOperationResponse(Boolean.FALSE, requestId, msg, "N/A");
164     // }
165     // }
166     //
167     // return response;
168     // }
169
170     /**
171      * Restart a VM
172      * 
173      * @param hdr
174      *            The common request header
175      * @param vnf
176      *            The identification of the VNF resource to be operated upon
177      * @return The rpc result of the restart operation
178      */
179     public RpcResult<ModifyConfigOutput> modifyConfig(CommonRequestHeader hdr, ConfigPayload data) {
180         long startTime = System.currentTimeMillis();
181         TimeZone tz = TimeZone.getTimeZone("UTC");
182         DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX");
183         df.setTimeZone(tz);
184         // String startTimeStr = String.valueOf(startTime);
185         String startTimeStr = df.format(new Date());
186         String requestId = hdr.getServiceRequestId();
187
188         //MDC.clear();
189         MDC.put(MDC_REMOTE_HOST, "");
190         MDC.put(MDC_KEY_REQUEST_ID, requestId);
191         MDC.put(MDC_SERVICE_NAME, "App-C Provider:Restart");
192         MDC.put(MDC_SERVICE_INSTANCE_ID, "");
193         try {
194             MDC.put(MDC_SERVER_FQDN, InetAddress.getLocalHost().getHostName());
195             MDC.put(MDC_SERVER_IP_ADDRESS, InetAddress.getLocalHost().getHostAddress());
196         } catch (Exception e) {
197             e.printStackTrace();
198         }
199         MDC.put(MDC_INSTANCE_UUID, java.util.UUID.randomUUID().toString());
200         MDC.put(MDC_ALERT_SEVERITY, "0");
201         MDC.put("startTime", Long.toString(startTime));
202         MDC.put("target", "appc");
203         logger.info(String.format("Starting RESTART for request with id [%s]", requestId));
204         metricsLogger.info(String.format("Metrics Logger: App-C Restart initiated. Start Time: [%s]. Request ID: [%s]",
205             startTime, requestId));
206
207         /*
208          * Copy any needed inputs or other values into the properties to be passed to the DG model
209          */
210         //UUID vmId = vnf.getVmId();
211         Properties properties = new Properties();
212         properties.put(Constants.CONTEXT_ACTION, "modifyConfig");
213         properties.put(Constants.CONTEXT_REQID, requestId);
214         //properties.put(Constants.CONTEXT_VMID, vmId.getValue());
215         String url = configuration.getProperty("appc.provider.vfodl.url");
216         try{
217         if(url.contains("NODE_NAME")){
218                 url = url.replace("NODE_NAME", data.getConfigUrl());
219         }
220         }catch(Exception e){
221                 url = configuration.getProperty("appc.provider.vfodl.url");
222         }
223         logger.trace("Final URL to VF ODL: "+url);
224         properties.put("org.openecomp.appc.configURL", url);
225         properties.put("org.openecomp.appc.configJson", data.getConfigJson());
226
227         //UUID identityUrl = vnf.getIdentityUrl();
228         //if (identityUrl != null) {
229         //    properties.put(Constants.CONTEXT_IDENTITY_URL, identityUrl.getValue());
230         //}
231         /*
232          * Attempt to call the DG with the appropriate properties
233          */
234         boolean success = callGraph(properties);
235
236  
237         MDC.put("target", "appc");
238         String statusStr = success ? "SUCCESS" : "FAILURE";
239         String infomsg =
240             String.format("APPC0119I ModifyConfig '%s' finished with status %s. Reason: %s", requestId, statusStr, reason);
241         logger.info(infomsg);
242
243         ModifyConfigOutputBuilder rob = new ModifyConfigOutputBuilder();
244         long endTime = System.currentTimeMillis();
245         long duration = endTime - startTime;
246         String endTimeStr = String.valueOf(endTime);
247         String durationStr = String.valueOf(duration);
248         MDC.put("endTime", endTimeStr);
249         MDC.put("duration", durationStr);
250         rob.setCommonResponseHeader(ResponseHeaderBuilder.buildHeader(success, requestId, reason, duration));
251         //rob.setVmId(new UUID(vmId));
252
253         auditLogger.info(String.format(
254             "Audit Logger: APPC0119I Restart '%s' finished with status %s. Start Time: [%s]. End Time: [%s]. Duration: [%s]. Request ID: [%s]. Reason:%s",
255             requestId, statusStr, startTime, endTime, duration, requestId, reason));
256         metricsLogger.info(String.format(
257             "Metrics Logger: APPC0119I Restart '%s' finished with status %s. Start Time: [%s]. End Time: [%s]. Duration: [%s]. Request ID: [%s]. Reason:%s",
258             requestId, statusStr, startTime, endTime, duration, requestId, reason));
259
260         // Status must be set to true to indicate that our return is expected
261         RpcResult<ModifyConfigOutput> rpcResult =
262             RpcResultBuilder.<ModifyConfigOutput> status(true).withResult(rob.build()).build();
263         return rpcResult;
264         
265     }
266     
267     
268     
269     
270     /**
271      * Restart a VM
272      * 
273      * @param hdr
274      *            The common request header
275      * @param vnf
276      *            The identification of the VNF resource to be operated upon
277      * @return The rpc result of the restart operation
278      */
279     public RpcResult<MigrateOutput> migrate(CommonRequestHeader hdr, VnfResource vnf) {
280         long startTime = System.currentTimeMillis();
281         TimeZone tz = TimeZone.getTimeZone("UTC");
282         DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX");
283         df.setTimeZone(tz);
284         // String startTimeStr = String.valueOf(startTime);
285         String startTimeStr = df.format(new Date());
286         String requestId = hdr.getServiceRequestId();
287
288         //MDC.clear();
289         MDC.put(MDC_REMOTE_HOST, "");
290         MDC.put(MDC_KEY_REQUEST_ID, requestId);
291         MDC.put(MDC_SERVICE_NAME, "App-C Provider:Migrate");
292         MDC.put(MDC_SERVICE_INSTANCE_ID, "");
293         try {
294             MDC.put(MDC_SERVER_FQDN, InetAddress.getLocalHost().getHostName());
295             MDC.put(MDC_SERVER_IP_ADDRESS, InetAddress.getLocalHost().getHostAddress());
296         } catch (Exception e) {
297             e.printStackTrace();
298         }
299         MDC.put(MDC_INSTANCE_UUID, java.util.UUID.randomUUID().toString());
300         MDC.put(MDC_ALERT_SEVERITY, "0");
301         MDC.put("startTime", startTimeStr);
302         MDC.put("target", "appc");
303         logger.info(String.format("Starting ANY for request with id [%s]", requestId));
304         metricsLogger.info(String.format("Metrics Logger: App-C Restart initiated. Start Time: [%s]. Request ID: [%s]",
305             startTime, requestId));
306
307         /*
308          * Copy any needed inputs or other values into the properties to be passed to the DG model
309          */
310         UUID vmId = vnf.getVmId();
311         Properties properties = new Properties();
312         properties.put(Constants.CONTEXT_ACTION, "migrate");
313         properties.put(Constants.CONTEXT_REQID, requestId);
314         properties.put(Constants.CONTEXT_VMID, vmId.getValue());
315
316         UUID identityUrl = vnf.getIdentityUrl();
317         if (identityUrl != null) {
318             properties.put(Constants.CONTEXT_IDENTITY_URL, identityUrl.getValue());
319         }
320
321         /*
322          * Attempt to call the DG with the appropriate properties
323          */
324         boolean success = callGraph(properties);
325
326         /*
327          * Generate the appropriate response
328          */
329         MDC.put("target", "appc");
330         String statusStr = success ? "SUCCESS" : "FAILURE";
331         String infomsg =
332             String.format("APPC0118I Migrate '%s' finished with status %s. Reason: %s", requestId, statusStr, reason);
333         logger.info(infomsg);
334
335         MigrateOutputBuilder mob = new MigrateOutputBuilder();
336
337         long endTime = System.currentTimeMillis();
338         long duration = endTime - startTime;
339         String endTimeStr = String.valueOf(endTime);
340         String durationStr = String.valueOf(duration);
341         MDC.put("endTime", endTimeStr);
342         MDC.put("duration", durationStr);
343         mob.setCommonResponseHeader(ResponseHeaderBuilder.buildHeader(success, requestId, reason, duration));
344         mob.setVmId(new UUID(vmId));
345
346         auditLogger.info(String.format(
347             "Audit Logger: APPC0118I Migrate '%s' finished with status %s. Start Time: [%s]. End Time: [%s]. Duration: [%s]. Request ID: [%s]. Reason:%s",
348             requestId, statusStr, startTime, endTime, duration, requestId, reason));
349         metricsLogger.info(String.format(
350             "Metrics Logger: APPC0118I Migrate '%s' finished with status %s. Start Time: [%s]. End Time: [%s]. Duration: [%s]. Request ID: [%s]. Reason:%s",
351             requestId, statusStr, startTime, endTime, duration, requestId, reason));
352
353         // Status must be set to true to indicate that our return is expected
354         RpcResult<MigrateOutput> rpcResult =
355             RpcResultBuilder.<MigrateOutput> status(true).withResult(mob.build()).build();
356         return rpcResult;
357     }
358
359     /**
360      * Restart a VM
361      * 
362      * @param hdr
363      *            The common request header
364      * @param vnf
365      *            The identification of the VNF resource to be operated upon
366      * @return The rpc result of the restart operation
367      */
368     public RpcResult<RestartOutput> restart(CommonRequestHeader hdr, VnfResource vnf) {
369         long startTime = System.currentTimeMillis();
370         TimeZone tz = TimeZone.getTimeZone("UTC");
371         DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX");
372         df.setTimeZone(tz);
373         // String startTimeStr = String.valueOf(startTime);
374         String startTimeStr = df.format(new Date());
375         String requestId = hdr.getServiceRequestId();
376
377         //MDC.clear();
378         MDC.put(MDC_REMOTE_HOST, "");
379         MDC.put(MDC_KEY_REQUEST_ID, requestId);
380         MDC.put(MDC_SERVICE_NAME, "App-C Provider:Restart");
381         MDC.put(MDC_SERVICE_INSTANCE_ID, "");
382         try {
383             MDC.put(MDC_SERVER_FQDN, InetAddress.getLocalHost().getHostName());
384             MDC.put(MDC_SERVER_IP_ADDRESS, InetAddress.getLocalHost().getHostAddress());
385         } catch (Exception e) {
386             e.printStackTrace();
387         }
388         MDC.put(MDC_INSTANCE_UUID, java.util.UUID.randomUUID().toString());
389         MDC.put(MDC_ALERT_SEVERITY, "0");
390         MDC.put("startTime", Long.toString(startTime));
391         MDC.put("target", "appc");
392         logger.info(String.format("Starting RESTART for request with id [%s]", requestId));
393         metricsLogger.info(String.format("Metrics Logger: App-C Restart initiated. Start Time: [%s]. Request ID: [%s]",
394             startTime, requestId));
395
396         /*
397          * Copy any needed inputs or other values into the properties to be passed to the DG model
398          */
399         UUID vmId = vnf.getVmId();
400         Properties properties = new Properties();
401         properties.put(Constants.CONTEXT_ACTION, "restart");
402         properties.put(Constants.CONTEXT_REQID, requestId);
403         properties.put(Constants.CONTEXT_VMID, vmId.getValue());
404
405         UUID identityUrl = vnf.getIdentityUrl();
406         if (identityUrl != null) {
407             properties.put(Constants.CONTEXT_IDENTITY_URL, identityUrl.getValue());
408         }
409         /*
410          * Attempt to call the DG with the appropriate properties
411          */
412         boolean success = callGraph(properties);
413
414         /*
415          * Generate the appropriate response
416          */
417         MDC.put("target", "appc");
418         String statusStr = success ? "SUCCESS" : "FAILURE";
419         String infomsg =
420             String.format("APPC0119I Restart '%s' finished with status %s. Reason: %s", requestId, statusStr, reason);
421         logger.info(infomsg);
422
423         RestartOutputBuilder rob = new RestartOutputBuilder();
424         long endTime = System.currentTimeMillis();
425         long duration = endTime - startTime;
426         String endTimeStr = String.valueOf(endTime);
427         String durationStr = String.valueOf(duration);
428         MDC.put("endTime", endTimeStr);
429         MDC.put("duration", durationStr);
430         rob.setCommonResponseHeader(ResponseHeaderBuilder.buildHeader(success, requestId, reason, duration));
431         rob.setVmId(new UUID(vmId));
432
433         auditLogger.info(String.format(
434             "Audit Logger: APPC0119I Restart '%s' finished with status %s. Start Time: [%s]. End Time: [%s]. Duration: [%s]. Request ID: [%s]. Reason:%s",
435             requestId, statusStr, startTime, endTime, duration, requestId, reason));
436         metricsLogger.info(String.format(
437             "Metrics Logger: APPC0119I Restart '%s' finished with status %s. Start Time: [%s]. End Time: [%s]. Duration: [%s]. Request ID: [%s]. Reason:%s",
438             requestId, statusStr, startTime, endTime, duration, requestId, reason));
439
440         // Status must be set to true to indicate that our return is expected
441         RpcResult<RestartOutput> rpcResult =
442             RpcResultBuilder.<RestartOutput> status(true).withResult(rob.build()).build();
443         return rpcResult;
444     }
445
446     /**
447      * Rebuild a VM
448      * 
449      * @param hdr
450      *            The common request header
451      * @param vnf
452      *            The identification of the VNF resource to be operated upon
453      * @return The rpc result of the rebuild operation
454      */
455     public RpcResult<RebuildOutput> rebuild(CommonRequestHeader hdr, VnfResource vnf) {
456         long startTime = System.currentTimeMillis();
457         TimeZone tz = TimeZone.getTimeZone("UTC");
458         DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX");
459         df.setTimeZone(tz);
460         // String startTimeStr = String.valueOf(startTime);
461         String startTimeStr = df.format(new Date());
462         String requestId = hdr.getServiceRequestId();
463
464         //MDC.clear();
465         MDC.put(MDC_REMOTE_HOST, "");
466         MDC.put(MDC_KEY_REQUEST_ID, requestId);
467         MDC.put(MDC_SERVICE_NAME, "App-C Provider:Rebuild");
468         MDC.put(MDC_SERVICE_INSTANCE_ID, "");
469         try {
470             MDC.put(MDC_SERVER_FQDN, InetAddress.getLocalHost().getHostName());
471             MDC.put(MDC_SERVER_IP_ADDRESS, InetAddress.getLocalHost().getHostAddress());
472         } catch (Exception e) {
473             e.printStackTrace();
474         }
475         MDC.put(MDC_INSTANCE_UUID, java.util.UUID.randomUUID().toString());
476         MDC.put(MDC_ALERT_SEVERITY, "0");
477         MDC.put("startTime", startTimeStr);
478         MDC.put("target", "appc");
479         logger.info(String.format("Starting REBUILD for request with id [%s]", requestId));
480         metricsLogger.info(String.format("Metrics Logger: App-C Restart initiated. Start Time: [%s]. Request ID: [%s]",
481             startTime, requestId));
482
483         /*
484          * Copy any needed inputs or other values into the properties to be passed to the DG model
485          */
486         UUID vmId = vnf.getVmId();
487         Properties properties = new Properties();
488         properties.put(Constants.CONTEXT_ACTION, "rebuild");
489         properties.put(Constants.CONTEXT_REQID, requestId);
490         properties.put(Constants.CONTEXT_VMID, vmId.getValue());
491
492         UUID identityUrl = vnf.getIdentityUrl();
493         if (identityUrl != null) {
494             properties.put(Constants.CONTEXT_IDENTITY_URL, identityUrl.getValue());
495         }
496
497         /*
498          * Attempt to call the DG with the appropriate properties
499          */
500         boolean success = callGraph(properties);
501
502         /*
503          * Generate the appropriate response
504          */
505         MDC.put("target", "appc");
506         String statusStr = success ? "SUCCESS" : "FAILURE";
507         String infomsg =
508             String.format("APPC0120I Rebuild '%s' finished with status %s. Reason: %s", requestId, statusStr, reason);
509         logger.info(infomsg);
510
511         RebuildOutputBuilder rob = new RebuildOutputBuilder();
512         long endTime = System.currentTimeMillis();
513         long duration = endTime - startTime;
514         String endTimeStr = String.valueOf(endTime);
515         String durationStr = String.valueOf(duration);
516         MDC.put("endTime", endTimeStr);
517         MDC.put("duration", durationStr);
518         rob.setCommonResponseHeader(ResponseHeaderBuilder.buildHeader(success, requestId, reason, duration));
519         rob.setOriginalVmId(new UUID(vmId));
520         rob.setNewVmId(new UUID(vmId));
521
522         auditLogger.info(String.format(
523             "Audit Logger: APPC0120I Rebuild '%s' finished with status %s. Start Time: [%s]. End Time: [%s]. Duration: [%s]. Request ID: [%s]. Reason:%s",
524             requestId, statusStr, startTime, endTime, duration, requestId, reason));
525         metricsLogger.info(String.format(
526             "Metrics Logger: APPC0120I Rebuild '%s' finished with status %s. Start Time: [%s]. End Time: [%s].  Duration: [%s]. Request ID: [%s]. Reason:%s",
527             requestId, statusStr, startTime, endTime, duration, requestId, reason));
528
529         // Status must be set to true to indicate that our return is expected
530         RpcResult<RebuildOutput> rpcResult =
531             RpcResultBuilder.<RebuildOutput> status(true).withResult(rob.build()).build();
532         return rpcResult;
533     }
534
535     /**
536      * Snapshot a VM
537      * 
538      * @param hdr
539      *            The common request header
540      * @param vnf
541      *            The identification of the VNF resource to be operated upon
542      * @return The rpc result of the restart operation
543      */
544     public RpcResult<SnapshotOutput> snapshot(CommonRequestHeader hdr, VnfResource vnf) {
545         long startTime = System.currentTimeMillis();
546         TimeZone tz = TimeZone.getTimeZone("UTC");
547         DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX");
548         df.setTimeZone(tz);
549         // String startTimeStr = String.valueOf(startTime);
550         String startTimeStr = df.format(new Date());
551         String requestId = hdr.getServiceRequestId();
552
553         //MDC.clear();
554         MDC.put(MDC_REMOTE_HOST, "");
555         MDC.put(MDC_KEY_REQUEST_ID, requestId);
556         MDC.put(MDC_SERVICE_NAME, "App-C Provider:Snapshot");
557         MDC.put(MDC_SERVICE_INSTANCE_ID, "");
558         try {
559             MDC.put(MDC_SERVER_FQDN, InetAddress.getLocalHost().getHostName());
560             MDC.put(MDC_SERVER_IP_ADDRESS, InetAddress.getLocalHost().getHostAddress());
561         } catch (Exception e) {
562             e.printStackTrace();
563         }
564         MDC.put(MDC_INSTANCE_UUID, java.util.UUID.randomUUID().toString());
565         MDC.put(MDC_ALERT_SEVERITY, "0");
566         MDC.put("startTime", Long.toString(startTime));
567         MDC.put("target", "appc");
568         logger.info(String.format("Starting SNAPSHOT for request with id [%s]", requestId));
569         metricsLogger.info(String.format("Metrics Logger: App-C Snapshot initiated. Start Time: [%s]. Request ID: [%s]",
570             startTime, requestId));
571
572         /*
573          * Copy any needed inputs or other values into the properties to be passed to the DG model
574          */
575         UUID vmId = vnf.getVmId();
576         Properties properties = new Properties();
577         properties.put(Constants.CONTEXT_ACTION, "snapshot");
578         properties.put(Constants.CONTEXT_REQID, requestId);
579         properties.put(Constants.CONTEXT_VMID, vmId.getValue());
580
581         UUID identityUrl = vnf.getIdentityUrl();
582         if (identityUrl != null) {
583             properties.put(Constants.CONTEXT_IDENTITY_URL, identityUrl.getValue());
584         }
585         /*
586          * Attempt to call the DG with the appropriate properties
587          */
588         boolean success = callGraph(properties);
589
590         /*
591          * Generate the appropriate response
592          */
593         MDC.put("target", "appc");
594         String statusStr = success ? "SUCCESS" : "FAILURE";
595         String infomsg =
596             String.format("APPC0119I Snapshot '%s' finished with status %s. Reason: %s", requestId, statusStr, reason);
597         logger.info(infomsg);
598
599         SnapshotOutputBuilder sob = new SnapshotOutputBuilder();
600         long endTime = System.currentTimeMillis();
601         long duration = endTime - startTime;
602         String endTimeStr = String.valueOf(endTime);
603         String durationStr = String.valueOf(duration);
604         MDC.put("endTime", endTimeStr);
605         MDC.put("duration", durationStr);
606         sob.setCommonResponseHeader(ResponseHeaderBuilder.buildHeader(success, requestId, reason, duration));
607         sob.setVmId(new UUID(vmId));
608
609         auditLogger.info(String.format(
610             "Audit Logger: APPC0119I Snapshot '%s' finished with status %s. Start Time: [%s]. End Time: [%s]. Duration: [%s]. Request ID: [%s]. Reason:%s",
611             requestId, statusStr, startTime, endTime, duration, requestId, reason));
612         metricsLogger.info(String.format(
613             "Metrics Logger: APPC0119I Snapshot '%s' finished with status %s. Start Time: [%s]. End Time: [%s]. Duration: [%s]. Request ID: [%s]. Reason:%s",
614             requestId, statusStr, startTime, endTime, duration, requestId, reason));
615
616         // Status must be set to true to indicate that our return is expected
617         RpcResult<SnapshotOutput> rpcResult =
618             RpcResultBuilder.<SnapshotOutput> status(true).withResult(sob.build()).build();
619         return rpcResult;
620     }
621     
622 /**************************************************/
623     
624     public RpcResult<VmstatuscheckOutput> vmstatuscheck(CommonRequestHeader hdr, VnfResource vnf) {
625         long startTime = System.currentTimeMillis();
626         String requestId = hdr.getServiceRequestId();
627
628         MDC.clear();
629         MDC.put(MDC_REMOTE_HOST, "");
630         MDC.put(MDC_KEY_REQUEST_ID, requestId);
631         MDC.put(MDC_SERVICE_NAME, "App-C Provider:vmstatuscheck");
632         MDC.put(MDC_SERVICE_INSTANCE_ID, "");
633         try {
634             MDC.put(MDC_SERVER_FQDN, InetAddress.getLocalHost().getHostName());
635             MDC.put(MDC_SERVER_IP_ADDRESS, InetAddress.getLocalHost().getHostAddress());
636         } catch (Exception e) {
637             e.printStackTrace();
638         }
639         MDC.put(MDC_INSTANCE_UUID, java.util.UUID.randomUUID().toString());
640         MDC.put(MDC_ALERT_SEVERITY, "0");
641         logger.info(String.format("Starting VMSTATUSCHECK for request with id [%s]", requestId));
642         
643         performanceLogger.info(String.format("Performance Logger: App-C vmstatuscheck initiated. Start Time: [%s]. Request ID: [%s]", startTime, requestId));
644         auditLogger.info(String.format("Audit Logger: App-C vmstatuscheck initiated. Start Time: [%s]. Request ID: [%s]", startTime, requestId));
645         metricsLogger.info(String.format("Metrics Logger: App-C vmstatuscheck initiated. Start Time: [%s]. Request ID: [%s]", startTime, requestId));
646
647         /*
648          * Copy any needed inputs or other values into the properties to be passed to the DG model
649          */
650         UUID vmId = vnf.getVmId();
651         Properties properties = new Properties();
652         properties.put(Constants.CONTEXT_ACTION, "vmstatuschecking");
653         properties.put(Constants.CONTEXT_REQID, requestId);
654         properties.put(Constants.CONTEXT_VMID, vmId.getValue());
655         properties.put(Constants.STATUS_GETTER, "checking");
656         
657        
658         
659
660         UUID identityUrl = vnf.getIdentityUrl();
661         if (identityUrl != null) {
662             properties.put(Constants.CONTEXT_IDENTITY_URL, identityUrl.getValue());
663         }
664         /*
665          * Attempt to call the DG with the appropriate properties
666          */
667         boolean success = callGraph(properties);
668
669         /*
670          * Generate the appropriate response
671          */
672         String statusStr = success ? "SUCCESS" : "FAILURE";
673         String infomsg =
674             String.format("VMSTATUSCHECK '%s' finished with status %s. Reason: %s", requestId, statusStr, reason);
675         logger.info(infomsg);
676         long endTime = System.currentTimeMillis();
677         auditLogger.info(String.format("Audit Logger: VMSTATUSCHECK '%s' finished with status %s. Start Time: [%s]. End Time: [%s]. Request ID: [%s]. Reason:%s", requestId, statusStr, startTime, endTime, requestId, reason));
678         metricsLogger.info(String.format("Metrics Logger: VMSTATUSCHECK '%s' finished with status %s. Start Time: [%s]. End Time: [%s]. Request ID: [%s]. Reason:%s", requestId, statusStr, startTime, endTime, requestId, reason));
679         //logger.info(String.format("Step1 [%s]", Constants.STATUS_GETTER));
680         String tempstring2 = properties.getProperty(Constants.STATUS_GETTER).trim();
681         //logger.info(String.format("Step2 [%s]", tempstring2));
682         
683         
684         VmstatuscheckOutputBuilder vob = new VmstatuscheckOutputBuilder();
685         long duration = System.currentTimeMillis() - startTime;
686         vob.setCommonResponseHeader(ResponseHeaderBuilder.buildHeader(success, requestId, reason, duration));
687         vob.setStatMsg(tempstring2);
688
689         // Status must be set to true to indicate that our return is expected
690         RpcResult<VmstatuscheckOutput> rpcResult =
691             RpcResultBuilder.<VmstatuscheckOutput> status(true).withResult(vob.build()).build();
692         return rpcResult;
693     }
694     
695     /*************************************************/
696     
697     
698
699     private boolean callGraph(Properties props) {
700         String moduleName = configuration.getProperty(Constants.PROPERTY_MODULE_NAME);
701         String methodName = configuration.getProperty(Constants.PROPERTY_TOPOLOGY_METHOD);
702         String version = configuration.getProperty(Constants.PROPERTY_TOPOLOGY_VERSION);
703         String mode = Constants.SYNC_MODE;
704         return callGraph(moduleName, methodName, version, mode, props);
705     }
706
707     /**
708      * Calls a specified directed graph with the specified properties and returns the response
709      * 
710      * @param module
711      *            The module name to be used to locate the graph
712      * @param method
713      *            The method name to be executed (rpc)
714      * @param version
715      *            The version of the graph to be used, or null for the latest
716      * @param mode
717      *            the execution mode of the graph, sync or async
718      * @param props
719      *            A set of name-value properties to be passed to the graph for context variables.
720      */
721     private boolean callGraph(String module, String method, String version, String mode, Properties props) {
722         String graphName = String.format(("%s:%s:%s"), module, method, version);
723         logger.debug(String.format("Calling Graph %s", graphName));
724         metricsLogger.info(String.format("Calling Graph %s", graphName));
725
726         boolean success = false;
727         String appName = configuration.getProperty(Constants.PROPERTY_APPLICATION_NAME);
728         AppcProviderClient svcLogicClient = new AppcProviderClient();
729         try {
730             if (svcLogicClient.hasGraph(module, method, version, mode)) {
731                 try {
732                     Properties respProps = svcLogicClient.execute(module, method, version, mode, props);
733                     success = false;        // Assume it failed unless proven otherwise
734                     reason = "Failed";      // Assume it failed unless proven otherwise
735
736                     logger.debug(EELFResourceManager.format(Msg.DEBUG_GRAPH_RESPONSE_HEADER, appName, graphName,
737                         Integer.toString(respProps.size())));
738                     for (String key : respProps.stringPropertyNames()) {
739                         logger.debug(EELFResourceManager.format(Msg.DEBUG_GRAPH_RESPONSE_DETAIL, appName, graphName,
740                             key, (String) respProps.get(key)));
741                     }
742
743                     // TODO - Find docs and see if there is a better way to handle this
744                     // Bad requests have errors
745                     if (respProps.containsKey(Constants.ATTRIBUTE_ERROR_CODE)) {
746                         // || respProps.containsKey(Constants.ATTRIBUTE_ERROR_MESSAGE)) {
747                         String errorCodeProperty = respProps.getProperty(Constants.ATTRIBUTE_ERROR_CODE).trim();
748                         int errorCode = 200;
749                         try {
750                             errorCode = Integer.parseInt(errorCodeProperty);
751                             if (errorCode >= 300) {
752                                 reason = EELFResourceManager.format(Msg.DG_FAILED_RESPONSE, appName, graphName,
753                                     errorCodeProperty, respProps.getProperty(Constants.ATTRIBUTE_ERROR_MESSAGE));
754                                 logger.error(reason);
755                                 success = false;
756                             } else {
757                                 success = true;
758                                 reason = "Success";
759                             }
760                         } catch (NumberFormatException e) {
761                             reason = EELFResourceManager.format(Msg.PARAMETER_NOT_NUMERIC, appName, graphName,
762                                 Constants.ATTRIBUTE_ERROR_CODE, errorCodeProperty);
763                             logger.error(reason);
764                             success = false;
765                         }
766                     } else {
767                         /*
768                          * Added code that requires error code to now be defined in ALL cases. If not, it is an error
769                          * and the response will be set to failed regardless if the DG worked or not.
770                          */
771                         reason = EELFResourceManager.format(Msg.PARAMETER_IS_MISSING, appName, graphName,
772                             Constants.ATTRIBUTE_ERROR_CODE);
773                         logger.error(reason);
774                         success = false;
775                     }
776                 } catch (Exception e) {
777                     success = false;
778                     reason = EELFResourceManager.format(Msg.EXCEPTION_CALLING_DG, e, appName,
779                         e.getClass().getSimpleName(), graphName, e.getMessage());
780                     logger.error(reason);
781                 }
782             } else {
783                 success = false;
784                 reason = EELFResourceManager.format(Msg.GRAPH_NOT_FOUND, appName, graphName);
785                 logger.error(reason);
786             }
787         } catch (Exception e) {
788             success = false;
789             reason = EELFResourceManager.format(Msg.EXCEPTION_CALLING_DG, e, appName, e.getClass().getSimpleName(),
790                 graphName, e.getMessage());
791             logger.error(reason);
792         }
793
794         return success;
795     }
796
797 }