Include impacted changes for APPC-346,APPC-348
[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  * 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.executor.impl;
26
27 import org.onap.appc.domainmodel.lcm.Status;
28 import org.onap.appc.domainmodel.lcm.VNFOperation;
29 import org.onap.appc.executor.impl.objects.CommandRequest;
30 import org.onap.appc.logging.LoggingConstants;
31 import org.onap.appc.requesthandler.RequestHandler;
32 import org.onap.appc.domainmodel.lcm.RuntimeContext;
33 import org.onap.appc.workflow.WorkFlowManager;
34 import org.onap.appc.workflow.objects.WorkflowRequest;
35 import com.att.eelf.configuration.EELFLogger;
36 import com.att.eelf.configuration.EELFManager;
37 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
38 import org.onap.ccsdk.sli.core.sli.SvcLogicException;
39 import org.onap.ccsdk.sli.core.sli.SvcLogicResource;
40 import org.onap.ccsdk.sli.adaptors.aai.AAIService;
41 import org.onap.ccsdk.sli.adaptors.aai.AAIServiceException;
42 import org.osgi.framework.BundleContext;
43 import org.osgi.framework.FrameworkUtil;
44 import org.osgi.framework.ServiceReference;
45 import org.slf4j.MDC;
46
47 import java.net.InetAddress;
48
49 import static com.att.eelf.configuration.Configuration.*;
50 import static com.att.eelf.configuration.Configuration.MDC_SERVICE_INSTANCE_ID;
51 import static com.att.eelf.configuration.Configuration.MDC_SERVICE_NAME;
52
53 /**
54  * This abstract class is base class for all Command tasks. All command task must inherit this class.
55  */
56
57 public class CommandTask implements Runnable {
58
59     private RequestHandler requestHandler;
60     private WorkFlowManager workflowManager;
61     private CommandRequest commandRequest;
62     private AAIService aaiService;
63
64
65     public CommandRequest getCommandRequest() {
66         return commandRequest;
67     }
68
69     public void setCommandRequest(CommandRequest commandRequest) {
70         this.commandRequest = commandRequest;
71     }
72
73     private final EELFLogger logger = EELFManager.getInstance().getLogger(CommandTask.class);
74
75     public void setWorkflowManager(WorkFlowManager workflowManager) {
76         this.workflowManager = workflowManager;
77     }
78
79     public void setRequestHandler(RequestHandler requestHandler) {
80         this.requestHandler = requestHandler;
81     }
82
83     public CommandTask(RequestHandler requestHandler,
84                        WorkFlowManager workflowManager){
85         this.requestHandler = requestHandler;
86         this.workflowManager = workflowManager;
87         getAAIservice();
88     }
89
90     private void getAAIservice() {
91         BundleContext bctx = FrameworkUtil.getBundle(AAIService.class).getBundleContext();
92         // Get AAIadapter reference
93         ServiceReference sref = bctx.getServiceReference(AAIService.class.getName());
94         if (sref != null) {
95             logger.info("AAIService from bundlecontext");
96             aaiService = (AAIService) bctx.getService(sref);
97         } else {
98             logger.info("AAIService error from bundlecontext");
99             logger.warn("Cannot find service reference for org.onap.ccsdk.sli.adaptors.aai.AAIService");
100
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
112         WorkflowRequest workflowRequest = new WorkflowRequest();
113         workflowRequest.setRequestContext(runtimeContext.getRequestContext());
114         workflowRequest.setResponseContext(runtimeContext.getResponseContext());
115         workflowRequest.setVnfContext(runtimeContext.getVnfContext());
116         logger.debug("Executing workflow :"+ workflowRequest);
117         workflowManager.executeWorkflow(workflowRequest);
118         logger.debug("Completed execution workflow with response:"+ commandRequest.getCommandExecutorInput().getRuntimeContext().getResponseContext());
119         try {
120             if (VNFOperation.Terminate ==  commandRequest.getCommandExecutorInput().getRuntimeContext().getRequestContext().getAction())
121                 updateAAIForTerminate(commandRequest);
122         } catch (AAIServiceException e) {
123             logger.error("Exception = " + e);
124             // In case of any errors we are updating the response status code and message
125             Status updatedStatus = new Status();
126             updatedStatus.setCode(401);
127             updatedStatus.setMessage("Failed to update VNF status in A&AI");
128             commandRequest.getCommandExecutorInput().getRuntimeContext().getResponseContext().setStatus(updatedStatus);
129             throw new RuntimeException(e);
130         }finally {
131             requestHandler.onRequestExecutionEnd(commandRequest.getCommandExecutorInput().getRuntimeContext());
132             clearRequestLogProperties();
133         }
134     }
135
136     private void updateAAIForTerminate(CommandRequest commandRequest) throws AAIServiceException {
137         final int statusCode = commandRequest.getCommandExecutorInput().getRuntimeContext().getResponseContext().getStatus().getCode();
138
139         if (logger.isDebugEnabled()) {
140             logger.debug("Workflow Execution Status = "+ statusCode);
141         }
142         if (statusCode == 100 || statusCode == 400) {
143             SvcLogicContext ctx = new SvcLogicContext();
144             ctx = getVnfdata(commandRequest.getCommandExecutorInput().getRuntimeContext().getVnfContext().getId(), "vnf", ctx);
145             aaiService.deleteGenericVnfData(commandRequest.getCommandExecutorInput().getRuntimeContext().getVnfContext().getId(), ctx.getAttribute("vnf.resource-version"));
146
147         }
148     }
149
150     private SvcLogicContext getVnfdata(String vnf_id, String prefix,SvcLogicContext ctx) {
151         String key="generic-vnf.vnf-id = '"+ vnf_id+"'"+" AND http-header.Real-Time = 'true'";
152         logger.debug("inside getVnfdata=== "+key);
153         try {
154             SvcLogicResource.QueryStatus response = aaiService.query("generic-vnf", false, null, key,prefix, null, ctx);
155             if(SvcLogicResource.QueryStatus.NOT_FOUND.equals(response)){
156                 logger.warn("VNF " + vnf_id + " not found while updating A&AI");
157                 throw new RuntimeException("VNF not found for vnf_id = "+ vnf_id);
158             }
159             else if(SvcLogicResource.QueryStatus.FAILURE.equals(response)){
160                 throw new RuntimeException("Error Querying AAI with vnfID = " +vnf_id);
161             }
162             logger.info("AAIResponse: " + response.toString());
163         } catch (SvcLogicException e) {
164             logger.error("Error in getVnfdata "+ e);
165             throw new RuntimeException(e);
166         }
167         return ctx;
168     }
169
170
171     private void setInitialLogProperties(CommandRequest request) {
172         MDC.put(MDC_KEY_REQUEST_ID, request.getCommandExecutorInput().getRuntimeContext().getRequestContext().getCommonHeader().getRequestId());
173         if (request.getCommandExecutorInput().getRuntimeContext().getRequestContext().getActionIdentifiers().getServiceInstanceId() != null)
174             MDC.put(MDC_SERVICE_INSTANCE_ID, request.getCommandExecutorInput().getRuntimeContext().getRequestContext().getActionIdentifiers().getServiceInstanceId());
175         MDC.put(LoggingConstants.MDCKeys.PARTNER_NAME, request.getCommandExecutorInput().getRuntimeContext().getRequestContext().getCommonHeader().getOriginatorId());
176         MDC.put(MDC_SERVICE_NAME, request.getCommandExecutorInput().getRuntimeContext().getRequestContext().getAction().name());
177         try {
178             MDC.put(MDC_SERVER_FQDN, InetAddress.getLocalHost().getCanonicalHostName());
179             MDC.put(MDC_SERVER_IP_ADDRESS, InetAddress.getLocalHost().getHostAddress());
180         } catch (Exception e) {
181             logger.error(e.getMessage(),e);
182         }
183         MDC.put(MDC_INSTANCE_UUID, ""); // make instanse_UUID generation once during APPC-instanse deploying
184     }
185
186     private void clearRequestLogProperties()
187     {
188         try {
189             MDC.remove(MDC_KEY_REQUEST_ID);
190             MDC.remove(MDC_SERVICE_INSTANCE_ID);
191             MDC.remove(MDC_SERVICE_NAME);
192             MDC.remove(LoggingConstants.MDCKeys.PARTNER_NAME);
193         } catch (Exception e) {
194             logger.error(e.getMessage(),e);
195         }
196     }
197 }