aboutsummaryrefslogtreecommitdiffstats
path: root/app-c/appc/appc-dispatcher/appc-request-handler/appc-request-handler-core/src/main/java/org/openecomp/appc/requesthandler/impl/RequestValidatorImpl.java
blob: 0871a8f97adb2268b00aca13b9af9ca36babda52 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
/*-
 * ============LICENSE_START=======================================================
 * openECOMP : APP-C
 * ================================================================================
 * Copyright (C) 2017 AT&T Intellectual Property. All rights
 * 						reserved.
 * ================================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ============LICENSE_END=========================================================
 */

package org.openecomp.appc.requesthandler.impl;

import org.apache.commons.lang.ObjectUtils;
import org.openecomp.appc.common.constant.Constants;
import org.openecomp.appc.configuration.Configuration;
import org.openecomp.appc.configuration.ConfigurationFactory;
import org.openecomp.appc.domainmodel.lcm.*;
import org.openecomp.appc.executor.UnstableVNFException;
import org.openecomp.appc.executor.objects.UniqueRequestIdentifier;
import org.openecomp.appc.i18n.Msg;
import org.openecomp.appc.lifecyclemanager.LifecycleManager;
import org.openecomp.appc.lifecyclemanager.objects.LifecycleException;
import org.openecomp.appc.lifecyclemanager.objects.NoTransitionDefinedException;
import org.openecomp.appc.logging.LoggingConstants;
import org.openecomp.appc.logging.LoggingUtils;
import org.openecomp.appc.requesthandler.exceptions.*;
import org.openecomp.appc.requesthandler.helper.RequestRegistry;
import org.openecomp.appc.requesthandler.helper.RequestValidator;
import org.openecomp.appc.workflow.WorkFlowManager;
import org.openecomp.appc.workflow.objects.WorkflowExistsOutput;
import org.openecomp.appc.workflow.objects.WorkflowRequest;
import org.openecomp.appc.workingstatemanager.WorkingStateManager;
import com.att.eelf.configuration.EELFLogger;
import com.att.eelf.configuration.EELFManager;
import com.att.eelf.i18n.EELFResourceManager;
import org.openecomp.sdnc.sli.SvcLogicContext;
import org.openecomp.sdnc.sli.SvcLogicException;
import org.openecomp.sdnc.sli.SvcLogicResource;
import org.openecomp.sdnc.sli.aai.AAIService;
import org.osgi.framework.BundleContext;
import org.osgi.framework.FrameworkUtil;
import org.osgi.framework.ServiceReference;

import java.util.Calendar;
import java.util.Date;


public class RequestValidatorImpl implements RequestValidator {

    private AAIService aaiService;

    private LifecycleManager lifecyclemanager;

    private WorkFlowManager workflowManager;

    private WorkingStateManager workingStateManager;

    private final RequestRegistry requestRegistry = new RequestRegistry();

    private final Configuration configuration = ConfigurationFactory.getConfiguration();
    private final EELFLogger logger = EELFManager.getInstance().getLogger(RequestValidatorImpl.class);
    private final EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger();

    public void setLifecyclemanager(LifecycleManager lifecyclemanager) {
        this.lifecyclemanager = lifecyclemanager;
    }

    public void setWorkflowManager(WorkFlowManager workflowManager) {
        this.workflowManager = workflowManager;
    }

    public void setWorkingStateManager(WorkingStateManager workingStateManager) {
        this.workingStateManager = workingStateManager;
    }

    public RequestValidatorImpl() {
    }

    @Override
    public void validateRequest(RuntimeContext runtimeContext) throws VNFNotFoundException, RequestExpiredException, UnstableVNFException, InvalidInputException, DuplicateRequestException, NoTransitionDefinedException, LifecycleException, WorkflowNotFoundException,DGWorkflowNotFoundException {
        if (logger.isTraceEnabled()){
            logger.trace("Entering to validateRequest with RequestHandlerInput = "+ ObjectUtils.toString(runtimeContext));
        }
        getAAIservice();
        validateInput(runtimeContext.getRequestContext());
        checkVNFWorkingState(runtimeContext);
        String vnfId = runtimeContext.getRequestContext().getActionIdentifiers().getVnfId();
        VNFContext vnfContext = queryAAI(vnfId);
        runtimeContext.setVnfContext(vnfContext);

        queryLCM(runtimeContext.getVnfContext().getStatus(), runtimeContext.getRequestContext().getAction());
        VNFOperation operation = runtimeContext.getRequestContext().getAction();
        if(!operation.isBuiltIn()) {
            // for built-in operations skip WF presence check
            queryWFM(vnfContext, runtimeContext.getRequestContext());
        }
        }

