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