Merge of new rebased code
[appc.git] / appc-dispatcher / appc-command-executor / appc-command-executor-core / src / main / java / org / openecomp / appc / executor / impl / LCMCommandTask.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * openECOMP : APP-C
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights
6  *                                              reserved.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  * 
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  * 
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.openecomp.appc.executor.impl;
23
24
25 import java.util.HashMap;
26 import java.util.Map;
27
28 import org.apache.commons.lang3.StringUtils;
29 import org.openecomp.appc.domainmodel.lcm.CommonHeader;
30 import org.openecomp.appc.domainmodel.lcm.RuntimeContext;
31 import org.openecomp.appc.domainmodel.lcm.Status;
32 import org.openecomp.appc.domainmodel.lcm.VNFOperation;
33 import org.openecomp.appc.executor.UnstableVNFException;
34 import org.openecomp.appc.executor.objects.CommandResponse;
35 import org.openecomp.appc.executor.objects.LCMCommandStatus;
36 import org.openecomp.appc.executor.objects.Params;
37 import org.openecomp.appc.executor.objects.UniqueRequestIdentifier;
38 import org.openecomp.appc.lifecyclemanager.LifecycleManager;
39 import org.openecomp.appc.lifecyclemanager.objects.LifecycleException;
40 import org.openecomp.appc.lifecyclemanager.objects.NoTransitionDefinedException;
41 import org.openecomp.appc.lifecyclemanager.objects.VNFOperationOutcome;
42 import org.openecomp.appc.logging.LoggingConstants;
43 import org.openecomp.appc.requesthandler.RequestHandler;
44 import org.openecomp.appc.workflow.WorkFlowManager;
45 import org.openecomp.appc.workflow.objects.WorkflowResponse;
46 import org.openecomp.sdnc.sli.SvcLogicContext;
47 import org.openecomp.sdnc.sli.SvcLogicException;
48 import org.openecomp.sdnc.sli.SvcLogicResource;
49 import org.openecomp.sdnc.sli.aai.AAIService;
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 import java.net.InetAddress;
56 import com.att.eelf.configuration.EELFLogger;
57 import com.att.eelf.configuration.EELFManager;
58
59 import static com.att.eelf.configuration.Configuration.*;
60 import static com.att.eelf.configuration.Configuration.MDC_SERVICE_INSTANCE_ID;
61 import static com.att.eelf.configuration.Configuration.MDC_SERVICE_NAME;
62
63
64 public class LCMCommandTask extends CommandTask {
65
66         private final AAIService aaiService;
67         private final LifecycleManager lifecyclemanager;
68
69         private static final EELFLogger logger = EELFManager.getInstance().getLogger(LCMCommandTask.class);
70
71     public LCMCommandTask(RuntimeContext commandRequest, RequestHandler requestHandler, WorkFlowManager workflowManager,
72             LifecycleManager lifecyclemanager) {
73         super(commandRequest, requestHandler, workflowManager);
74         this.lifecyclemanager = lifecyclemanager;
75
76                 BundleContext bctx = FrameworkUtil.getBundle(AAIService.class).getBundleContext();
77                 // Get AAIadapter reference
78                 ServiceReference sref = bctx.getServiceReference(AAIService.class.getName());
79                 if (sref != null) {
80                         logger.info("AAIService from bundlecontext");
81                         aaiService = (AAIService) bctx.getService(sref);
82
83                 } else {
84                         logger.info("AAIService error from bundlecontext");
85                         logger.warn("Cannot find service reference for org.openecomp.sdnc.sli.aai.AAIService");
86                         aaiService = null;
87                 }
88         }
89
90
91         @Override
92         public void onRequestCompletion(CommandResponse response) {
93         final RuntimeContext request = commandRequest;
94         boolean isAAIUpdated = false;
95                 try {
96
97                         final int statusCode = request.getResponseContext().getStatus().getCode();
98
99                         if (logger.isDebugEnabled()) {
100                                 logger.debug("Workflow Execution Status = "+ statusCode);
101                         }
102
103                         boolean isSuccess = statusCode == 100 || statusCode == 400;
104
105                         if (isSuccess && VNFOperation.Terminate ==  request.getRequestContext().getAction()) {
106                                 SvcLogicContext ctx = new SvcLogicContext();
107                                 ctx = getVnfdata(request.getVnfContext().getId(), "vnf", ctx);
108                                 isAAIUpdated = aaiService.deleteGenericVnfData(request.getVnfContext().getId(), ctx.getAttribute("vnf.resource-version"));
109                         }
110                         else{
111                                 isAAIUpdated = updateAAI(request.getVnfContext().getId() , false, isSuccess);
112                         }
113                         logger.debug("isAAIUpdated = " + isAAIUpdated);
114                         if(!isAAIUpdated){
115                                 throw new Exception();
116                         }
117                 }
118                 catch(Exception e1) {
119                         logger.error("Exception = " + e1);
120                         // In case of any errors we are updating the response status code and message
121                         Status updatedStatus = new Status(401, "Fail to update VNF status in A&AI");
122                         request.getResponseContext().setStatus(updatedStatus);
123                         throw new RuntimeException(e1);
124                 }
125                 finally {
126                         super.onRequestCompletion(response, isAAIUpdated);
127                 }
128         }
129
130         @Override
131         public void run() {
132                 final RuntimeContext request = commandRequest;
133                 setInitialLogProperties(request);
134                 boolean isAAIUpdated = false;
135                 final String vnfId = request.getVnfContext().getId();
136                 final String vnfType = request.getVnfContext().getType();
137                 try {
138                         final CommonHeader commonHeader = request.getRequestContext().getCommonHeader();
139                         final boolean forceFlag = commonHeader.getFlags().isForce();
140                         UniqueRequestIdentifier requestIdentifier = new UniqueRequestIdentifier(commonHeader.getOriginatorId(),
141                                         commonHeader.getRequestId(), commonHeader.getSubRequestId());
142                         String requestIdentifierString = requestIdentifier.toIdentifierString();
143                         requestHandler.onRequestExecutionStart(vnfId,false, requestIdentifierString, forceFlag);
144
145                         final String currentStatus = request.getVnfContext().getStatus();
146                         final VNFOperation action = request.getRequestContext().getAction();
147
148                         final String nextState = lifecyclemanager.getNextState(vnfType, currentStatus, action.name());
149
150                         SvcLogicContext ctx = new SvcLogicContext();
151                         ctx=getVnfdata(vnfId, "onRequestExecutionStart", ctx);
152                         isAAIUpdated= postVnfdata(vnfId, nextState,"onRequestExecutionStart",ctx);
153                 } catch (NoTransitionDefinedException e) {
154                         logger.error("Error getting Next State for AAI Update:  " + e.getMessage(), e);
155                         Params params = new Params().addParam("actionName",e.event).addParam("currentState",e.currentState);
156                         request.getResponseContext().setStatus(LCMCommandStatus.NO_TRANSITION_DEFINE_FAILURE.toStatus(params));
157                         isAAIUpdated = false;
158                 } catch (UnstableVNFException e) {
159                         logger.error(e.getMessage(), e);
160                         Params params = new Params().addParam("vnfId",vnfId);
161                         request.getResponseContext().setStatus(LCMCommandStatus.UNSTABLE_VNF_FAILURE.toStatus(params));
162                         isAAIUpdated = false;
163                 }catch (Exception e) {
164                         logger.error("Error before Request Execution starts.", e);
165                         String errorMsg = StringUtils.isEmpty(e.getMessage()) ? e.toString() : e.getMessage();
166                         Params params = new Params().addParam("errorMsg",errorMsg);
167                         request.getResponseContext().setStatus(LCMCommandStatus.UNEXPECTED_FAILURE.toStatus(params));
168                         isAAIUpdated =  false;
169                 }
170
171                 if (isAAIUpdated){
172                         super.execute();
173                 }else{
174                         String errorMsg = "Error updating A& AI before Workflow execution";
175                         logger.error(errorMsg);
176                         WorkflowResponse response = new WorkflowResponse();
177                         response.setResponseContext(request.getResponseContext());
178                         CommandResponse commandResponse = super.buildCommandResponse(response);
179                         this.onRequestCompletion(commandResponse);
180                 }
181
182         clearRequestLogProperties();
183     }
184
185
186         private boolean updateAAI(String vnf_id, boolean isTTLEnd, boolean executionStatus)
187         {
188                 String orchestrationStatus = null;
189                 String nextState;
190                 boolean callbackResponse;
191                 VNFOperationOutcome outcome;
192                 SvcLogicContext ctx = new SvcLogicContext();
193                 try {
194                         ctx=getVnfdata(vnf_id, "onRequestExecutionEnd",ctx);
195                         orchestrationStatus=ctx.getAttribute("onRequestExecutionEnd.orchestration-status");
196
197                         if(isTTLEnd){
198                                 outcome = VNFOperationOutcome.FAILURE;
199                         }
200                         else if(executionStatus){
201                                 outcome = VNFOperationOutcome.SUCCESS;
202                         }
203                         else{
204                                 outcome = VNFOperationOutcome.FAILURE;
205                         }
206                         nextState = lifecyclemanager.getNextState(null,orchestrationStatus, outcome.toString()) ;
207                         callbackResponse= postVnfdata(vnf_id, nextState,"onRequestExecutionEnd",ctx);
208                         logger.debug("AAI posting  status: " + callbackResponse);
209
210                 } catch (NoTransitionDefinedException e) {
211                         logger.debug("Transition not defined for State = " + orchestrationStatus);
212                         callbackResponse =false;
213                 } catch (LifecycleException e) {
214                         logger.debug("State or command not registered with State Machine. State = " + orchestrationStatus);
215                         callbackResponse =false;
216                 }
217                 return callbackResponse;
218         }
219
220
221         private SvcLogicContext getVnfdata(String vnf_id, String prefix,SvcLogicContext ctx) {
222                 String key="generic-vnf.vnf-id = '"+ vnf_id+"'"+" AND http-header.Real-Time = 'true'";
223                 logger.debug("inside getVnfdata=== "+key);
224                 try {
225                         SvcLogicResource.QueryStatus response = aaiService.query("generic-vnf", false, null, key,prefix, null, ctx);
226                         if(SvcLogicResource.QueryStatus.NOT_FOUND.equals(response)){
227                                 logger.warn("VNF " + vnf_id + " not found while updating A&AI");
228                                 throw new RuntimeException("VNF not found for vnf_id = "+ vnf_id);
229                         }
230                         else if(SvcLogicResource.QueryStatus.FAILURE.equals(response)){
231                                 throw new RuntimeException("Error Querying AAI with vnfID = " +vnf_id);
232                         }
233                         logger.info("AAIResponse: " + response.toString());
234                 } catch (SvcLogicException e) {
235                         logger.error("Error in getVnfdata "+ e);
236                         throw new RuntimeException(e);
237                 }
238                 return ctx;
239         }
240
241         private boolean postVnfdata(String vnf_id, String status,String prefix,SvcLogicContext ctx) {
242                 String key="vnf-id = '"+ vnf_id+"'";
243                 logger.debug("inside postVnfdata=== "+key);
244                 Map<String, String> data = new HashMap<>();
245                 data.put("orchestration-status", status);
246                 try {
247                         SvcLogicResource.QueryStatus response = aaiService.update("generic-vnf", key, data, prefix,  ctx);
248                         if(SvcLogicResource.QueryStatus.NOT_FOUND.equals(response)){
249                                 logger.warn("VNF " + vnf_id + " not found while updating A&AI");
250                                 return false;
251                         }
252                         logger.info("AAIResponse: " + response.toString());
253                         if(response.toString().equals("SUCCESS"))
254                         {
255                                 return true;
256                         }
257                 } catch (SvcLogicException e) {
258                         logger.error("Error in postVnfdata "+ e);
259                         throw new RuntimeException(e);
260                 }
261                 return false;
262         }
263
264     protected void setInitialLogProperties(RuntimeContext request)
265     {
266         MDC.put(MDC_KEY_REQUEST_ID, request.getRequestContext().getCommonHeader().getRequestId());
267         if (request.getRequestContext().getActionIdentifiers().getServiceInstanceId() != null)
268             MDC.put(MDC_SERVICE_INSTANCE_ID, request.getRequestContext().getActionIdentifiers().getServiceInstanceId());
269         MDC.put(LoggingConstants.MDCKeys.PARTNER_NAME, request.getRequestContext().getCommonHeader().getOriginatorId());
270         MDC.put(MDC_SERVICE_NAME, request.getRequestContext().getAction().name());
271         try {
272             MDC.put(MDC_SERVER_FQDN, InetAddress.getLocalHost().getCanonicalHostName());
273             MDC.put(MDC_SERVER_IP_ADDRESS, InetAddress.getLocalHost().getHostAddress());
274         } catch (Exception e) {
275             logger.debug(e.getMessage());
276         }
277         MDC.put(MDC_INSTANCE_UUID, ""); //TODO make instanse_UUID generation once during APPC-instanse deploying
278     }
279
280     protected void clearRequestLogProperties()
281     {
282         try {
283             MDC.remove(MDC_KEY_REQUEST_ID);
284             MDC.remove(MDC_SERVICE_INSTANCE_ID);
285             MDC.remove(MDC_SERVICE_NAME);
286             MDC.remove(LoggingConstants.MDCKeys.PARTNER_NAME);
287         } catch (Exception e) {
288
289         }
290     }
291 }