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