965664429afcf1774b6ff139a14862aeb58785a1
[appc.git] /
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 import static com.att.eelf.configuration.Configuration.MDC_SERVICE_INSTANCE_ID;
52 import static com.att.eelf.configuration.Configuration.MDC_SERVICE_NAME;
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
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
113         WorkflowRequest workflowRequest = new WorkflowRequest();
114         workflowRequest.setRequestContext(runtimeContext.getRequestContext());
115         workflowRequest.setResponseContext(runtimeContext.getResponseContext());
116         workflowRequest.setVnfContext(runtimeContext.getVnfContext());
117         logger.debug("Executing workflow :"+ workflowRequest);
118         workflowManager.executeWorkflow(workflowRequest);
119         logger.debug("Completed execution workflow with response:"+ commandRequest.getCommandExecutorInput().getRuntimeContext().getResponseContext());
120         try {
121             if (VNFOperation.Terminate ==  commandRequest.getCommandExecutorInput().getRuntimeContext().getRequestContext().getAction())
122                 updateAAIForTerminate(commandRequest);
123         } catch (AAIServiceException e) {
124             logger.error("Exception = " + e);
125             // In case of any errors we are updating the response status code and message
126             Status updatedStatus = new Status();
127             updatedStatus.setCode(401);
128             updatedStatus.setMessage("Failed to update VNF status in A&AI");
129             commandRequest.getCommandExecutorInput().getRuntimeContext().getResponseContext().setStatus(updatedStatus);
130             throw new RuntimeException(e);
131         }finally {
132             requestHandler.onRequestExecutionEnd(commandRequest.getCommandExecutorInput().getRuntimeContext());
133             clearRequestLogProperties();
134         }
135     }
136
137     private void updateAAIForTerminate(CommandRequest commandRequest) throws AAIServiceException {
138         final int statusCode = commandRequest.getCommandExecutorInput().getRuntimeContext().getResponseContext().getStatus().getCode();
139
140         if (logger.isDebugEnabled()) {
141             logger.debug("Workflow Execution Status = "+ statusCode);
142         }
143         if (statusCode == 100 || statusCode == 400) {
144             SvcLogicContext ctx = new SvcLogicContext();
145             ctx = getVnfdata(commandRequest.getCommandExecutorInput().getRuntimeContext().getVnfContext().getId(), "vnf", ctx);
146             deleteGenericVnfData(commandRequest.getCommandExecutorInput().getRuntimeContext().getVnfContext().getId(), ctx.getAttribute("vnf.resource-version"));
147
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 = aaiService.query("generic-vnf", false, null, key,prefix, null, ctx);
156             if(SvcLogicResource.QueryStatus.NOT_FOUND.equals(response)){
157                 logger.warn("VNF " + vnf_id + " not found while updating A&AI");
158                 throw new RuntimeException("VNF not found for vnf_id = "+ vnf_id);
159             }
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         String reqId = request.getCommandExecutorInput().getRuntimeContext().getRequestContext().getCommonHeader().getRequestId();
174
175         try {
176             MDC.put(MDC_KEY_REQUEST_ID, UUID.fromString(reqId).toString());
177             //reaching here without exception means existing RequestId is
178             //valid UUID as per ECOMP logging standards
179         } catch (Exception e) {
180             String reqIdUUID = UUID.randomUUID().toString();
181             MDC.put(MDC_KEY_REQUEST_ID, reqIdUUID);
182             logger.info("Replaced invalid requestID of " + reqId + ".  New value is " + reqIdUUID + ".");
183         }
184         if (request.getCommandExecutorInput().getRuntimeContext().getRequestContext().getActionIdentifiers().getServiceInstanceId() != null)
185             MDC.put(MDC_SERVICE_INSTANCE_ID, request.getCommandExecutorInput().getRuntimeContext().getRequestContext().getActionIdentifiers().getServiceInstanceId());
186         MDC.put(LoggingConstants.MDCKeys.PARTNER_NAME, request.getCommandExecutorInput().getRuntimeContext().getRequestContext().getCommonHeader().getOriginatorId());
187         MDC.put(MDC_SERVICE_NAME, request.getCommandExecutorInput().getRuntimeContext().getRequestContext().getAction().name());
188         try {
189             MDC.put(MDC_SERVER_FQDN, InetAddress.getLocalHost().getCanonicalHostName());
190             MDC.put(MDC_SERVER_IP_ADDRESS, InetAddress.getLocalHost().getHostAddress());
191         } catch (Exception e) {
192             logger.error(e.getMessage(),e);
193         }
194         MDC.put(MDC_INSTANCE_UUID, ""); // make instanse_UUID generation once during APPC-instanse deploying
195     }
196
197     private void clearRequestLogProperties()
198     {
199         try {
200             MDC.remove(MDC_KEY_REQUEST_ID);
201             MDC.remove(MDC_SERVICE_INSTANCE_ID);
202             MDC.remove(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 }