cfd4ff8d03a59043a17f6549b319194cfb412d6c
[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 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.Status;
34 import org.onap.appc.domainmodel.lcm.VNFOperation;
35 import org.onap.appc.executor.impl.objects.CommandRequest;
36 import org.onap.appc.logging.LoggingConstants;
37 import org.onap.appc.requesthandler.RequestHandler;
38 import org.onap.appc.domainmodel.lcm.RuntimeContext;
39 import org.onap.appc.workflow.WorkFlowManager;
40 import org.onap.appc.workflow.objects.WorkflowRequest;
41 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
42 import org.onap.ccsdk.sli.core.sli.SvcLogicException;
43 import org.onap.ccsdk.sli.core.sli.SvcLogicResource;
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.osgi.framework.BundleContext;
48 import org.osgi.framework.FrameworkUtil;
49 import org.osgi.framework.ServiceReference;
50 import org.slf4j.MDC;
51
52
53
54 /**
55  * This abstract class is base class for all Command tasks. All command task must inherit this class.
56  */
57
58 public class CommandTask implements Runnable {
59
60     private RequestHandler requestHandler;
61     private WorkFlowManager workflowManager;
62     private CommandRequest commandRequest;
63     private AAIService aaiService;
64
65
66     public CommandRequest getCommandRequest() {
67         return commandRequest;
68     }
69
70     public void setCommandRequest(CommandRequest commandRequest) {
71         this.commandRequest = commandRequest;
72     }
73
74     private final EELFLogger logger = EELFManager.getInstance().getLogger(CommandTask.class);
75
76     public void setWorkflowManager(WorkFlowManager workflowManager) {
77         this.workflowManager = workflowManager;
78     }
79
80     public void setRequestHandler(RequestHandler requestHandler) {
81         this.requestHandler = requestHandler;
82     }
83
84     public CommandTask(RequestHandler requestHandler,
85                        WorkFlowManager workflowManager){
86         this.requestHandler = requestHandler;
87         this.workflowManager = workflowManager;
88         getAAIservice();
89     }
90
91     private void getAAIservice() {
92         BundleContext bctx = FrameworkUtil.getBundle(AAIService.class).getBundleContext();
93         // Get AAIadapter reference
94         ServiceReference sref = bctx.getServiceReference(AAIService.class.getName());
95         if (sref != null) {
96             logger.info("AAIService from bundlecontext");
97             aaiService = (AAIService) bctx.getService(sref);
98         } else {
99             logger.info("AAIService error from bundlecontext");
100             logger.warn("Cannot find service reference for org.onap.ccsdk.sli.adaptors.aai.AAIService");
101         }
102     }
103
104
105     @Override
106     public void run() {
107         logger.debug("Starting execution of command :" + commandRequest);
108         setInitialLogProperties(commandRequest);
109         final RuntimeContext runtimeContext = commandRequest.getCommandExecutorInput().getRuntimeContext();
110
111         WorkflowRequest workflowRequest = new WorkflowRequest();
112         workflowRequest.setRequestContext(runtimeContext.getRequestContext());
113         workflowRequest.setResponseContext(runtimeContext.getResponseContext());
114         workflowRequest.setVnfContext(runtimeContext.getVnfContext());
115         logger.debug("Executing workflow :" + workflowRequest);
116         workflowManager.executeWorkflow(workflowRequest);
117         logger.debug("Completed execution workflow with response:"+ commandRequest.getCommandExecutorInput().getRuntimeContext().getResponseContext());
118         try {
119             if (VNFOperation.Terminate ==  commandRequest.getCommandExecutorInput().getRuntimeContext().getRequestContext().getAction())
120                 updateAAIForTerminate(commandRequest);
121         } catch (AAIServiceException e) {
122             logger.error("Exception = " + e);
123             // In case of any errors we are updating the response status code and message
124             Status updatedStatus = new Status();
125             updatedStatus.setCode(401);
126             updatedStatus.setMessage("Failed to update VNF status in A&AI");
127             commandRequest.getCommandExecutorInput().getRuntimeContext().getResponseContext().setStatus(updatedStatus);
128             throw new RuntimeException(e);
129         }finally {
130             requestHandler.onRequestExecutionEnd(commandRequest.getCommandExecutorInput().getRuntimeContext());
131             clearRequestLogProperties();
132         }
133     }
134
135     private void updateAAIForTerminate(CommandRequest commandRequest) throws AAIServiceException {
136         final int statusCode = commandRequest.getCommandExecutorInput().getRuntimeContext().getResponseContext().getStatus().getCode();
137
138         logger.debug("Workflow Execution Status = "+ statusCode);
139         if (statusCode == 100 || statusCode == 400) {
140             SvcLogicContext ctx = new SvcLogicContext();
141             ctx = getVnfdata(commandRequest.getCommandExecutorInput().getRuntimeContext().getVnfContext().getId(), "vnf", ctx);
142             deleteGenericVnfData(commandRequest.getCommandExecutorInput().getRuntimeContext().getVnfContext().getId(),
143                     ctx.getAttribute("vnf.resource-version"));
144         }
145     }
146
147     private SvcLogicContext getVnfdata(String vnf_id, String prefix,SvcLogicContext ctx) {
148         String key="generic-vnf.vnf-id = '" + vnf_id + "'" + " AND http-header.Real-Time = 'true'";
149         logger.debug("inside getVnfdata=== " + key);
150         try {
151             SvcLogicResource.QueryStatus response = aaiService.query("generic-vnf", false, null, key,prefix, null, ctx);
152             if(SvcLogicResource.QueryStatus.NOT_FOUND.equals(response)){
153                 logger.warn("VNF " + vnf_id + " not found while updating A&AI");
154                 throw new RuntimeException("VNF not found for vnf_id = " + vnf_id);
155             }
156             else if(SvcLogicResource.QueryStatus.FAILURE.equals(response)){
157                 throw new RuntimeException("Error Querying AAI with vnfID = " + vnf_id);
158             }
159             logger.info("AAIResponse: " + response.toString());
160         } catch (SvcLogicException e) {
161             logger.error("Error in getVnfdata " + e);
162             throw new RuntimeException(e);
163         }
164         return ctx;
165     }
166
167
168     private void setInitialLogProperties(CommandRequest request) {
169         String reqId = request.getCommandExecutorInput().getRuntimeContext().getRequestContext().getCommonHeader().getRequestId();
170
171         try {
172             MDC.put(Configuration.MDC_KEY_REQUEST_ID, UUID.fromString(reqId).toString());
173             //reaching here without exception means existing RequestId is
174             //valid UUID as per ECOMP logging standards
175         } catch (Exception e) {
176             String reqIdUUID = UUID.randomUUID().toString();
177             MDC.put(Configuration.MDC_KEY_REQUEST_ID, reqIdUUID);
178             logger.info("Replaced invalid requestID of " + reqId + ".  New value is " + reqIdUUID + ".");
179         }
180         if (request.getCommandExecutorInput().getRuntimeContext().getRequestContext().getActionIdentifiers().getServiceInstanceId() != null) {
181             MDC.put(Configuration.MDC_SERVICE_INSTANCE_ID, 
182                     request.getCommandExecutorInput().getRuntimeContext().getRequestContext().getActionIdentifiers().getServiceInstanceId());
183             MDC.put(LoggingConstants.MDCKeys.PARTNER_NAME, 
184                     request.getCommandExecutorInput().getRuntimeContext().getRequestContext().getCommonHeader().getOriginatorId());
185             MDC.put(Configuration.MDC_SERVICE_NAME, 
186                     request.getCommandExecutorInput().getRuntimeContext().getRequestContext().getAction().name());
187         }
188         try {
189             MDC.put(Configuration.MDC_SERVER_FQDN, InetAddress.getLocalHost().getCanonicalHostName());
190             MDC.put(Configuration.MDC_SERVER_IP_ADDRESS, InetAddress.getLocalHost().getHostAddress());
191         } catch (Exception e) {
192             logger.error(e.getMessage(), e);
193         }
194         MDC.put(Configuration.MDC_INSTANCE_UUID, ""); // make instanse_UUID generation once during APPC-instance deploying
195     }
196
197     private void clearRequestLogProperties()
198     {
199         try {
200             MDC.remove(Configuration.MDC_KEY_REQUEST_ID);
201             MDC.remove(Configuration.MDC_SERVICE_INSTANCE_ID);
202             MDC.remove(Configuration.MDC_SERVICE_NAME);
203             MDC.remove(LoggingConstants.MDCKeys.PARTNER_NAME);
204         } catch (Exception e) {
205             logger.error(e.getMessage(), e);
206         }
207     }
208
209     public boolean deleteGenericVnfData(String vnf_id, String resourceVersion) throws AAIServiceException {
210         boolean response = false;
211
212         try {
213             AAIRequest request = aaiService.getRequestFromResource("generic-vnf");
214             request.addRequestProperty("generic-vnf.vnf-id", vnf_id);
215             response = aaiService.delete(request, resourceVersion);
216         } catch(AAIServiceException aaiexc) {
217             throw aaiexc;
218         } catch (Exception exc) {
219             logger.warn("deleteGenericVnfData", exc);
220             throw new AAIServiceException(exc);
221         }
222         return response;
223     }
224 }