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