Code clean-up in ChefAdapterImpl.java
[appc.git] / appc-dispatcher / appc-request-handler / appc-request-handler-core / src / main / java / org / openecomp / appc / requesthandler / impl / AbstractRequestValidatorImpl.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 com.att.eelf.configuration.EELFLogger;
28 import com.att.eelf.configuration.EELFManager;
29 import com.att.eelf.i18n.EELFResourceManager;
30 import org.apache.commons.lang.ObjectUtils;
31 import org.apache.commons.lang.StringUtils;
32 import org.openecomp.appc.requesthandler.constant.Constants;
33 import org.openecomp.appc.configuration.Configuration;
34 import org.openecomp.appc.configuration.ConfigurationFactory;
35 import org.openecomp.appc.domainmodel.lcm.CommonHeader;
36 import org.openecomp.appc.domainmodel.lcm.RequestContext;
37 import org.openecomp.appc.domainmodel.lcm.RuntimeContext;
38 import org.openecomp.appc.domainmodel.lcm.VNFContext;
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.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.sdnc.sli.SvcLogicContext;
55 import org.openecomp.sdnc.sli.SvcLogicException;
56 import org.openecomp.sdnc.sli.SvcLogicResource;
57 import org.openecomp.sdnc.sli.aai.AAIService;
58 import org.osgi.framework.BundleContext;
59 import org.osgi.framework.FrameworkUtil;
60 import org.osgi.framework.ServiceReference;
61
62 import java.time.Instant;
63 import java.util.Calendar;
64 import java.util.Date;
65
66 public abstract class AbstractRequestValidatorImpl implements RequestValidator {
67
68     protected final EELFLogger logger = EELFManager.getInstance().getLogger(RequestValidatorImpl.class);
69     private final Configuration configuration = ConfigurationFactory.getConfiguration();
70     protected LifecycleManager lifecyclemanager;
71     protected LCMStateManager lcmStateManager;
72     private AAIService aaiService;
73     private WorkFlowManager workflowManager;
74     private RequestRegistry requestRegistry = new RequestRegistry();
75
76     protected static Calendar DateToCalendar(Date date) {
77         Calendar cal = Calendar.getInstance();
78         cal.setTime(date);
79         return cal;
80     }
81
82     public void setWorkflowManager(WorkFlowManager workflowManager) {
83         this.workflowManager = workflowManager;
84     }
85
86     public void setLcmStateManager(LCMStateManager lcmStateManager) {
87         this.lcmStateManager = lcmStateManager;
88     }
89
90     public void setRequestRegistry(RequestRegistry requestRegistry) {
91         this.requestRegistry = requestRegistry;
92     }
93
94     public abstract void validateRequest(RuntimeContext runtimeContext) throws VNFNotFoundException, RequestExpiredException, UnstableVNFException, InvalidInputException, DuplicateRequestException, NoTransitionDefinedException, LifecycleException, WorkflowNotFoundException, DGWorkflowNotFoundException, MissingVNFDataInAAIException, LCMOperationsDisabledException;
95
96     private boolean isValidTTL(String ttl) {
97         if (logger.isTraceEnabled()){
98             logger.trace("Entering to isValidTTL where ttl = "+ ObjectUtils.toString(ttl));
99         }
100         if (ttl == null || ttl.length() == 0) {
101             if (logger.isTraceEnabled()) {
102                 logger.trace("Exiting from isValidTT with (result = "+ ObjectUtils.toString(false)+")");
103             }
104             return false;
105         }
106         try {
107             Integer i = Integer.parseInt(ttl);
108             if (logger.isTraceEnabled()) {
109                 logger.trace("Exiting from isValidTTL with (result = "+ ObjectUtils.toString(i > 0)+")");
110             }
111             return (i > 0);
112         } catch (NumberFormatException e) {
113             if (logger.isTraceEnabled()) {
114                 logger.trace("Exiting from isValidTTL with (result = "+ ObjectUtils.toString(false)+")");
115             }
116             return false;
117         }
118     }
119
120     protected void getAAIservice() {
121         BundleContext bctx = FrameworkUtil.getBundle(AAIService.class).getBundleContext();
122         // Get AAIadapter reference
123         ServiceReference sref = bctx.getServiceReference(AAIService.class.getName());
124         if (sref != null) {
125             logger.info("AAIService from bundlecontext");
126             aaiService = (AAIService) bctx.getService(sref);
127
128         } else {
129             logger.info("AAIService error from bundlecontext");
130             logger.warn("Cannot find service reference for org.openecomp.sdnc.sli.aai.AAIService");
131
132         }
133     }
134
135     protected VNFContext queryAAI(String vnfId) throws VNFNotFoundException, MissingVNFDataInAAIException {
136         SvcLogicContext ctx = new SvcLogicContext();
137         ctx = getVnfdata(vnfId, "vnf", ctx);
138
139         VNFContext vnfContext = new VNFContext();
140         populateVnfContext(vnfContext, ctx);
141
142         return vnfContext;
143     }
144
145     protected void queryWFM(VNFContext vnfContext, RequestContext requestContext) throws WorkflowNotFoundException,DGWorkflowNotFoundException {
146
147         checkWorkflowExists(vnfContext, requestContext);
148     }
149
150     private void checkWorkflowExists(VNFContext vnfContext, RequestContext requestContext) throws WorkflowNotFoundException,DGWorkflowNotFoundException {
151
152         WorkflowExistsOutput workflowExistsOutput = workflowManager.workflowExists(getWorkflowQueryParams(vnfContext, requestContext));
153         if (!workflowExistsOutput.isMappingExist()) {
154             if (logger.isDebugEnabled()) {
155                 logger.debug("WorkflowManager : Workflow not found for vnfType = " + vnfContext.getType() + ", version = " + vnfContext.getVersion() + ", command = " + requestContext.getAction().name());
156             }
157
158             LoggingUtils.logErrorMessage(
159                     LoggingConstants.TargetNames.WORKFLOW_MANAGER,
160                     EELFResourceManager.format(Msg.APPC_WORKFLOW_NOT_FOUND, vnfContext.getType(), requestContext.getAction().name()),
161                     this.getClass().getCanonicalName());
162
163
164             throw new WorkflowNotFoundException("Workflow not found for vnfType = " + vnfContext.getType() + ", command = " + requestContext.getAction().name(),vnfContext.getType(),requestContext.getAction().name());
165         }
166         if (!workflowExistsOutput.isDgExist()) {
167             if (logger.isDebugEnabled()) {
168                 logger.debug("WorkflowManager : DG Workflow not found for vnfType = " + vnfContext.getType() + ", version = " + vnfContext.getVersion() + ", command = " + requestContext.getAction().name()+" "+workflowExistsOutput);
169             }
170
171
172             LoggingUtils.logErrorMessage(
173                     LoggingConstants.TargetNames.WORKFLOW_MANAGER,
174                     EELFResourceManager.format(Msg.APPC_WORKFLOW_NOT_FOUND, vnfContext.getType(), requestContext.getAction().name()),
175                     this.getClass().getCanonicalName());
176
177
178             throw new DGWorkflowNotFoundException("Workflow not found for vnfType = " + vnfContext.getType() + ", command = " + requestContext.getAction().name(),
179                     workflowExistsOutput.getWorkflowModule(),workflowExistsOutput.getWorkflowName(),workflowExistsOutput.getWorkflowVersion());
180         }
181     }
182
183     private void populateVnfContext(VNFContext vnfContext, SvcLogicContext ctx) throws MissingVNFDataInAAIException {
184         String vnfType = ctx.getAttribute("vnf.vnf-type");
185         String orchestrationStatus = ctx.getAttribute("vnf.orchestration-status");
186         if(StringUtils.isEmpty(vnfType)){
187             throw new MissingVNFDataInAAIException("vnf-type");
188         }
189         else if(StringUtils.isEmpty(orchestrationStatus)){
190             throw new MissingVNFDataInAAIException("orchestration-status");
191         }
192         vnfContext.setType(vnfType);
193         vnfContext.setStatus(orchestrationStatus);
194         vnfContext.setId(ctx.getAttribute("vnf.vnf-id"));
195     }
196
197     private WorkflowRequest getWorkflowQueryParams(VNFContext vnfContext, RequestContext requestContext) {
198
199         WorkflowRequest workflowRequest = new WorkflowRequest();
200         workflowRequest.setVnfContext(vnfContext);
201         workflowRequest.setRequestContext(requestContext);
202         if (logger.isTraceEnabled()) {
203             logger.trace("Exiting from etWorkflowQueryParams with (WorkflowRequest = "+ ObjectUtils.toString(workflowRequest)+")");
204         }
205         return workflowRequest;
206     }
207
208     protected void checkForDuplicateRequest(CommonHeader header) throws DuplicateRequestException {
209         if (logger.isTraceEnabled()) {
210             logger.trace("Entering to checkForDuplicateRequest with RequestHeader = "+ ObjectUtils.toString(header));
211         }
212
213         UniqueRequestIdentifier requestIdentifier = new UniqueRequestIdentifier(header.getOriginatorId(), header.getRequestId(), header.getSubRequestId());
214         boolean requestAccepted = requestRegistry.registerRequest(requestIdentifier);
215         if (!requestAccepted) {
216             if (logger.isDebugEnabled()) {
217                 logger.debug("Duplicate Request with " + requestIdentifier);
218             }
219             throw new DuplicateRequestException("Duplicate Request with " + requestIdentifier);
220         }
221     }
222
223     protected Integer readTTL(CommonHeader header) {
224         if (logger.isTraceEnabled()) {
225             logger.trace("Entering to readTTL with RequestHandlerInput = "+ ObjectUtils.toString(header));
226         }
227         if (header.getFlags()== null || !isValidTTL(String.valueOf(header.getFlags().getTtl()))) {
228             String defaultTTLStr = configuration.getProperty("org.openecomp.appc.workflow.default.ttl", String.valueOf(Constants.DEFAULT_TTL));
229             return Integer.parseInt(defaultTTLStr);
230         }
231         if (logger.isTraceEnabled()) {
232             logger.trace("Exiting from readTTL with (TTL = "+  ObjectUtils.toString(header.getFlags().getTtl())+")");
233         }
234         return header.getFlags().getTtl();
235     }
236
237     private SvcLogicContext getVnfdata(String vnf_id, String prefix, SvcLogicContext ctx) throws VNFNotFoundException {
238         if (logger.isTraceEnabled()) {
239             logger.trace("Entering to getVnfdata with vnfid = "+ ObjectUtils.toString(vnf_id) + ", prefix = "+ ObjectUtils.toString(prefix)+ ", SvcLogicContext"+ ObjectUtils.toString(ctx));
240         }
241
242         String key = "vnf-id = '" + vnf_id + "'";
243         logger.debug("inside getVnfdata=== " + key);
244         try {
245             Instant beginTimestamp = Instant.now();
246             SvcLogicResource.QueryStatus response = aaiService.query("generic-vnf", false, null, key, prefix, null, ctx);
247             Instant endTimestamp = Instant.now();
248             String status = SvcLogicResource.QueryStatus.SUCCESS.equals(response) ? LoggingConstants.StatusCodes.COMPLETE : LoggingConstants.StatusCodes.ERROR;
249             LoggingUtils.logMetricsMessage(
250                     beginTimestamp,
251                     endTimestamp,
252                     LoggingConstants.TargetNames.AAI,
253                     LoggingConstants.TargetServiceNames.AAIServiceNames.QUERY,
254                     status,
255                     "",
256                     response.name(),
257                     this.getClass().getCanonicalName());
258             if (SvcLogicResource.QueryStatus.NOT_FOUND.equals(response)) {
259                 throw new VNFNotFoundException("VNF not found for vnf_id = " + vnf_id);
260             } else if (SvcLogicResource.QueryStatus.FAILURE.equals(response)) {
261                 throw new RuntimeException("Error Querying AAI with vnfID = " + vnf_id);
262             }
263             logger.info("AAIResponse: " + response.toString());
264         } catch (SvcLogicException e) {
265
266             LoggingUtils.logErrorMessage(
267                     LoggingConstants.TargetServiceNames.AAIServiceNames.GET_VNF_DATA,
268                     "Error in getVnfdata" + e,
269                     this.getClass().getCanonicalName());
270
271             throw new RuntimeException(e);
272         }
273         if (logger.isTraceEnabled()) {
274             logger.trace("Exiting from getVnfdata with (SvcLogicContext = "+ ObjectUtils.toString(ctx)+")");
275         }
276         return ctx;
277     }
278
279     protected void validateInput(RequestContext requestContext)
280             throws RequestExpiredException, InvalidInputException, DuplicateRequestException {
281         if (logger.isTraceEnabled()){
282             logger.trace("Entering to validateInput with RequestHandlerInput = "+ ObjectUtils.toString(requestContext));
283         }
284         if (requestContext.getActionIdentifiers().getVnfId() == null || requestContext.getAction() == null
285                 || requestContext.getActionIdentifiers().getVnfId().length() == 0 || requestContext.getAction().name().length() == 0 ||
286                 null == requestContext.getCommonHeader().getApiVer()) {
287             if (logger.isDebugEnabled()) {
288                 logger.debug("vnfID = " + requestContext.getActionIdentifiers().getVnfId() + ", action = " + requestContext.getAction().name());
289             }
290
291             LoggingUtils.logErrorMessage(
292                     LoggingConstants.TargetNames.REQUEST_VALIDATOR,
293                     EELFResourceManager.format(Msg.APPC_INVALID_INPUT),
294                     this.getClass().getCanonicalName());
295
296             throw new InvalidInputException("vnfID or command is null");
297         }
298         CommonHeader commonHeader = requestContext.getCommonHeader();
299
300         checkForDuplicateRequest(commonHeader);
301
302         Calendar inputTimeStamp = DateToCalendar(Date.from(commonHeader.getTimeStamp()));
303         Calendar currentTime = Calendar.getInstance();
304
305         // If input timestamp is of future, we reject the request
306         if (inputTimeStamp.getTime().getTime() > currentTime.getTime().getTime()) {
307             if (logger.isDebugEnabled()) {
308                 logger.debug("Input Timestamp is of future = " + inputTimeStamp.getTime());
309             }
310             throw new InvalidInputException("Input Timestamp is of future = " + inputTimeStamp.getTime());
311         }
312         Integer ttl = readTTL(commonHeader);
313         logger.debug("TTL value set to (seconds) : " + ttl);
314         inputTimeStamp.add(Calendar.SECOND, ttl);
315         if (currentTime.getTime().getTime() >= inputTimeStamp.getTime().getTime()) {
316
317             LoggingUtils.logErrorMessage(
318                     LoggingConstants.TargetNames.REQUEST_VALIDATOR,
319                     "TTL Expired: Current time - " + currentTime.getTime().getTime() + " Request time: " + inputTimeStamp.getTime().getTime() + " with TTL value: " + ttl,
320                     this.getClass().getCanonicalName());
321
322             throw new RequestExpiredException("TTL Expired");
323         }
324         if (logger.isDebugEnabled()) {
325             logger.debug("Validation of the request is successful");
326         }
327     }
328 }