     private boolean isValidTTL(String ttl) {
        if (logger.isTraceEnabled()){
            logger.trace("Entering to isValidTTL where ttl = "+ ObjectUtils.toString(ttl));
        }
        if (ttl == null || ttl.length() == 0) {
            if (logger.isTraceEnabled()) {
                logger.trace("Exiting from isValidTT with (result = "+ ObjectUtils.toString(false)+")");
            }
            return false;
        }
        try {
            Integer i = Integer.parseInt(ttl);
            if (logger.isTraceEnabled()) {
                logger.trace("Exiting from isValidTTL with (result = "+ ObjectUtils.toString(i > 0)+")");
            }
            return (i > 0);
        } catch (NumberFormatException e) {
            if (logger.isTraceEnabled()) {
                logger.trace("Exiting from isValidTTL with (result = "+ ObjectUtils.toString(false)+")");
            }
            return false;
        }
    }

    private void validateInput(RequestContext requestContext) throws RequestExpiredException, InvalidInputException, DuplicateRequestException {
        if (logger.isTraceEnabled()){
            logger.trace("Entering to validateInput with RequestHandlerInput = "+ ObjectUtils.toString(requestContext));
        }
        if (requestContext.getActionIdentifiers().getVnfId() == null || requestContext.getAction() == null
                || requestContext.getActionIdentifiers().getVnfId().length() == 0 || requestContext.getAction().name().length() == 0 ||
                null == requestContext.getCommonHeader().getApiVer()) {
            if (logger.isDebugEnabled()) {
                logger.debug("vnfID = " + requestContext.getActionIdentifiers().getVnfId() + ", action = " + requestContext.getAction().name());
            }

            LoggingUtils.logErrorMessage(
                    LoggingConstants.TargetNames.REQUEST_VALIDATOR,
                    EELFResourceManager.format(Msg.APPC_INVALID_INPUT),
                    this.getClass().getCanonicalName());

            throw new InvalidInputException("vnfID or command is null");
        }
        CommonHeader commonHeader = requestContext.getCommonHeader();

        checkForDuplicateRequest(commonHeader);

        Calendar inputTimeStamp = DateToCalendar(commonHeader.getTimeStamp());
        Calendar currentTime = Calendar.getInstance();

        // If input timestamp is of future, we reject the request
        if (inputTimeStamp.getTime().getTime() > currentTime.getTime().getTime()) {
            if (logger.isDebugEnabled()) {
                logger.debug("Input Timestamp is of future = " + inputTimeStamp.getTime());
            }
            throw new InvalidInputException("Input Timestamp is of future = " + inputTimeStamp.getTime());
        }
        Integer ttl = readTTL(commonHeader);
        logger.debug("TTL value set to (seconds) : " + ttl);
        inputTimeStamp.add(Calendar.SECOND, ttl);
        if (currentTime.getTime().getTime() >= inputTimeStamp.getTime().getTime()) {

            LoggingUtils.logErrorMessage(
                    LoggingConstants.TargetNames.REQUEST_VALIDATOR,
                    "TTL Expired: Current time - " + currentTime.getTime().getTime() + " Request time: " + inputTimeStamp.getTime().getTime() + " with TTL value: " + ttl,
                    this.getClass().getCanonicalName());

            throw new RequestExpiredException("TTL Expired");
        }
        if (logger.isDebugEnabled()) {
            logger.debug("Validation of the request is successful");
        }
    }


    private static Calendar DateToCalendar(Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        return cal;
    }

    // TODO: Get reference once via Blueprint and get rid of this method
    private void getAAIservice() {
        BundleContext bctx = FrameworkUtil.getBundle(AAIService.class).getBundleContext();
        // Get AAIadapter reference
        ServiceReference sref = bctx.getServiceReference(AAIService.class.getName());
        if (sref != null) {
            logger.info("AAIService from bundlecontext");
            aaiService = (AAIService) bctx.getService(sref);

        } else {
            logger.info("AAIService error from bundlecontext");
            logger.warn("Cannot find service reference for org.openecomp.sdnc.sli.aai.AAIService");

        }
    }

    private VNFContext queryAAI(String vnfId) throws VNFNotFoundException {
        SvcLogicContext ctx = new SvcLogicContext();
        ctx = getVnfdata(vnfId, "vnf", ctx);

        VNFContext vnfContext = new VNFContext();
        populateVnfContext(vnfContext, ctx);

        return vnfContext;
    }

