Moving all files to root directory
[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                         Status status = request.getCommandExecutorInput().getRuntimeContext().getResponseContext().getStatus();
151                         Params params = new Params().addParam("actionName",e.event).addParam("currentState",e.currentState);
152                         fillStatus(status, LCMCommandStatus.NO_TRANSITION_DEFINE_FAILURE, params);
153                         isAAIUpdated = false;
154                 } catch (UnstableVNFException e) {
155                         logger.error(e.getMessage(), e);
156                         Status status = request.getCommandExecutorInput().getRuntimeContext().getResponseContext().getStatus();
157                         Params params = new Params().addParam("vnfId",vnfId);
158                         fillStatus(status, LCMCommandStatus.UNSTABLE_VNF_FAILURE, params);
159                         isAAIUpdated = false;
160                 }catch (Exception e) {
161                         logger.error("Error before Request Execution starts.", e);
162                         Status status = request.getCommandExecutorInput().getRuntimeContext().getResponseContext().getStatus();
163                         String errorMsg = StringUtils.isEmpty(e.getMessage()) ? e.toString() : e.getMessage();
164                         Params params = new Params().addParam("errorMsg",errorMsg);
165                         fillStatus(status, LCMCommandStatus.UNEXPECTED_FAILURE, params);
166                         isAAIUpdated =  false;
167                 }
168
169                 if (isAAIUpdated){
170                         super.execute();
171                 }else{
172                         String errorMsg = "Error updating A& AI before Workflow execution";
173                         logger.error(errorMsg);
174                         WorkflowResponse response = new WorkflowResponse();
175                         response.setResponseContext(request.getCommandExecutorInput().getRuntimeContext().getResponseContext());
176                         CommandResponse commandResponse = super.buildCommandResponse(request, response);
177                         this.onRequestCompletion(request,commandResponse);
178                 }
179         }
180
181
182
183         private boolean updateAAI(String vnf_id , boolean isTTLEnd , boolean executionStatus)
184         {
185                 String orchestrationStatus = null;
186                 String nextState;
187                 boolean callbackResponse;
188                 VNFOperationOutcome outcome;
189                 SvcLogicContext ctx = new SvcLogicContext();
190                 try {
191                         ctx=getVnfdata(vnf_id, "onRequestExecutionEnd",ctx);
192                         orchestrationStatus=ctx.getAttribute("onRequestExecutionEnd.orchestration-status");
193
194                         if(isTTLEnd){
195                                 outcome = VNFOperationOutcome.FAILURE;
196                         }
197                         else if(executionStatus){
198                                 outcome = VNFOperationOutcome.SUCCESS;
199                         }
200                         else{
201                                 outcome = VNFOperationOutcome.FAILURE;
202                         }
203                         nextState = lifecyclemanager.getNextState(null,orchestrationStatus, outcome.toString()) ;
204                         callbackResponse= postVnfdata(vnf_id, nextState,"onRequestExecutionEnd",ctx);
205                         logger.debug("AAI posting  status: " + callbackResponse);
206
207                 } catch (NoTransitionDefinedException e) {
208                         logger.debug("Transition not defined for State = " + orchestrationStatus);
209                         callbackResponse =false;
210                 } catch (LifecycleException e) {
211                         logger.debug("State or command not registered with State Machine. State = " + orchestrationStatus);
212                         callbackResponse =false;
213                 }
214                 return callbackResponse;
215         }
216
217
218         private SvcLogicContext getVnfdata(String vnf_id, String prefix,SvcLogicContext ctx) {
219                 String key="vnf-id = '"+ vnf_id+"'";
220                 logger.debug("inside getVnfdata=== "+key);
221                 try {
222                         SvcLogicResource.QueryStatus response = aaiService.query("generic-vnf", false, null, key,prefix, null, ctx);
223                         if(SvcLogicResource.QueryStatus.NOT_FOUND.equals(response)){
224                                 logger.warn("VNF " + vnf_id + " not found while updating A&AI");
225                                 throw new RuntimeException("VNF not found for vnf_id = "+ vnf_id);
226                         }
227                         else if(SvcLogicResource.QueryStatus.FAILURE.equals(response)){
228                                 throw new RuntimeException("Error Querying AAI with vnfID = " +vnf_id);
229                         }
230                         logger.info("AAIResponse: " + response.toString());
231                 } catch (SvcLogicException e) {
232                         logger.error("Error in getVnfdata "+ e);
233                         throw new RuntimeException(e);
234                 }
235                 return ctx;
236         }
237
238         private boolean postVnfdata(String vnf_id, String status,String prefix,SvcLogicContext ctx) {
239                 String key="vnf-id = '"+ vnf_id+"'";
240                 logger.debug("inside postVnfdata=== "+key);
241                 Map<String, String> data = new HashMap<>();
242                 data.put("orchestration-status", status);
243                 try {
244                         SvcLogicResource.QueryStatus response = aaiService.update("generic-vnf", key, data, prefix,  ctx);
245                         if(SvcLogicResource.QueryStatus.NOT_FOUND.equals(response)){
246                                 logger.warn("VNF " + vnf_id + " not found while updating A&AI");
247                                 return false;
248                         }
249                         logger.info("AAIResponse: " + response.toString());
250                         if(response.toString().equals("SUCCESS"))
251                         {
252                                 return true;
253                         }
254                 } catch (SvcLogicException e) {
255                         logger.error("Error in postVnfdata "+ e);
256                         throw new RuntimeException(e);
257                 }
258                 return false;
259         }
260
261 }