Change code in appc dispatcher for new LCMs in R6
[appc.git] / appc-dispatcher / appc-command-executor / appc-command-executor-core / src / main / java / org / onap / appc / executor / impl / CommandTask.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP : APPC
4  * ================================================================================
5  * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Copyright (C) 2017 Amdocs
8  * ================================================================================
9  * Modifications Copyright (C) 2019 Ericsson
10  * =============================================================================
11  * Licensed under the Apache License, Version 2.0 (the "License");
12  * you may not use this file except in compliance with the License.
13  * You may obtain a copy of the License at
14  *
15  *      http://www.apache.org/licenses/LICENSE-2.0
16  *
17  * Unless required by applicable law or agreed to in writing, software
18  * distributed under the License is distributed on an "AS IS" BASIS,
19  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20  * See the License for the specific language governing permissions and
21  * limitations under the License.
22  *
23  * ============LICENSE_END=========================================================
24  */
25
26 package org.onap.appc.executor.impl;
27
28 import com.att.eelf.configuration.Configuration;
29 import com.att.eelf.configuration.EELFLogger;
30 import com.att.eelf.configuration.EELFManager;
31 import java.net.InetAddress;
32 import java.util.UUID;
33 import org.onap.appc.domainmodel.lcm.CommonHeader;
34 import org.onap.appc.domainmodel.lcm.RequestContext;
35 import org.onap.appc.domainmodel.lcm.ResponseContext;
36 import org.onap.appc.domainmodel.lcm.RuntimeContext;
37 import org.onap.appc.domainmodel.lcm.Status;
38 import org.onap.appc.domainmodel.lcm.VNFOperation;
39 import org.onap.appc.executor.impl.objects.CommandRequest;
40 import org.onap.appc.logging.LoggingConstants;
41 import org.onap.appc.requesthandler.RequestHandler;
42 import org.onap.appc.workflow.WorkFlowManager;
43 import org.onap.appc.workflow.objects.WorkflowRequest;
44 import org.onap.ccsdk.sli.adaptors.aai.AAIRequest;
45 import org.onap.ccsdk.sli.adaptors.aai.AAIService;
46 import org.onap.ccsdk.sli.adaptors.aai.AAIServiceException;
47 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
48 import org.onap.ccsdk.sli.core.sli.SvcLogicException;
49 import org.onap.ccsdk.sli.core.sli.SvcLogicResource;
50 import org.osgi.framework.BundleContext;
51 import org.osgi.framework.FrameworkUtil;
52 import org.osgi.framework.ServiceReference;
53 import org.slf4j.MDC;
54
55
56 /**
57  * This abstract class is base class for all Command tasks. All command task must inherit this class.
58  */
59
60 public class CommandTask implements Runnable {
61
62     private RequestHandler requestHandler;
63     private WorkFlowManager workflowManager;
64     private CommandRequest commandRequest;
65     private AAIService aaiService;
66
67
68     public CommandRequest getCommandRequest() {
69         return commandRequest;
70     }
71
72     public void setCommandRequest(CommandRequest commandRequest) {
73         this.commandRequest = commandRequest;
74     }
75
76     private final EELFLogger logger = EELFManager.getInstance().getLogger(CommandTask.class);
77
78     public void setWorkflowManager(WorkFlowManager workflowManager) {
79         this.workflowManager = workflowManager;
80     }
81
82     public void setRequestHandler(RequestHandler requestHandler) {
83         this.requestHandler = requestHandler;
84     }
85
86     public CommandTask(RequestHandler requestHandler, WorkFlowManager workflowManager) {
87         this.requestHandler = requestHandler;
88         this.workflowManager = workflowManager;
89         getAAIservice();
90     }
91
92     private void getAAIservice() {
93         BundleContext bctx = FrameworkUtil.getBundle(AAIService.class).getBundleContext();
94         // Get AAIadapter reference
95         ServiceReference sref = bctx.getServiceReference(AAIService.class.getName());
96         if (sref != null) {
97             logger.info("AAIService from bundlecontext");
98             aaiService = (AAIService) bctx.getService(sref);
99         } else {
100             logger.info("AAIService error from bundlecontext");
101             logger.warn("Cannot find service reference for org.onap.ccsdk.sli.adaptors.aai.AAIService");
102         }
103     }
104
105
106     @Override
107     public void run() {
108         logger.debug("Starting execution of command: " + commandRequest);
109         setInitialLogProperties(commandRequest);
110         final RuntimeContext runtimeContext = commandRequest.getCommandExecutorInput().getRuntimeContext();
111
112         WorkflowRequest workflowRequest = new WorkflowRequest();
113         final RequestContext reqContext = runtimeContext.getRequestContext();
114         workflowRequest.setRequestContext(reqContext);
115         final ResponseContext respContext = runtimeContext.getResponseContext();
116         workflowRequest.setResponseContext(respContext);
117         workflowRequest.setVnfContext(runtimeContext.getVnfContext());
118         logger.debug("Executing workflow: " + workflowRequest);
119         workflowManager.executeWorkflow(workflowRequest);
120         logger.debug("Completed execution workflow with response: " + respContext);
121         try {
122             if (VNFOperation.Terminate == reqContext.getAction())
123                 updateAAIForTerminate(commandRequest);
124         } catch (AAIServiceException e) {
125             logger.error("Exception = " + e);
126             // In case of any errors we are updating the response status code and message
127             Status updatedStatus = new Status();
128             updatedStatus.setCode(401);
129             updatedStatus.setMessage("Failed to update VNF status in A&AI");
130             respContext.setStatus(updatedStatus);
131             throw new RuntimeException(e);
132         } finally {
133             requestHandler.onRequestExecutionEnd(runtimeContext);
134             clearRequestLogProperties();
135         }
136     }
137
138     private void updateAAIForTerminate(CommandRequest commandRequest) throws AAIServiceException {
139         final RuntimeContext runtimeContext = commandRequest.getCommandExecutorInput().getRuntimeContext();
140         final int statusCode = runtimeContext.getResponseContext().getStatus().getCode();
141
142         logger.debug("Workflow Execution Status = " + statusCode);
143         if (statusCode == 100 || statusCode == 400) {
144             String id = runtimeContext.getVnfContext().getId();
145             SvcLogicContext ctx = new SvcLogicContext();
146             ctx = getVnfdata(id, "vnf", ctx);
147             deleteGenericVnfData(id, ctx.getAttribute("vnf.resource-version"));
148         }
149     }
150
151     private SvcLogicContext getVnfdata(String vnf_id, String prefix, SvcLogicContext ctx) {
152         String key = "generic-vnf.vnf-id = '" + vnf_id + "'" + " AND http-header.Real-Time = 'true'";
153         logger.debug("inside getVnfdata=== " + key);
154         try {
155             SvcLogicResource.QueryStatus response =
156                     aaiService.query("generic-vnf", false, null, key, prefix, null, ctx);
157             if (SvcLogicResource.QueryStatus.NOT_FOUND.equals(response)) {
158                 logger.warn("VNF " + vnf_id + " not found while updating A&AI");
159                 throw new RuntimeException("VNF not found for vnf_id = " + vnf_id);
160             } else if (SvcLogicResource.QueryStatus.FAILURE.equals(response)) {
161                 throw new RuntimeException("Error Querying AAI with vnfID = " + vnf_id);
162             }
163             logger.info("AAIResponse: " + response.toString());
164         } catch (SvcLogicException e) {
165             logger.error("Error in getVnfdata " + e);
166             throw new RuntimeException(e);
167         }
168         return ctx;
169     }
170
171
172     private void setInitialLogProperties(CommandRequest request) {
173         RequestContext reqContext = request.getCommandExecutorInput().getRuntimeContext().getRequestContext();
174         CommonHeader reqHdr = reqContext.getCommonHeader();
175         String reqId = reqHdr.getRequestId();
176
177         try {
178             MDC.put(Configuration.MDC_KEY_REQUEST_ID, UUID.fromString(reqId).toString());
179             //reaching here without exception means existing RequestId is
180             //valid UUID as per ONAP logging standards
181         } catch (Exception e) {
182             String reqIdUUID = UUID.randomUUID().toString();
183             MDC.put(Configuration.MDC_KEY_REQUEST_ID, reqIdUUID);
184             logger.info("Replaced invalid requestID of " + reqId + ".  New value is " + reqIdUUID + ".");
185         }
186         String svcInstanceId = reqContext.getActionIdentifiers().getServiceInstanceId();
187         if (svcInstanceId != null) {
188             MDC.put(Configuration.MDC_SERVICE_INSTANCE_ID, svcInstanceId);
189             MDC.put(LoggingConstants.MDCKeys.PARTNER_NAME, reqHdr.getOriginatorId());
190             MDC.put(Configuration.MDC_SERVICE_NAME, reqContext.getAction().name());
191         }
192         try {
193             MDC.put(Configuration.MDC_SERVER_FQDN, InetAddress.getLocalHost().getCanonicalHostName());
194             MDC.put(Configuration.MDC_SERVER_IP_ADDRESS, InetAddress.getLocalHost().getHostAddress());
195         } catch (Exception e) {
196             logger.error(e.getMessage(), e);
197         }
198         MDC.put(Configuration.MDC_INSTANCE_UUID, ""); // confine instance_UUID generation to APPC-instance deployment
199     }
200
201     private void clearRequestLogProperties() {
202         try {
203             MDC.remove(Configuration.MDC_KEY_REQUEST_ID);
204             MDC.remove(Configuration.MDC_SERVICE_INSTANCE_ID);
205             MDC.remove(Configuration.MDC_SERVICE_NAME);
206             MDC.remove(LoggingConstants.MDCKeys.PARTNER_NAME);
207         } catch (Exception e) {
208             logger.error(e.getMessage(), e);
209         }
210     }
211
212     public boolean deleteGenericVnfData(String vnf_id, String resourceVersion) throws AAIServiceException {
213         boolean response = false;
214
215         try {
216             AAIRequest request = aaiService.getRequestFromResource("generic-vnf");
217             request.addRequestProperty("generic-vnf.vnf-id", vnf_id);
218             response = aaiService.delete(request, resourceVersion);
219         } catch (AAIServiceException aaiexc) {
220             throw aaiexc;
221         } catch (Exception exc) {
222             logger.warn("deleteGenericVnfData", exc);
223             throw new AAIServiceException(exc);
224         }
225         return response;
226     }
227 }