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