    private String queryLCM(String orchestrationStatus, VNFOperation action) throws LifecycleException, NoTransitionDefinedException {
        if (logger.isTraceEnabled()) {
            logger.trace("Entering to queryLCM  with Orchestration Status = "+ ObjectUtils.toString(orchestrationStatus)+
                    ", command = "+ ObjectUtils.toString(action));
        }

        String nextState = lifecyclemanager.getNextState(null, orchestrationStatus, action.name());
        if (logger.isDebugEnabled()) {
            logger.trace("Exiting from queryLCM with (LCMResponse = "+ ObjectUtils.toString(nextState)+")");
        }
        return nextState;
    }

    private void queryWFM(VNFContext vnfContext, RequestContext requestContext) throws WorkflowNotFoundException,DGWorkflowNotFoundException {

        checkWorkflowExists(vnfContext, requestContext);
    }

    private void checkWorkflowExists(VNFContext vnfContext, RequestContext requestContext) throws WorkflowNotFoundException,DGWorkflowNotFoundException {

        WorkflowExistsOutput workflowExistsOutput = workflowManager.workflowExists(getWorkflowQueryParams(vnfContext, requestContext));
        if (!workflowExistsOutput.isMappingExist()) {
            if (logger.isDebugEnabled()) {
                logger.debug("WorkflowManager : Workflow not found for vnfType = " + vnfContext.getType() + ", version = " + vnfContext.getVersion() + ", command = " + requestContext.getAction().name());
            }

            LoggingUtils.logErrorMessage(
                    LoggingConstants.TargetNames.WORKFLOW_MANAGER,
                    EELFResourceManager.format(Msg.APPC_WORKFLOW_NOT_FOUND, vnfContext.getType(), requestContext.getAction().name()),
                    this.getClass().getCanonicalName());


            throw new WorkflowNotFoundException("Workflow not found for vnfType = " + vnfContext.getType() + ", command = " + requestContext.getAction().name(),vnfContext.getType(),requestContext.getAction().name());
        }
        if (!workflowExistsOutput.isDgExist()) {
            if (logger.isDebugEnabled()) {
                logger.debug("WorkflowManager : DG Workflow not found for vnfType = " + vnfContext.getType() + ", version = " + vnfContext.getVersion() + ", command = " + requestContext.getAction().name()+" "+workflowExistsOutput);
            }


            LoggingUtils.logErrorMessage(
                    LoggingConstants.TargetNames.WORKFLOW_MANAGER,
                    EELFResourceManager.format(Msg.APPC_WORKFLOW_NOT_FOUND, vnfContext.getType(), requestContext.getAction().name()),
                    this.getClass().getCanonicalName());


            throw new DGWorkflowNotFoundException("Workflow not found for vnfType = " + vnfContext.getType() + ", command = " + requestContext.getAction().name(),
                    workflowExistsOutput.getWorkflowModule(),workflowExistsOutput.getWorkflowName(),workflowExistsOutput.getWorkflowVersion());
        }
    }

    private void populateVnfContext(VNFContext vnfContext, SvcLogicContext ctx) {
        vnfContext.setType(ctx.getAttribute("vnf.vnf-type"));
        vnfContext.setStatus(ctx.getAttribute("vnf.orchestration-status"));
        vnfContext.setId(ctx.getAttribute("vnf.vnf-id"));
        // TODO: Uncomment once A&AI supports VNF version
        //vnfContext.setVersion(ctx.getAttribute("vnf.vnf-version"));
        }

    private WorkflowRequest getWorkflowQueryParams(VNFContext vnfContext, RequestContext requestContext) {

        WorkflowRequest workflowRequest = new WorkflowRequest();
        workflowRequest.setVnfContext(vnfContext);
        workflowRequest.setRequestContext(requestContext);
        if (logger.isTraceEnabled()) {
            logger.trace("Exiting from etWorkflowQueryParams with (WorkflowRequest = "+ ObjectUtils.toString(workflowRequest)+")");
        }
        return workflowRequest;
    }


