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