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