458814daba737c1e56d9d15fb18dd94d65da7ce3
[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  * ============LICENSE_END=========================================================
22  */
23
24 package org.onap.appc.executor.impl;
25
26 import org.onap.appc.domainmodel.lcm.Status;
27 import org.onap.appc.domainmodel.lcm.VNFOperation;
28 import org.onap.appc.executor.impl.objects.CommandRequest;
29 import org.onap.appc.logging.LoggingConstants;
30 import org.onap.appc.requesthandler.RequestHandler;
31 import org.onap.appc.domainmodel.lcm.RuntimeContext;
32 import org.onap.appc.workflow.WorkFlowManager;
33 import org.onap.appc.workflow.objects.WorkflowRequest;
34 import com.att.eelf.configuration.EELFLogger;
35 import com.att.eelf.configuration.EELFManager;
36 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
37 import org.onap.ccsdk.sli.core.sli.SvcLogicException;
38 import org.onap.ccsdk.sli.core.sli.SvcLogicResource;
39 import org.onap.ccsdk.sli.adaptors.aai.AAIRequest;
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 import java.util.UUID;
49
50 import static com.att.eelf.configuration.Configuration.*;
51
52 /**
53  * This abstract class is base class for all Command tasks. All command task must inherit this class.
54  */
55
56 public class CommandTask implements Runnable {
57
58     private RequestHandler requestHandler;
59     private WorkFlowManager workflowManager;
60     private CommandRequest commandRequest;
61     private AAIService aaiService;
62
63
64     public CommandRequest getCommandRequest() {
65         return commandRequest;
66     }
67
68     public void setCommandRequest(CommandRequest commandRequest) {
69         this.commandRequest = commandRequest;
70     }
71
72     private final EELFLogger logger = EELFManager.getInstance().getLogger(CommandTask.class);
73
74     public void setWorkflowManager(WorkFlowManager workflowManager) {
75         this.workflowManager = workflowManager;
76     }
77
78     public void setRequestHandler(RequestHandler requestHandler) {
79         this.requestHandler = requestHandler;
80     }
81
82     public CommandTask(RequestHandler requestHandler,
83                        WorkFlowManager workflowManager){
84         this.requestHandler = requestHandler;
85         this.workflowManager = workflowManager;
86         getAAIservice();
87     }
88
89     private void getAAIservice() {
90         BundleContext bctx = FrameworkUtil.getBundle(AAIService.class).getBundleContext();
91         // Get AAIadapter reference
92         ServiceReference sref = bctx.getServiceReference(AAIService.class.getName());
93         if (sref != null) {
94             logger.info("AAIService from bundlecontext");
95             aaiService = (AAIService) bctx.getService(sref);
96         } else {
97             logger.info("AAIService error from bundlecontext");
98             logger.warn("Cannot find service reference for org.onap.ccsdk.sli.adaptors.aai.AAIService");
99
100         }
101     }
102
103
104     @Override
105     public void run() {
106         logger.debug("Starting execution of command :"+ commandRequest);
107         setInitialLogProperties(commandRequest);
108         final RuntimeContext runtimeContext = commandRequest.getCommandExecutorInput().getRuntimeContext();
109
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         if (logger.isDebugEnabled()) {
139             logger.debug("Workflow Execution Status = "+ statusCode);
140         }
141         if (statusCode == 100 || statusCode == 400) {
142             SvcLogicContext ctx = new SvcLogicContext();
143             ctx = getVnfdata(commandRequest.getCommandExecutorInput().getRuntimeContext().getVnfContext().getId(), "vnf", ctx);
144             deleteGenericVnfData(commandRequest.getCommandExecutorInput().getRuntimeContext().getVnfContext().getId(), ctx.getAttribute("vnf.resource-version"));
145
146         }
147     }
148
149     private SvcLogicContext getVnfdata(String vnf_id, String prefix,SvcLogicContext ctx) {
150         String key="generic-vnf.vnf-id = '"+ vnf_id+"'"+" AND http-header.Real-Time = 'true'";
151         logger.debug("inside getVnfdata=== "+key);
152         try {
153             SvcLogicResource.QueryStatus response = aaiService.query("generic-vnf", false, null, key,prefix, null, ctx);
154             if(SvcLogicResource.QueryStatus.NOT_FOUND.equals(response)){
155                 logger.warn("VNF " + vnf_id + " not found while updating A&AI");
156                 throw new RuntimeException("VNF not found for vnf_id = "+ vnf_id);
157             }
158             else if(SvcLogicResource.QueryStatus.FAILURE.equals(response)){
159                 throw new RuntimeException("Error Querying AAI with vnfID = " +vnf_id);
160             }
161             logger.info("AAIResponse: " + response.toString());
162         } catch (SvcLogicException e) {
163             logger.error("Error in getVnfdata "+ e);
164             throw new RuntimeException(e);
165         }
166         return ctx;
167     }
168
169
170     private void setInitialLogProperties(CommandRequest request) {
171         String reqId = request.getCommandExecutorInput().getRuntimeContext().getRequestContext().getCommonHeader().getRequestId();
172
173         try {
174             MDC.put(MDC_KEY_REQUEST_ID, UUID.fromString(reqId).toString());
175             //reaching here without exception means existing RequestId is
176             //valid UUID as per ECOMP logging standards
177         } catch (Exception e) {
178             String reqIdUUID = UUID.randomUUID().toString();
179             MDC.put(MDC_KEY_REQUEST_ID, reqIdUUID);
180             logger.info("Replaced invalid requestID of " + reqId + ".  New value is " + reqIdUUID + ".");
181         }
182         if (request.getCommandExecutorInput().getRuntimeContext().getRequestContext().getActionIdentifiers().getServiceInstanceId() != null)
183             MDC.put(MDC_SERVICE_INSTANCE_ID, request.getCommandExecutorInput().getRuntimeContext().getRequestContext().getActionIdentifiers().getServiceInstanceId());
184         MDC.put(LoggingConstants.MDCKeys.PARTNER_NAME, request.getCommandExecutorInput().getRuntimeContext().getRequestContext().getCommonHeader().getOriginatorId());
185         MDC.put(MDC_SERVICE_NAME, request.getCommandExecutorInput().getRuntimeContext().getRequestContext().getAction().name());
186         try {
187             MDC.put(MDC_SERVER_FQDN, InetAddress.getLocalHost().getCanonicalHostName());
188             MDC.put(MDC_SERVER_IP_ADDRESS, InetAddress.getLocalHost().getHostAddress());
189         } catch (Exception e) {
190             logger.error(e.getMessage(),e);
191         }
192         MDC.put(MDC_INSTANCE_UUID, ""); // make instanse_UUID generation once during APPC-instanse deploying
193     }
194
195     private void clearRequestLogProperties()
196     {
197         try {
198             MDC.remove(MDC_KEY_REQUEST_ID);
199             MDC.remove(MDC_SERVICE_INSTANCE_ID);
200             MDC.remove(MDC_SERVICE_NAME);
201             MDC.remove(LoggingConstants.MDCKeys.PARTNER_NAME);
202         } catch (Exception e) {
203             logger.error(e.getMessage(),e);
204         }
205     }
206     
207     public boolean deleteGenericVnfData(String vnf_id, String resourceVersion) throws AAIServiceException {
208         boolean response = false;
209
210         try {
211             AAIRequest request = aaiService.getRequestFromResource("generic-vnf");
212             request.addRequestProperty("generic-vnf.vnf-id", vnf_id);
213             response = aaiService.delete(request, resourceVersion);
214         } catch(AAIServiceException aaiexc) {
215             throw aaiexc;
216         } catch (Exception exc) {
217             logger.warn("deleteGenericVnfData", exc);
218             throw new AAIServiceException(exc);
219         }
220         return response;
221     }
222 }