    private void checkForDuplicateRequest(CommonHeader header) throws DuplicateRequestException {
        if (logger.isTraceEnabled()) {
            logger.trace("Entering to checkForDuplicateRequest with RequestHeader = "+ ObjectUtils.toString(header));
        }

        UniqueRequestIdentifier requestIdentifier = new UniqueRequestIdentifier(header.getOriginatorId(), header.getRequestId(), header.getSubRequestId());
        boolean requestAccepted = requestRegistry.registerRequest(requestIdentifier);
        if (!requestAccepted) {
            if (logger.isDebugEnabled()) {
                logger.debug("Duplicate Request with " + requestIdentifier);
            }
            throw new DuplicateRequestException("Duplicate Request with " + requestIdentifier);
        }
    }

    private void checkVNFWorkingState(RuntimeContext runtimeContext) throws UnstableVNFException {

        if (logger.isTraceEnabled()) {
            logger.trace("Entering to checkVNFWorkingState with RequestHandlerInput = "+ ObjectUtils.toString(runtimeContext.getRequestContext()));
        }
        boolean forceFlag = runtimeContext.getRequestContext().getCommonHeader().getFlags() != null ? runtimeContext.getRequestContext().getCommonHeader().getFlags().isForce() : false;
        String vnfId = runtimeContext.getRequestContext().getActionIdentifiers().getVnfId();

            if (logger.isDebugEnabled()) {
                logger.debug("forceFlag = " + forceFlag);
            }
        boolean isVNFStable = workingStateManager.isVNFStable(vnfId);
            if (!isVNFStable && !forceFlag) {
                if (logger.isDebugEnabled()) {
                logger.debug("VNF is not stable for VNF ID = " + vnfId);
                }
            throw new UnstableVNFException("VNF is not stable for vnfID = " + vnfId);
            }

        }


    private Integer readTTL(CommonHeader header) {
        if (logger.isTraceEnabled()) {
            logger.trace("Entering to readTTL with RequestHandlerInput = "+ ObjectUtils.toString(header));
        }
        if (header.getFlags()== null || !isValidTTL(String.valueOf(header.getFlags().getTtl()))) {
            String defaultTTLStr = configuration.getProperty("org.openecomp.appc.workflow.default.ttl", String.valueOf(Constants.DEFAULT_TTL));
            Integer defaultTTL = Integer.parseInt(defaultTTLStr);
            return defaultTTL;
        }
        if (logger.isTraceEnabled()) {
            logger.trace("Exiting from readTTL with (TTL = "+  ObjectUtils.toString(header.getFlags().getTtl())+")");
        }
        return header.getFlags().getTtl();
    }


    private SvcLogicContext getVnfdata(String vnf_id, String prefix, SvcLogicContext ctx) throws VNFNotFoundException {
        if (logger.isTraceEnabled()) {
            logger.trace("Entering to getVnfdata with vnfid = "+ ObjectUtils.toString(vnf_id) + ", prefix = "+ ObjectUtils.toString(prefix)+ ", SvcLogicContext"+ ObjectUtils.toString(ctx));
        }

        String key = "vnf-id = '" + vnf_id + "'";
        logger.debug("inside getVnfdata=== " + key);
        try {
            Date beginTimestamp = new Date();
            SvcLogicResource.QueryStatus response = aaiService.query("generic-vnf", false, null, key, prefix, null, ctx);
            Date endTimestamp = new Date();
            String status = SvcLogicResource.QueryStatus.SUCCESS.equals(response) ? LoggingConstants.StatusCodes.COMPLETE : LoggingConstants.StatusCodes.ERROR;
            LoggingUtils.logMetricsMessage(
                    beginTimestamp,
                    endTimestamp,
                    LoggingConstants.TargetNames.AAI,
                    LoggingConstants.TargetServiceNames.AAIServiceNames.QUERY,
                    status,
                    "",
                    response.name(),
                    this.getClass().getCanonicalName());
            if (SvcLogicResource.QueryStatus.NOT_FOUND.equals(response)) {
                throw new VNFNotFoundException("VNF not found for vnf_id = " + vnf_id);
            } else if (SvcLogicResource.QueryStatus.FAILURE.equals(response)) {
                throw new RuntimeException("Error Querying AAI with vnfID = " + vnf_id);
            }
            logger.info("AAIResponse: " + response.toString());
        } catch (SvcLogicException e) {

            LoggingUtils.logErrorMessage(
                    LoggingConstants.TargetServiceNames.AAIServiceNames.GET_VNF_DATA,
                    "Error in getVnfdata" + e,
                    this.getClass().getCanonicalName());

            throw new RuntimeException(e);
        }
        if (logger.isTraceEnabled()) {
            logger.trace("Exiting from getVnfdata with (SvcLogicContext = "+ ObjectUtils.toString(ctx)+")");
        }
        return ctx;
    }

}