8499937c7d4929a643bd59413fb26b762b6c07e4
[appc.git] / appc-dispatcher / appc-request-handler / appc-request-handler-core / src / main / java / org / openecomp / appc / requesthandler / impl / RequestValidatorImpl.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.requesthandler.impl;
23
24 import java.time.Instant;
25
26 import org.apache.commons.lang.ObjectUtils;
27 import org.apache.commons.lang.StringUtils;
28 import org.openecomp.appc.common.constant.Constants;
29 import org.openecomp.appc.configuration.Configuration;
30 import org.openecomp.appc.configuration.ConfigurationFactory;
31 import org.openecomp.appc.domainmodel.lcm.CommonHeader;
32 import org.openecomp.appc.domainmodel.lcm.RequestContext;
33 import org.openecomp.appc.domainmodel.lcm.RuntimeContext;
34 import org.openecomp.appc.domainmodel.lcm.VNFContext;
35 import org.openecomp.appc.domainmodel.lcm.VNFOperation;
36 import org.openecomp.appc.executor.UnstableVNFException;
37 import org.openecomp.appc.executor.objects.UniqueRequestIdentifier;
38 import org.openecomp.appc.i18n.Msg;
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.logging.LoggingConstants;
43 import org.openecomp.appc.logging.LoggingUtils;
44 import org.openecomp.appc.requesthandler.LCMStateManager;
45 import org.openecomp.appc.requesthandler.exceptions.*;
46 import org.openecomp.appc.requesthandler.exceptions.DGWorkflowNotFoundException;
47 import org.openecomp.appc.requesthandler.exceptions.DuplicateRequestException;
48 import org.openecomp.appc.requesthandler.exceptions.InvalidInputException;
49 import org.openecomp.appc.requesthandler.exceptions.RequestExpiredException;
50 import org.openecomp.appc.requesthandler.exceptions.VNFNotFoundException;
51 import org.openecomp.appc.requesthandler.exceptions.WorkflowNotFoundException;
52 import org.openecomp.appc.requesthandler.helper.RequestRegistry;
53 import org.openecomp.appc.requesthandler.helper.RequestValidator;
54 import org.openecomp.appc.workflow.WorkFlowManager;
55 import org.openecomp.appc.workflow.objects.WorkflowExistsOutput;
56 import org.openecomp.appc.workflow.objects.WorkflowRequest;
57 import org.openecomp.appc.workingstatemanager.WorkingStateManager;
58 import org.openecomp.sdnc.sli.SvcLogicContext;
59 import org.openecomp.sdnc.sli.SvcLogicException;
60 import org.openecomp.sdnc.sli.SvcLogicResource;
61 import org.openecomp.sdnc.sli.aai.AAIService;
62 import org.osgi.framework.BundleContext;
63 import org.osgi.framework.FrameworkUtil;
64 import org.osgi.framework.ServiceReference;
65
66 import com.att.eelf.configuration.EELFLogger;
67 import com.att.eelf.configuration.EELFManager;
68 import com.att.eelf.i18n.EELFResourceManager;
69
70
71 public class RequestValidatorImpl implements RequestValidator {
72
73     private AAIService aaiService;
74
75     private LifecycleManager lifecyclemanager;
76
77     private WorkFlowManager workflowManager;
78
79     private WorkingStateManager workingStateManager;
80     private LCMStateManager lcmStateManager;
81
82     private final RequestRegistry requestRegistry = new RequestRegistry();
83
84     private final Configuration configuration = ConfigurationFactory.getConfiguration();
85     private final EELFLogger logger = EELFManager.getInstance().getLogger(RequestValidatorImpl.class);
86     private final EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger();
87
88     public void setLifecyclemanager(LifecycleManager lifecyclemanager) {
89         this.lifecyclemanager = lifecyclemanager;
90     }
91
92     public void setWorkflowManager(WorkFlowManager workflowManager) {
93         this.workflowManager = workflowManager;
94     }
95
96     public void setWorkingStateManager(WorkingStateManager workingStateManager) {
97         this.workingStateManager = workingStateManager;
98     }
99
100     public void setLcmStateManager(LCMStateManager lcmStateManager) {
101         this.lcmStateManager = lcmStateManager;
102     }
103
104     public RequestValidatorImpl() {
105     }
106
107     @Override
108     public void validateRequest(RuntimeContext runtimeContext) throws VNFNotFoundException, RequestExpiredException, UnstableVNFException, InvalidInputException, DuplicateRequestException, NoTransitionDefinedException, LifecycleException, WorkflowNotFoundException, DGWorkflowNotFoundException, MissingVNFDataInAAIException, LCMOperationsDisabledException {
109         if (logger.isTraceEnabled()){
110             logger.trace("Entering to validateRequest with RequestHandlerInput = "+ ObjectUtils.toString(runtimeContext));
111         }
112         if(!lcmStateManager.isLCMOperationEnabled()) {
113             LoggingUtils.logErrorMessage(
114                     LoggingConstants.TargetNames.REQUEST_VALIDATOR,
115                     EELFResourceManager.format(Msg.LCM_OPERATIONS_DISABLED),
116                     this.getClass().getCanonicalName());
117             throw new LCMOperationsDisabledException("APPC LCM operations have been administratively disabled");
118         }
119
120         getAAIservice();
121         validateInput(runtimeContext.getRequestContext());
122         checkVNFWorkingState(runtimeContext);
123         String vnfId = runtimeContext.getRequestContext().getActionIdentifiers().getVnfId();
124         VNFContext vnfContext = queryAAI(vnfId);
125         runtimeContext.setVnfContext(vnfContext);
126
127         queryLCM(runtimeContext.getVnfContext().getStatus(), runtimeContext.getRequestContext().getAction());
128         VNFOperation operation = runtimeContext.getRequestContext().getAction();
129         if(!operation.isBuiltIn()) {
130             // for built-in operations skip WF presence check
131             queryWFM(vnfContext, runtimeContext.getRequestContext());
132         }
133     }
134
135     private boolean isValidTTL(String ttl) {
136         if (logger.isTraceEnabled()){
137             logger.trace("Entering to isValidTTL where ttl = "+ ObjectUtils.toString(ttl));
138         }
139         if (ttl == null || ttl.length() == 0) {
140             if (logger.isTraceEnabled()) {
141                 logger.trace("Exiting from isValidTT with (result = "+ ObjectUtils.toString(false)+")");
142             }
143             return false;
144         }
145         try {
146             Integer i = Integer.parseInt(ttl);
147             if (logger.isTraceEnabled()) {
148                 logger.trace("Exiting from isValidTTL with (result = "+ ObjectUtils.toString(i > 0)+")");
149             }
150             return (i > 0);
151         } catch (NumberFormatException e) {
152             if (logger.isTraceEnabled()) {
153                 logger.trace("Exiting from isValidTTL with (result = "+ ObjectUtils.toString(false)+")");
154             }
155             return false;
156         }
157     }
158
159     private void validateInput(RequestContext requestContext) throws RequestExpiredException, InvalidInputException, DuplicateRequestException {
160         if (logger.isTraceEnabled()){
161             logger.trace("Entering to validateInput with RequestHandlerInput = "+ ObjectUtils.toString(requestContext));
162         }
163         if (requestContext.getActionIdentifiers().getVnfId() == null || requestContext.getAction() == null
164                 || requestContext.getActionIdentifiers().getVnfId().length() == 0 || requestContext.getAction().name().length() == 0 ||
165                 null == requestContext.getCommonHeader().getApiVer()) {
166             if (logger.isDebugEnabled()) {
167                 logger.debug("vnfID = " + requestContext.getActionIdentifiers().getVnfId() + ", action = " + requestContext.getAction().name());
168             }
169
170             LoggingUtils.logErrorMessage(
171                     LoggingConstants.TargetNames.REQUEST_VALIDATOR,
172                     EELFResourceManager.format(Msg.APPC_INVALID_INPUT),
173                     this.getClass().getCanonicalName());
174
175             throw new InvalidInputException("vnfID or command is null");
176         }
177         CommonHeader commonHeader = requestContext.getCommonHeader();
178
179         checkForDuplicateRequest(commonHeader);
180
181         Instant inputTimeStamp = commonHeader.getTimeStamp();
182         Instant currentTime = Instant.now();
183
184         // If input timestamp is of future, we reject the request
185         if (inputTimeStamp.isAfter(currentTime)) {
186             if (logger.isDebugEnabled()) {
187                 logger.debug("Input Timestamp is of future = " + inputTimeStamp);
188             }
189             throw new InvalidInputException("Input Timestamp is of future = " + inputTimeStamp);
190         }
191         int ttl = readTTL(commonHeader);
192         logger.debug("TTL value set to (seconds) : " + ttl);
193         Instant expirationTime = inputTimeStamp.plusSeconds(ttl);
194         if (currentTime.isAfter(expirationTime)) {
195
196             LoggingUtils.logErrorMessage(
197                     LoggingConstants.TargetNames.REQUEST_VALIDATOR,
198                     "TTL Expired: Current time - " + currentTime + " Request time: " + expirationTime + " with TTL value: " + ttl,
199                     this.getClass().getCanonicalName());
200
201             throw new RequestExpiredException("TTL Expired");
202         }
203         if (logger.isDebugEnabled()) {
204             logger.debug("Validation of the request is successful");
205         }
206     }
207
208
209     // TODO: Get reference once via Blueprint and get rid of this method
210     private void getAAIservice() {
211         BundleContext bctx = FrameworkUtil.getBundle(AAIService.class).getBundleContext();
212         // Get AAIadapter reference
213         ServiceReference sref = bctx.getServiceReference(AAIService.class.getName());
214         if (sref != null) {
215             logger.info("AAIService from bundlecontext");
216             aaiService = (AAIService) bctx.getService(sref);
217
218         } else {
219             logger.info("AAIService error from bundlecontext");
220             logger.warn("Cannot find service reference for org.openecomp.sdnc.sli.aai.AAIService");
221
222         }
223     }
224
225     private VNFContext queryAAI(String vnfId) throws VNFNotFoundException, MissingVNFDataInAAIException {
226         SvcLogicContext ctx = new SvcLogicContext();
227         ctx = getVnfdata(vnfId, "vnf", ctx);
228
229         VNFContext vnfContext = new VNFContext();
230         populateVnfContext(vnfContext, ctx);
231
232         return vnfContext;
233     }
234
235     private String queryLCM(String orchestrationStatus, VNFOperation action) throws LifecycleException, NoTransitionDefinedException {
236         if (logger.isTraceEnabled()) {
237             logger.trace("Entering to queryLCM  with Orchestration Status = "+ ObjectUtils.toString(orchestrationStatus)+
238                     ", command = "+ ObjectUtils.toString(action));
239         }
240
241         String nextState = lifecyclemanager.getNextState(null, orchestrationStatus, action.name());
242         if (logger.isDebugEnabled()) {
243             logger.trace("Exiting from queryLCM with (LCMResponse = "+ ObjectUtils.toString(nextState)+")");
244         }
245         return nextState;
246     }
247
248     private void queryWFM(VNFContext vnfContext, RequestContext requestContext) throws WorkflowNotFoundException,DGWorkflowNotFoundException {
249
250         checkWorkflowExists(vnfContext, requestContext);
251     }
252
253     private void checkWorkflowExists(VNFContext vnfContext, RequestContext requestContext) throws WorkflowNotFoundException,DGWorkflowNotFoundException {
254
255         WorkflowExistsOutput workflowExistsOutput = workflowManager.workflowExists(getWorkflowQueryParams(vnfContext, requestContext));
256         if (!workflowExistsOutput.isMappingExist()) {
257             if (logger.isDebugEnabled()) {
258                 logger.debug("WorkflowManager : Workflow not found for vnfType = " + vnfContext.getType() + ", version = " + vnfContext.getVersion() + ", command = " + requestContext.getAction().name());
259             }
260
261             LoggingUtils.logErrorMessage(
262                     LoggingConstants.TargetNames.WORKFLOW_MANAGER,
263                     EELFResourceManager.format(Msg.APPC_WORKFLOW_NOT_FOUND, vnfContext.getType(), requestContext.getAction().name()),
264                     this.getClass().getCanonicalName());
265
266
267             throw new WorkflowNotFoundException("Workflow not found for vnfType = " + vnfContext.getType() + ", command = " + requestContext.getAction().name(),vnfContext.getType(),requestContext.getAction().name());
268         }
269         if (!workflowExistsOutput.isDgExist()) {
270             if (logger.isDebugEnabled()) {
271                 logger.debug("WorkflowManager : DG Workflow not found for vnfType = " + vnfContext.getType() + ", version = " + vnfContext.getVersion() + ", command = " + requestContext.getAction().name()+" "+workflowExistsOutput);
272             }
273
274
275             LoggingUtils.logErrorMessage(
276                     LoggingConstants.TargetNames.WORKFLOW_MANAGER,
277                     EELFResourceManager.format(Msg.APPC_WORKFLOW_NOT_FOUND, vnfContext.getType(), requestContext.getAction().name()),
278                     this.getClass().getCanonicalName());
279
280
281             throw new DGWorkflowNotFoundException("Workflow not found for vnfType = " + vnfContext.getType() + ", command = " + requestContext.getAction().name(),
282                     workflowExistsOutput.getWorkflowModule(),workflowExistsOutput.getWorkflowName(),workflowExistsOutput.getWorkflowVersion());
283         }
284     }
285
286     private void populateVnfContext(VNFContext vnfContext, SvcLogicContext ctx) throws MissingVNFDataInAAIException {
287         String vnfType = ctx.getAttribute("vnf.vnf-type");
288         String orchestrationStatus = ctx.getAttribute("vnf.orchestration-status");
289         if(StringUtils.isEmpty(vnfType)){
290             throw new MissingVNFDataInAAIException("vnf-type");
291         }
292         else if(StringUtils.isEmpty(orchestrationStatus)){
293             throw new MissingVNFDataInAAIException("orchestration-status");
294         }
295         vnfContext.setType(vnfType);
296         vnfContext.setStatus(orchestrationStatus);
297         vnfContext.setId(ctx.getAttribute("vnf.vnf-id"));
298         // TODO: Uncomment once A&AI supports VNF version
299         //vnfContext.setVersion(ctx.getAttribute("vnf.vnf-version"));
300         }
301
302     private WorkflowRequest getWorkflowQueryParams(VNFContext vnfContext, RequestContext requestContext) {
303
304         WorkflowRequest workflowRequest = new WorkflowRequest();
305         workflowRequest.setVnfContext(vnfContext);
306         workflowRequest.setRequestContext(requestContext);
307         if (logger.isTraceEnabled()) {
308             logger.trace("Exiting from etWorkflowQueryParams with (WorkflowRequest = "+ ObjectUtils.toString(workflowRequest)+")");
309         }
310         return workflowRequest;
311     }
312
313
314     private void checkForDuplicateRequest(CommonHeader header) throws DuplicateRequestException {
315         if (logger.isTraceEnabled()) {
316             logger.trace("Entering to checkForDuplicateRequest with RequestHeader = "+ ObjectUtils.toString(header));
317         }
318
319         UniqueRequestIdentifier requestIdentifier = new UniqueRequestIdentifier(header.getOriginatorId(), header.getRequestId(), header.getSubRequestId());
320         boolean requestAccepted = requestRegistry.registerRequest(requestIdentifier);
321         if (!requestAccepted) {
322             if (logger.isDebugEnabled()) {
323                 logger.debug("Duplicate Request with " + requestIdentifier);
324             }
325             throw new DuplicateRequestException("Duplicate Request with " + requestIdentifier);
326         }
327     }
328
329     private void checkVNFWorkingState(RuntimeContext runtimeContext) throws UnstableVNFException {
330
331         if (logger.isTraceEnabled()) {
332             logger.trace("Entering to checkVNFWorkingState with RequestHandlerInput = "+ ObjectUtils.toString(runtimeContext.getRequestContext()));
333         }
334         boolean forceFlag = runtimeContext.getRequestContext().getCommonHeader().getFlags() != null ? runtimeContext.getRequestContext().getCommonHeader().getFlags().isForce() : false;
335         String vnfId = runtimeContext.getRequestContext().getActionIdentifiers().getVnfId();
336
337             if (logger.isDebugEnabled()) {
338                 logger.debug("forceFlag = " + forceFlag);
339             }
340         boolean isVNFStable = workingStateManager.isVNFStable(vnfId);
341             if (!isVNFStable && !forceFlag) {
342                 if (logger.isDebugEnabled()) {
343                 logger.debug("VNF is not stable for VNF ID = " + vnfId);
344                 }
345             throw new UnstableVNFException("VNF is not stable for vnfID = " + vnfId);
346             }
347
348         }
349
350
351     private int readTTL(CommonHeader header) {
352         if (logger.isTraceEnabled()) {
353             logger.trace("Entering to readTTL with RequestHandlerInput = "+ ObjectUtils.toString(header));
354         }
355         if (header.getFlags()== null || !isValidTTL(String.valueOf(header.getFlags().getTtl()))) {
356             String defaultTTLStr = configuration.getProperty("org.openecomp.appc.workflow.default.ttl", String.valueOf(Constants.DEFAULT_TTL));
357             return Integer.parseInt(defaultTTLStr);
358         }
359         if (logger.isTraceEnabled()) {
360             logger.trace("Exiting from readTTL with (TTL = "+  ObjectUtils.toString(header.getFlags().getTtl())+")");
361         }
362         return header.getFlags().getTtl();
363     }
364
365
366     private SvcLogicContext getVnfdata(String vnf_id, String prefix, SvcLogicContext ctx) throws VNFNotFoundException {
367         if (logger.isTraceEnabled()) {
368             logger.trace("Entering to getVnfdata with vnfid = "+ ObjectUtils.toString(vnf_id) + ", prefix = "+ ObjectUtils.toString(prefix)+ ", SvcLogicContext"+ ObjectUtils.toString(ctx));
369         }
370
371         String key = "vnf-id = '" + vnf_id + "'";
372         logger.debug("inside getVnfdata=== " + key);
373         try {
374             Instant beginTimestamp = Instant.now();
375             SvcLogicResource.QueryStatus response = aaiService.query("generic-vnf", false, null, key, prefix, null, ctx);
376             Instant endTimestamp = Instant.now();
377             String status = SvcLogicResource.QueryStatus.SUCCESS.equals(response) ? LoggingConstants.StatusCodes.COMPLETE : LoggingConstants.StatusCodes.ERROR;
378             LoggingUtils.logMetricsMessage(
379                     beginTimestamp,
380                     endTimestamp,
381                     LoggingConstants.TargetNames.AAI,
382                     LoggingConstants.TargetServiceNames.AAIServiceNames.QUERY,
383                     status,
384                     "",
385                     response.name(),
386                     this.getClass().getCanonicalName());
387             if (SvcLogicResource.QueryStatus.NOT_FOUND.equals(response)) {
388                 throw new VNFNotFoundException("VNF not found for vnf_id = " + vnf_id);
389             } else if (SvcLogicResource.QueryStatus.FAILURE.equals(response)) {
390                 throw new RuntimeException("Error Querying AAI with vnfID = " + vnf_id);
391             }
392             logger.info("AAIResponse: " + response.toString());
393         } catch (SvcLogicException e) {
394
395             LoggingUtils.logErrorMessage(
396                     LoggingConstants.TargetServiceNames.AAIServiceNames.GET_VNF_DATA,
397                     "Error in getVnfdata" + e,
398                     this.getClass().getCanonicalName());
399
400             throw new RuntimeException(e);
401         }
402         if (logger.isTraceEnabled()) {
403             logger.trace("Exiting from getVnfdata with (SvcLogicContext = "+ ObjectUtils.toString(ctx)+")");
404         }
405         return ctx;
406     }
407
408 }