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