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