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