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