56a58821821f891c812f0962caf1d3093ac181ab
[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  * APPC
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * Copyright (C) 2017 Amdocs
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  * ECOMP is a trademark and service mark of AT&T Intellectual Property.
21  */
22
23 package org.openecomp.appc.executor.impl;
24
25
26 import java.util.HashMap;
27 import java.util.Map;
28
29 import org.apache.commons.lang3.StringUtils;
30 import org.openecomp.appc.domainmodel.lcm.CommonHeader;
31 import org.openecomp.appc.domainmodel.lcm.RuntimeContext;
32 import org.openecomp.appc.domainmodel.lcm.Status;
33 import org.openecomp.appc.domainmodel.lcm.VNFOperation;
34 import org.openecomp.appc.executor.UnstableVNFException;
35 import org.openecomp.appc.executor.objects.CommandResponse;
36 import org.openecomp.appc.executor.objects.LCMCommandStatus;
37 import org.openecomp.appc.executor.objects.Params;
38 import org.openecomp.appc.executor.objects.UniqueRequestIdentifier;
39 import org.openecomp.appc.lifecyclemanager.LifecycleManager;
40 import org.openecomp.appc.lifecyclemanager.objects.LifecycleException;
41 import org.openecomp.appc.lifecyclemanager.objects.NoTransitionDefinedException;
42 import org.openecomp.appc.lifecyclemanager.objects.VNFOperationOutcome;
43 import org.openecomp.appc.logging.LoggingConstants;
44 import org.openecomp.appc.requesthandler.RequestHandler;
45 import org.openecomp.appc.workflow.WorkFlowManager;
46 import org.openecomp.appc.workflow.objects.WorkflowResponse;
47 import org.openecomp.sdnc.sli.SvcLogicContext;
48 import org.openecomp.sdnc.sli.SvcLogicException;
49 import org.openecomp.sdnc.sli.SvcLogicResource;
50 import org.openecomp.sdnc.sli.aai.AAIService;
51 import org.osgi.framework.BundleContext;
52 import org.osgi.framework.FrameworkUtil;
53 import org.osgi.framework.ServiceReference;
54 import org.slf4j.MDC;
55
56 import java.net.InetAddress;
57 import com.att.eelf.configuration.EELFLogger;
58 import com.att.eelf.configuration.EELFManager;
59
60 import static com.att.eelf.configuration.Configuration.*;
61 import static com.att.eelf.configuration.Configuration.MDC_SERVICE_INSTANCE_ID;
62 import static com.att.eelf.configuration.Configuration.MDC_SERVICE_NAME;
63
64
65 public class LCMCommandTask extends CommandTask {
66
67         private final AAIService aaiService;
68         private final LifecycleManager lifecyclemanager;
69
70         private static final EELFLogger logger = EELFManager.getInstance().getLogger(LCMCommandTask.class);
71
72     public LCMCommandTask(RuntimeContext commandRequest, RequestHandler requestHandler, WorkFlowManager workflowManager,
73             LifecycleManager lifecyclemanager) {
74         super(commandRequest, requestHandler, workflowManager);
75         this.lifecyclemanager = lifecyclemanager;
76
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                         aaiService = null;
88                 }
89         }
90
91
92         @Override
93         public void onRequestCompletion(CommandResponse response) {
94         final RuntimeContext request = commandRequest;
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                         if(!isAAIUpdated){
116                                 throw new Exception();
117                         }
118                 }
119                 catch(Exception e1) {
120                         logger.error("Exception = " + e1);
121                         // In case of any errors we are updating the response status code and message
122                         Status updatedStatus = new Status(401, "Fail to update VNF status in A&AI");
123                         request.getResponseContext().setStatus(updatedStatus);
124                         throw new RuntimeException(e1);
125                 }
126                 finally {
127                         super.onRequestCompletion(response, isAAIUpdated);
128                 }
129         }
130
131         @Override
132         public void run() {
133                 final RuntimeContext request = commandRequest;
134                 setInitialLogProperties(request);
135                 boolean isAAIUpdated = false;
136                 final String vnfId = request.getVnfContext().getId();
137                 final String vnfType = request.getVnfContext().getType();
138                 try {
139                         final CommonHeader commonHeader = request.getRequestContext().getCommonHeader();
140                         final boolean forceFlag = commonHeader.getFlags().isForce();
141                         UniqueRequestIdentifier requestIdentifier = new UniqueRequestIdentifier(commonHeader.getOriginatorId(),
142                                         commonHeader.getRequestId(), commonHeader.getSubRequestId());
143                         String requestIdentifierString = requestIdentifier.toIdentifierString();
144                         requestHandler.onRequestExecutionStart(vnfId,false, requestIdentifierString, forceFlag);
145
146                         final String currentStatus = request.getVnfContext().getStatus();
147                         final VNFOperation action = request.getRequestContext().getAction();
148
149                         final String nextState = lifecyclemanager.getNextState(vnfType, currentStatus, action.name());
150
151                         SvcLogicContext ctx = new SvcLogicContext();
152                         ctx=getVnfdata(vnfId, "onRequestExecutionStart", ctx);
153                         isAAIUpdated= postVnfdata(vnfId, nextState,"onRequestExecutionStart",ctx);
154                 } catch (NoTransitionDefinedException e) {
155                         logger.error("Error getting Next State for AAI Update:  " + e.getMessage(), e);
156                         Params params = new Params().addParam("actionName",e.event).addParam("currentState",e.currentState);
157                         request.getResponseContext().setStatus(LCMCommandStatus.NO_TRANSITION_DEFINE_FAILURE.toStatus(params));
158                         isAAIUpdated = false;
159                 } catch (UnstableVNFException e) {
160                         logger.error(e.getMessage(), e);
161                         Params params = new Params().addParam("vnfId",vnfId);
162                         request.getResponseContext().setStatus(LCMCommandStatus.UNSTABLE_VNF_FAILURE.toStatus(params));
163                         isAAIUpdated = false;
164                 }catch (Exception e) {
165                         logger.error("Error before Request Execution starts.", e);
166                         String errorMsg = StringUtils.isEmpty(e.getMessage()) ? e.toString() : e.getMessage();
167                         Params params = new Params().addParam("errorMsg",errorMsg);
168                         request.getResponseContext().setStatus(LCMCommandStatus.UNEXPECTED_FAILURE.toStatus(params));
169                         isAAIUpdated =  false;
170                 }
171
172                 if (isAAIUpdated){
173                         super.execute();
174                 }else{
175                         String errorMsg = "Error updating A& AI before Workflow execution";
176                         logger.error(errorMsg);
177                         WorkflowResponse response = new WorkflowResponse();
178                         response.setResponseContext(request.getResponseContext());
179                         CommandResponse commandResponse = super.buildCommandResponse(response);
180                         this.onRequestCompletion(commandResponse);
181                 }
182
183         clearRequestLogProperties();
184     }
185
186
187         private boolean updateAAI(String vnf_id, boolean isTTLEnd, boolean executionStatus)
188         {
189                 String orchestrationStatus = null;
190                 String nextState;
191                 boolean callbackResponse;
192                 VNFOperationOutcome outcome;
193                 SvcLogicContext ctx = new SvcLogicContext();
194                 try {
195                         ctx=getVnfdata(vnf_id, "onRequestExecutionEnd",ctx);
196                         orchestrationStatus=ctx.getAttribute("onRequestExecutionEnd.orchestration-status");
197
198                         if(isTTLEnd){
199                                 outcome = VNFOperationOutcome.FAILURE;
200                         }
201                         else if(executionStatus){
202                                 outcome = VNFOperationOutcome.SUCCESS;
203                         }
204                         else{
205                                 outcome = VNFOperationOutcome.FAILURE;
206                         }
207                         nextState = lifecyclemanager.getNextState(null,orchestrationStatus, outcome.toString()) ;
208                         callbackResponse= postVnfdata(vnf_id, nextState,"onRequestExecutionEnd",ctx);
209                         logger.debug("AAI posting  status: " + callbackResponse);
210
211                 } catch (NoTransitionDefinedException e) {
212                         logger.debug("Transition not defined for State = " + orchestrationStatus);
213                         callbackResponse =false;
214                 } catch (LifecycleException e) {
215                         logger.debug("State or command not registered with State Machine. State = " + orchestrationStatus);
216                         callbackResponse =false;
217                 }
218                 return callbackResponse;
219         }
220
221
222         private SvcLogicContext getVnfdata(String vnf_id, String prefix,SvcLogicContext ctx) {
223                 String key="generic-vnf.vnf-id = '"+ vnf_id+"'"+" AND http-header.Real-Time = 'true'";
224                 logger.debug("inside getVnfdata=== "+key);
225                 try {
226                         SvcLogicResource.QueryStatus response = aaiService.query("generic-vnf", false, null, key,prefix, null, ctx);
227                         if(SvcLogicResource.QueryStatus.NOT_FOUND.equals(response)){
228                                 logger.warn("VNF " + vnf_id + " not found while updating A&AI");
229                                 throw new RuntimeException("VNF not found for vnf_id = "+ vnf_id);
230                         }
231                         else if(SvcLogicResource.QueryStatus.FAILURE.equals(response)){
232                                 throw new RuntimeException("Error Querying AAI with vnfID = " +vnf_id);
233                         }
234                         logger.info("AAIResponse: " + response.toString());
235                 } catch (SvcLogicException e) {
236                         logger.error("Error in getVnfdata "+ e);
237                         throw new RuntimeException(e);
238                 }
239                 return ctx;
240         }
241
242         private boolean postVnfdata(String vnf_id, String status,String prefix,SvcLogicContext ctx) {
243                 String key="vnf-id = '"+ vnf_id+"'";
244                 logger.debug("inside postVnfdata=== "+key);
245                 Map<String, String> data = new HashMap<>();
246                 data.put("orchestration-status", status);
247                 try {
248                         SvcLogicResource.QueryStatus response = aaiService.update("generic-vnf", key, data, prefix,  ctx);
249                         if(SvcLogicResource.QueryStatus.NOT_FOUND.equals(response)){
250                                 logger.warn("VNF " + vnf_id + " not found while updating A&AI");
251                                 return false;
252                         }
253                         logger.info("AAIResponse: " + response.toString());
254                         if(response.toString().equals("SUCCESS"))
255                         {
256                                 return true;
257                         }
258                 } catch (SvcLogicException e) {
259                         logger.error("Error in postVnfdata "+ e);
260                         throw new RuntimeException(e);
261                 }
262                 return false;
263         }
264
265     protected void setInitialLogProperties(RuntimeContext request)
266     {
267         MDC.put(MDC_KEY_REQUEST_ID, request.getRequestContext().getCommonHeader().getRequestId());
268         if (request.getRequestContext().getActionIdentifiers().getServiceInstanceId() != null)
269             MDC.put(MDC_SERVICE_INSTANCE_ID, request.getRequestContext().getActionIdentifiers().getServiceInstanceId());
270         MDC.put(LoggingConstants.MDCKeys.PARTNER_NAME, request.getRequestContext().getCommonHeader().getOriginatorId());
271         MDC.put(MDC_SERVICE_NAME, request.getRequestContext().getAction().name());
272         try {
273             MDC.put(MDC_SERVER_FQDN, InetAddress.getLocalHost().getCanonicalHostName());
274             MDC.put(MDC_SERVER_IP_ADDRESS, InetAddress.getLocalHost().getHostAddress());
275         } catch (Exception e) {
276             logger.debug(e.getMessage());
277         }
278         MDC.put(MDC_INSTANCE_UUID, ""); //TODO make instanse_UUID generation once during APPC-instanse deploying
279     }
280
281     protected void clearRequestLogProperties()
282     {
283         try {
284             MDC.remove(MDC_KEY_REQUEST_ID);
285             MDC.remove(MDC_SERVICE_INSTANCE_ID);
286             MDC.remove(MDC_SERVICE_NAME);
287             MDC.remove(LoggingConstants.MDCKeys.PARTNER_NAME);
288         } catch (Exception e) {
289
290         }
291     }
292 }