2  * ============LICENSE_START=======================================================
 
   4  * ================================================================================
 
   5  * Copyright (C) 2017 AT&T Intellectual Property. All rights
 
   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
 
  12  *      http://www.apache.org/licenses/LICENSE-2.0
 
  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=========================================================
 
  22 package org.openecomp.appc.requesthandler.impl;
 
  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;
 
  55 import java.util.Calendar;
 
  56 import java.util.Date;
 
  59 public class RequestValidatorImpl implements RequestValidator {
 
  61     private AAIService aaiService;
 
  63     private LifecycleManager lifecyclemanager;
 
  65     private WorkFlowManager workflowManager;
 
  67     private WorkingStateManager workingStateManager;
 
  69     private final RequestRegistry requestRegistry = new RequestRegistry();
 
  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();
 
  75     public void setLifecyclemanager(LifecycleManager lifecyclemanager) {
 
  76         this.lifecyclemanager = lifecyclemanager;
 
  79     public void setWorkflowManager(WorkFlowManager workflowManager) {
 
  80         this.workflowManager = workflowManager;
 
  83     public void setWorkingStateManager(WorkingStateManager workingStateManager) {
 
  84         this.workingStateManager = workingStateManager;
 
  87     public RequestValidatorImpl() {
 
  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));
 
  96         validateInput(runtimeContext.getRequestContext());
 
  97         checkVNFWorkingState(runtimeContext);
 
  98         String vnfId = runtimeContext.getRequestContext().getActionIdentifiers().getVnfId();
 
  99         VNFContext vnfContext = queryAAI(vnfId);
 
 100         runtimeContext.setVnfContext(vnfContext);
 
 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());
 
 110      private boolean isValidTTL(String ttl) {
 
 111         if (logger.isTraceEnabled()){
 
 112             logger.trace("Entering to isValidTTL where ttl = "+ ObjectUtils.toString(ttl));
 
 114         if (ttl == null || ttl.length() == 0) {
 
 115             if (logger.isTraceEnabled()) {
 
 116                 logger.trace("Exiting from isValidTT with (result = "+ ObjectUtils.toString(false)+")");
 
 121             Integer i = Integer.parseInt(ttl);
 
 122             if (logger.isTraceEnabled()) {
 
 123                 logger.trace("Exiting from isValidTTL with (result = "+ ObjectUtils.toString(i > 0)+")");
 
 126         } catch (NumberFormatException e) {
 
 127             if (logger.isTraceEnabled()) {
 
 128                 logger.trace("Exiting from isValidTTL with (result = "+ ObjectUtils.toString(false)+")");
 
 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));
 
 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());
 
 145             LoggingUtils.logErrorMessage(
 
 146                     LoggingConstants.TargetNames.REQUEST_VALIDATOR,
 
 147                     EELFResourceManager.format(Msg.APPC_INVALID_INPUT),
 
 148                     this.getClass().getCanonicalName());
 
 150             throw new InvalidInputException("vnfID or command is null");
 
 152         CommonHeader commonHeader = requestContext.getCommonHeader();
 
 154         checkForDuplicateRequest(commonHeader);
 
 156         Calendar inputTimeStamp = DateToCalendar(commonHeader.getTimeStamp());
 
 157         Calendar currentTime = Calendar.getInstance();
 
 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());
 
 164             throw new InvalidInputException("Input Timestamp is of future = " + inputTimeStamp.getTime());
 
 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()) {
 
 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());
 
 176             throw new RequestExpiredException("TTL Expired");
 
 178         if (logger.isDebugEnabled()) {
 
 179             logger.debug("Validation of the request is successful");
 
 184     private static Calendar DateToCalendar(Date date) {
 
 185         Calendar cal = Calendar.getInstance();
 
 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());
 
 196             logger.info("AAIService from bundlecontext");
 
 197             aaiService = (AAIService) bctx.getService(sref);
 
 200             logger.info("AAIService error from bundlecontext");
 
 201             logger.warn("Cannot find service reference for org.openecomp.sdnc.sli.aai.AAIService");
 
 206     private VNFContext queryAAI(String vnfId) throws VNFNotFoundException {
 
 207         SvcLogicContext ctx = new SvcLogicContext();
 
 208         ctx = getVnfdata(vnfId, "vnf", ctx);
 
 210         VNFContext vnfContext = new VNFContext();
 
 211         populateVnfContext(vnfContext, ctx);
 
 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));
 
 222         String nextState = lifecyclemanager.getNextState(null, orchestrationStatus, action.name());
 
 223         if (logger.isDebugEnabled()) {
 
 224             logger.trace("Exiting from queryLCM with (LCMResponse = "+ ObjectUtils.toString(nextState)+")");
 
 229     private void queryWFM(VNFContext vnfContext, RequestContext requestContext) throws WorkflowNotFoundException,DGWorkflowNotFoundException {
 
 231         checkWorkflowExists(vnfContext, requestContext);
 
 234     private void checkWorkflowExists(VNFContext vnfContext, RequestContext requestContext) throws WorkflowNotFoundException,DGWorkflowNotFoundException {
 
 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());
 
 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());
 
 248             throw new WorkflowNotFoundException("Workflow not found for vnfType = " + vnfContext.getType() + ", command = " + requestContext.getAction().name(),vnfContext.getType(),requestContext.getAction().name());
 
 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);
 
 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());
 
 262             throw new DGWorkflowNotFoundException("Workflow not found for vnfType = " + vnfContext.getType() + ", command = " + requestContext.getAction().name(),
 
 263                     workflowExistsOutput.getWorkflowModule(),workflowExistsOutput.getWorkflowName(),workflowExistsOutput.getWorkflowVersion());
 
 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"));
 
 275     private WorkflowRequest getWorkflowQueryParams(VNFContext vnfContext, RequestContext requestContext) {
 
 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)+")");
 
 283         return workflowRequest;
 
 287     private void checkForDuplicateRequest(CommonHeader header) throws DuplicateRequestException {
 
 288         if (logger.isTraceEnabled()) {
 
 289             logger.trace("Entering to checkForDuplicateRequest with RequestHeader = "+ ObjectUtils.toString(header));
 
 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);
 
 298             throw new DuplicateRequestException("Duplicate Request with " + requestIdentifier);
 
 302     private void checkVNFWorkingState(RuntimeContext runtimeContext) throws UnstableVNFException {
 
 304         if (logger.isTraceEnabled()) {
 
 305             logger.trace("Entering to checkVNFWorkingState with RequestHandlerInput = "+ ObjectUtils.toString(runtimeContext.getRequestContext()));
 
 307         boolean forceFlag = runtimeContext.getRequestContext().getCommonHeader().getFlags() != null ? runtimeContext.getRequestContext().getCommonHeader().getFlags().isForce() : false;
 
 308         String vnfId = runtimeContext.getRequestContext().getActionIdentifiers().getVnfId();
 
 310             if (logger.isDebugEnabled()) {
 
 311                 logger.debug("forceFlag = " + forceFlag);
 
 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);
 
 318             throw new UnstableVNFException("VNF is not stable for vnfID = " + vnfId);
 
 324     private Integer readTTL(CommonHeader header) {
 
 325         if (logger.isTraceEnabled()) {
 
 326             logger.trace("Entering to readTTL with RequestHandlerInput = "+ ObjectUtils.toString(header));
 
 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);
 
 333         if (logger.isTraceEnabled()) {
 
 334             logger.trace("Exiting from readTTL with (TTL = "+  ObjectUtils.toString(header.getFlags().getTtl())+")");
 
 336         return header.getFlags().getTtl();
 
 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));
 
 345         String key = "vnf-id = '" + vnf_id + "'";
 
 346         logger.debug("inside getVnfdata=== " + key);
 
 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(
 
 355                     LoggingConstants.TargetNames.AAI,
 
 356                     LoggingConstants.TargetServiceNames.AAIServiceNames.QUERY,
 
 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);
 
 366             logger.info("AAIResponse: " + response.toString());
 
 367         } catch (SvcLogicException e) {
 
 369             LoggingUtils.logErrorMessage(
 
 370                     LoggingConstants.TargetServiceNames.AAIServiceNames.GET_VNF_DATA,
 
 371                     "Error in getVnfdata" + e,
 
 372                     this.getClass().getCanonicalName());
 
 374             throw new RuntimeException(e);
 
 376         if (logger.isTraceEnabled()) {
 
 377             logger.trace("Exiting from getVnfdata with (SvcLogicContext = "+ ObjectUtils.toString(ctx)+")");