Merge "Refactor CommandExecutorInput to be immutable"
[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 org.apache.commons.lang3.StringUtils;
26 import org.openecomp.appc.domainmodel.lcm.CommonHeader;
27 import org.openecomp.appc.domainmodel.lcm.Status;
28 import org.openecomp.appc.domainmodel.lcm.VNFOperation;
29 import org.openecomp.appc.executor.UnstableVNFException;
30 import org.openecomp.appc.executor.impl.objects.CommandRequest;
31 import org.openecomp.appc.executor.impl.objects.LCMCommandRequest;
32 import org.openecomp.appc.executor.objects.CommandResponse;
33 import org.openecomp.appc.executor.objects.LCMCommandStatus;
34 import org.openecomp.appc.executor.objects.Params;
35 import org.openecomp.appc.executor.objects.UniqueRequestIdentifier;
36 import org.openecomp.appc.lifecyclemanager.LifecycleManager;
37 import org.openecomp.appc.lifecyclemanager.objects.LifecycleException;
38 import org.openecomp.appc.lifecyclemanager.objects.NoTransitionDefinedException;
39 import org.openecomp.appc.lifecyclemanager.objects.VNFOperationOutcome;
40 import org.openecomp.appc.requesthandler.RequestHandler;
41 import org.openecomp.appc.workflow.WorkFlowManager;
42 import org.openecomp.appc.workflow.objects.WorkflowResponse;
43 import com.att.eelf.configuration.EELFLogger;
44 import com.att.eelf.configuration.EELFManager;
45 import org.openecomp.sdnc.sli.SvcLogicContext;
46 import org.openecomp.sdnc.sli.SvcLogicException;
47 import org.openecomp.sdnc.sli.SvcLogicResource;
48 import org.openecomp.sdnc.sli.aai.AAIService;
49 import org.osgi.framework.BundleContext;
50 import org.osgi.framework.FrameworkUtil;
51 import org.osgi.framework.ServiceReference;
52
53 import java.util.HashMap;
54 import java.util.Map;
55
56
57 public class LCMCommandTask extends CommandTask<LCMCommandRequest> {
58
59         private AAIService aaiService;
60         private LifecycleManager lifecyclemanager;
61
62         private static final EELFLogger logger = EELFManager.getInstance().getLogger(LCMCommandTask.class);
63
64         public LCMCommandTask(RequestHandler requestHandler, WorkFlowManager workflowManager,
65                                                   LifecycleManager lifecyclemanager){
66                 setRequestHandler(requestHandler);
67                 setWorkflowManager(workflowManager);
68                 setLifecyclemanager(lifecyclemanager);
69                 getAAIservice();
70         }
71
72         public void setLifecyclemanager(LifecycleManager lifecyclemanager) {
73                 this.lifecyclemanager = lifecyclemanager;
74         }
75
76
77         private void getAAIservice() {
78                 BundleContext bctx = FrameworkUtil.getBundle(AAIService.class).getBundleContext();
79                 // Get AAIadapter reference
80                 ServiceReference sref = bctx.getServiceReference(AAIService.class.getName());
81                 if (sref != null) {
82                         logger.info("AAIService from bundlecontext");
83                         aaiService = (AAIService) bctx.getService(sref);
84
85                 } else {
86                         logger.info("AAIService error from bundlecontext");
87                         logger.warn("Cannot find service reference for org.openecomp.sdnc.sli.aai.AAIService");
88
89                 }
90         }
91
92
93         @Override
94         public void onRequestCompletion(CommandRequest request, CommandResponse response) {
95
96                 boolean isAAIUpdated = false;
97                 try {
98
99                         final int statusCode = request.getCommandExecutorInput().getRuntimeContext().getResponseContext().getStatus().getCode();
100
101                         if (logger.isDebugEnabled()) {
102                                 logger.debug("Workflow Execution Status = "+ statusCode);
103                         }
104
105                         boolean isSuccess = statusCode == 100 || statusCode == 400;
106
107                         if (isSuccess && VNFOperation.Terminate ==  request.getCommandExecutorInput().getRuntimeContext().getRequestContext().getAction()) {
108                                 SvcLogicContext ctx = new SvcLogicContext();
109                                 ctx = getVnfdata(request.getCommandExecutorInput().getRuntimeContext().getVnfContext().getId(), "vnf", ctx);
110                                 isAAIUpdated = aaiService.deleteGenericVnfData(request.getCommandExecutorInput().getRuntimeContext().getVnfContext().getId(), ctx.getAttribute("vnf.resource-version"));
111                         }
112                         else{
113                                 isAAIUpdated = updateAAI(request.getCommandExecutorInput().getRuntimeContext().getVnfContext().getId() , false, isSuccess);
114                         }
115                         logger.debug("isAAIUpdated = " + isAAIUpdated);
116                 }
117                 catch(Exception e1) {
118                         logger.error("Exception = " + e1);
119                         throw new RuntimeException(e1);
120                 }
121                 finally {
122                         super.onRequestCompletion(request, response , isAAIUpdated);
123                 }
124         }
125
126         @Override
127         public void run() {
128                 LCMCommandRequest request = (LCMCommandRequest)getCommandRequest();
129                 boolean isAAIUpdated;
130                 final String vnfId = request.getCommandExecutorInput().getRuntimeContext().getVnfContext().getId();
131                 final String vnfType = request.getCommandExecutorInput().getRuntimeContext().getVnfContext().getType();
132                 try {
133                         final CommonHeader commonHeader = request.getCommandExecutorInput().getRuntimeContext().getRequestContext().getCommonHeader();
134                         final boolean forceFlag = commonHeader.getFlags().isForce();
135                         UniqueRequestIdentifier requestIdentifier = new UniqueRequestIdentifier(commonHeader.getOriginatorId(),
136                                         commonHeader.getRequestId(), commonHeader.getSubRequestId());
137                         String requestIdentifierString = requestIdentifier.toIdentifierString();
138                         requestHandler.onRequestExecutionStart(vnfId,false, requestIdentifierString, forceFlag);
139
140                         final String currentStatus = request.getCommandExecutorInput().getRuntimeContext().getVnfContext().getStatus();
141                         final VNFOperation action = request.getCommandExecutorInput().getRuntimeContext().getRequestContext().getAction();
142
143                         final String nextState = lifecyclemanager.getNextState(vnfType, currentStatus, action.name());
144
145                         SvcLogicContext ctx = new SvcLogicContext();
146                         ctx=getVnfdata(vnfId, "onRequestExecutionStart", ctx);
147                         isAAIUpdated= postVnfdata(vnfId, nextState,"onRequestExecutionStart",ctx);
148                 } catch (NoTransitionDefinedException e) {
149                         logger.error("Error getting Next State for AAI Update:  " + e.getMessage(), e);
150                         Params params = new Params().addParam("actionName",e.event).addParam("currentState",e.currentState);
151                         request.getCommandExecutorInput().getRuntimeContext().getResponseContext().setStatus(LCMCommandStatus.NO_TRANSITION_DEFINE_FAILURE.toStatus(params));
152                         isAAIUpdated = false;
153                 } catch (UnstableVNFException e) {
154                         logger.error(e.getMessage(), e);
155                         Params params = new Params().addParam("vnfId",vnfId);
156                         request.getCommandExecutorInput().getRuntimeContext().getResponseContext().setStatus(LCMCommandStatus.UNSTABLE_VNF_FAILURE.toStatus(params));
157                         isAAIUpdated = false;
158                 }catch (Exception e) {
159                         logger.error("Error before Request Execution starts.", e);
160                         String errorMsg = StringUtils.isEmpty(e.getMessage()) ? e.toString() : e.getMessage();
161                         Params params = new Params().addParam("errorMsg",errorMsg);
162                         request.getCommandExecutorInput().getRuntimeContext().getResponseContext().setStatus(LCMCommandStatus.UNEXPECTED_FAILURE.toStatus(params));
163                         isAAIUpdated =  false;
164                 }
165
166                 if (isAAIUpdated){
167                         super.execute();
168                 }else{
169                         String errorMsg = "Error updating A& AI before Workflow execution";
170                         logger.error(errorMsg);
171                         WorkflowResponse response = new WorkflowResponse();
172                         response.setResponseContext(request.getCommandExecutorInput().getRuntimeContext().getResponseContext());
173                         CommandResponse commandResponse = super.buildCommandResponse(request, response);
174                         this.onRequestCompletion(request,commandResponse);
175                 }
176         }
177
178
179
180         private boolean updateAAI(String vnf_id , boolean isTTLEnd , boolean executionStatus)
181         {
182                 String orchestrationStatus = null;
183                 String nextState;
184                 boolean callbackResponse;
185                 VNFOperationOutcome outcome;
186                 SvcLogicContext ctx = new SvcLogicContext();
187                 try {
188                         ctx=getVnfdata(vnf_id, "onRequestExecutionEnd",ctx);
189                         orchestrationStatus=ctx.getAttribute("onRequestExecutionEnd.orchestration-status");
190
191                         if(isTTLEnd){
192                                 outcome = VNFOperationOutcome.FAILURE;
193                         }
194                         else if(executionStatus){
195                                 outcome = VNFOperationOutcome.SUCCESS;
196                         }
197                         else{
198                                 outcome = VNFOperationOutcome.FAILURE;
199                         }
200                         nextState = lifecyclemanager.getNextState(null,orchestrationStatus, outcome.toString()) ;
201                         callbackResponse= postVnfdata(vnf_id, nextState,"onRequestExecutionEnd",ctx);
202                         logger.debug("AAI posting  status: " + callbackResponse);
203
204                 } catch (NoTransitionDefinedException e) {
205                         logger.debug("Transition not defined for State = " + orchestrationStatus);
206                         callbackResponse =false;
207                 } catch (LifecycleException e) {
208                         logger.debug("State or command not registered with State Machine. State = " + orchestrationStatus);
209                         callbackResponse =false;
210                 }
211                 return callbackResponse;
212         }
213
214
215         private SvcLogicContext getVnfdata(String vnf_id, String prefix,SvcLogicContext ctx) {
216                 String key="vnf-id = '"+ vnf_id+"'";
217                 logger.debug("inside getVnfdata=== "+key);
218                 try {
219                         SvcLogicResource.QueryStatus response = aaiService.query("generic-vnf", false, null, key,prefix, null, ctx);
220                         if(SvcLogicResource.QueryStatus.NOT_FOUND.equals(response)){
221                                 logger.warn("VNF " + vnf_id + " not found while updating A&AI");
222                                 throw new RuntimeException("VNF not found for vnf_id = "+ vnf_id);
223                         }
224                         else if(SvcLogicResource.QueryStatus.FAILURE.equals(response)){
225                                 throw new RuntimeException("Error Querying AAI with vnfID = " +vnf_id);
226                         }
227                         logger.info("AAIResponse: " + response.toString());
228                 } catch (SvcLogicException e) {
229                         logger.error("Error in getVnfdata "+ e);
230                         throw new RuntimeException(e);
231                 }
232                 return ctx;
233         }
234
235         private boolean postVnfdata(String vnf_id, String status,String prefix,SvcLogicContext ctx) {
236                 String key="vnf-id = '"+ vnf_id+"'";
237                 logger.debug("inside postVnfdata=== "+key);
238                 Map<String, String> data = new HashMap<>();
239                 data.put("orchestration-status", status);
240                 try {
241                         SvcLogicResource.QueryStatus response = aaiService.update("generic-vnf", key, data, prefix,  ctx);
242                         if(SvcLogicResource.QueryStatus.NOT_FOUND.equals(response)){
243                                 logger.warn("VNF " + vnf_id + " not found while updating A&AI");
244                                 return false;
245                         }
246                         logger.info("AAIResponse: " + response.toString());
247                         if(response.toString().equals("SUCCESS"))
248                         {
249                                 return true;
250                         }
251                 } catch (SvcLogicException e) {
252                         logger.error("Error in postVnfdata "+ e);
253                         throw new RuntimeException(e);
254                 }
255                 return false;
256         }
257
258 }