a6452a44ac99ec01c10e2960df1c3c1d1abe5b1d
[so.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.so.apihandlerinfra.tenantisolation;
22
23 import java.sql.Timestamp;
24 import java.util.HashMap;
25 import java.util.List;
26 import java.util.Map;
27 import java.util.Map.Entry;
28
29 import javax.ws.rs.core.MultivaluedMap;
30 import javax.ws.rs.core.Response;
31
32 import org.apache.commons.lang3.StringUtils;
33 import org.onap.so.apihandlerinfra.Constants;
34 import org.onap.so.apihandlerinfra.MsoException;
35 import org.onap.so.apihandlerinfra.Status;
36 import org.onap.so.apihandlerinfra.tenantisolationbeans.Action;
37 import org.onap.so.apihandlerinfra.tenantisolationbeans.Manifest;
38 import org.onap.so.apihandlerinfra.tenantisolationbeans.OperationalEnvironment;
39 import org.onap.so.apihandlerinfra.tenantisolationbeans.RelatedInstance;
40 import org.onap.so.apihandlerinfra.tenantisolationbeans.RelatedInstanceList;
41 import org.onap.so.apihandlerinfra.tenantisolationbeans.RequestDetails;
42 import org.onap.so.apihandlerinfra.tenantisolationbeans.RequestInfo;
43 import org.onap.so.apihandlerinfra.tenantisolationbeans.RequestParameters;
44 import org.onap.so.apihandlerinfra.tenantisolationbeans.ResourceType;
45 import org.onap.so.apihandlerinfra.tenantisolationbeans.ServiceModelList;
46 import org.onap.so.apihandlerinfra.vnfbeans.RequestStatusType;
47 import org.onap.so.db.request.beans.InfraActiveRequests;
48 import org.onap.so.db.request.data.repository.InfraActiveRequestsRepository;
49 import org.onap.so.exceptions.ValidationException;
50 import org.onap.so.logger.MessageEnum;
51 import org.onap.so.logger.MsoLogger;
52 import org.onap.so.serviceinstancebeans.PolicyException;
53 import org.onap.so.serviceinstancebeans.RequestError;
54 import org.onap.so.serviceinstancebeans.ServiceException;
55 import org.onap.so.utils.UUIDChecker;
56 import org.springframework.beans.factory.annotation.Autowired;
57 import org.springframework.context.annotation.Scope;
58 import org.springframework.stereotype.Component;
59
60 import com.fasterxml.jackson.annotation.JsonInclude.Include;
61 import com.fasterxml.jackson.core.JsonProcessingException;
62 import com.fasterxml.jackson.databind.ObjectMapper;
63
64 @Component
65 @Scope("prototype")
66 public class TenantIsolationRequest {
67
68     private String requestId;
69     private String requestJSON;
70     private RequestInfo requestInfo;
71
72     private String errorMessage;
73     private String errorCode;
74     private String httpResponse;
75     private String responseBody;
76     private RequestStatusType status;
77     private String operationalEnvironmentId;
78     private long progress = Constants.PROGRESS_REQUEST_RECEIVED;
79     private String requestScope;
80     private CloudOrchestrationRequest cor;
81     
82     @Autowired 
83     private InfraActiveRequestsRepository infraActiveRequestsRepository;
84     
85     private static MsoLogger msoLogger = MsoLogger.getMsoLogger (MsoLogger.Catalog.APIH, TenantIsolationRequest.class);
86
87
88         TenantIsolationRequest (String requestId) {
89         this.requestId = requestId;
90         MsoLogger.setLogContext (requestId, null);
91     }
92
93         TenantIsolationRequest () {
94         MsoLogger.setLogContext (requestId, null);
95     }
96     
97         void parse(CloudOrchestrationRequest request, HashMap<String,String> instanceIdMap, Action action) throws ValidationException {
98                 this.cor = request;
99                 this.requestInfo = request.getRequestDetails().getRequestInfo();
100                 
101                 try{
102                         ObjectMapper mapper = new ObjectMapper();
103                 requestJSON = mapper.writeValueAsString(request.getRequestDetails());
104
105         } catch(JsonProcessingException e){
106                 throw new ValidationException ("Parse ServiceInstanceRequest to JSON string", true);
107         }
108                 
109                 String envId = null;
110                 if(instanceIdMap != null) {
111                         envId = instanceIdMap.get("operationalEnvironmentId");
112                         if(envId != null && !UUIDChecker.isValidUUID (envId)){
113                                 throw new ValidationException ("operationalEnvironmentId", true);
114                         }
115                         cor.setOperationalEnvironmentId(envId);
116                 }
117                 
118                 this.operationalEnvironmentId = envId;
119                  
120                 RequestDetails requestDetails = request.getRequestDetails();
121                 RequestParameters requestParameters = requestDetails.getRequestParameters();
122                 
123                 requestInfoValidation(action, requestInfo);
124                 
125                 requestParamsValidation(action, requestParameters);
126                 
127                 relatedInstanceValidation(action, requestDetails, requestParameters);
128                 
129         }
130
131         private void relatedInstanceValidation(Action action, RequestDetails requestDetails, RequestParameters requestParameters) throws ValidationException {
132                 RelatedInstanceList[] instanceList = requestDetails.getRelatedInstanceList();
133                 
134                 if (requestParameters == null) {
135                         throw new ValidationException("requestParameters", true);
136                 }
137                 if((Action.activate.equals(action) || Action.deactivate.equals(action)) && OperationalEnvironment.ECOMP.equals(requestParameters.getOperationalEnvironmentType())) {
138                         throw new ValidationException("operationalEnvironmentType in requestParameters", true);
139                 }
140                 
141                 if(!Action.deactivate.equals(action) && OperationalEnvironment.VNF.equals(requestParameters.getOperationalEnvironmentType())) {
142                         if(instanceList != null && instanceList.length > 0) {
143                                 for(RelatedInstanceList relatedInstanceList : instanceList){
144                                         RelatedInstance relatedInstance = relatedInstanceList.getRelatedInstance();
145                                         
146                                         if(relatedInstance.getResourceType() == null) {
147                                                 throw new ValidationException("ResourceType in relatedInstance", true);
148                                         }
149                                         
150                                         if(!empty(relatedInstance.getInstanceName()) && !relatedInstance.getInstanceName().matches(Constants.VALID_INSTANCE_NAME_FORMAT)) {
151                                                 throw new ValidationException ("instanceName format", true);
152                                         } 
153                                         
154                                         if (empty (relatedInstance.getInstanceId ())) {
155                                                 throw new ValidationException ("instanceId in relatedInstance", true);
156                                         }
157                                         
158                                         if (!UUIDChecker.isValidUUID (relatedInstance.getInstanceId ())) {
159                                                 throw new ValidationException ("instanceId format in relatedInstance", true);
160                                         }
161                                 }
162                         } else {
163                                 throw new ValidationException ("relatedInstanceList", true);
164                         }
165                 }
166         }
167
168         private void requestParamsValidation(Action action, RequestParameters requestParameters) throws ValidationException {
169                 
170                 if(requestParameters != null) {
171                         if(!Action.deactivate.equals(action) && requestParameters.getOperationalEnvironmentType() == null) {
172                                 throw new ValidationException ("OperationalEnvironmentType", true);
173                         }
174                         
175                         if (Action.create.equals(action) && empty(requestParameters.getTenantContext())) {
176                                 throw new ValidationException ("Tenant Context", true);
177                         }
178                         if (!Action.deactivate.equals(action) && empty(requestParameters.getWorkloadContext())) {
179                                 throw new ValidationException ("Workload Context", true);
180                         }
181                         
182                         Manifest manifest = requestParameters.getManifest();
183                         
184                         if(Action.activate.equals(action)) {
185                                 if(manifest == null) {
186                                         throw new ValidationException ("Manifest on Activate", true);
187                                 } else {
188                                         List<ServiceModelList> serviceModelList = manifest.getServiceModelList();
189                                         
190                                         if(serviceModelList.isEmpty()) {
191                                                 throw new ValidationException (" empty ServiceModelList", true);
192                                         }
193                                         
194                                         for(ServiceModelList list : serviceModelList) {
195                                                 if(empty(list.getServiceModelVersionId())) {
196                                                         throw new ValidationException ("ServiceModelVersionId", true);
197                                                 }
198                                                 
199                                                 if (!UUIDChecker.isValidUUID (list.getServiceModelVersionId())) {
200                                                         throw new ValidationException ("ServiceModelVersionId format", true);
201                                                 }
202                                                 
203                                                 if(list.getRecoveryAction() == null) {
204                                                         throw new ValidationException ("RecoveryAction", true);
205                                                 }
206                                         }
207                                 }
208                         }
209                 } else if(!Action.deactivate.equals(action)) {
210                         throw new ValidationException("request Parameters", true);
211                 }
212         }
213
214         private void requestInfoValidation(Action action, RequestInfo requestInfo) throws ValidationException {
215                  
216                 if(Action.create.equals(action) && empty(requestInfo.getInstanceName())) {
217                         throw new ValidationException ("instanceName", true);
218                 } 
219                 
220                 if(!empty(requestInfo.getInstanceName()) && !requestInfo.getInstanceName().matches(Constants.VALID_INSTANCE_NAME_FORMAT)) {
221                         throw new ValidationException ("instanceName format", true);
222                 } 
223                 
224                 if (empty(requestInfo.getSource())) {
225                 throw new ValidationException ("source", true);
226         }
227                 
228                 if(empty(requestInfo.getRequestorId())) {
229                 throw new ValidationException ("requestorId", true);
230         }
231                 
232                 ResourceType resourceType = requestInfo.getResourceType();
233                 if(resourceType == null) {
234                         throw new ValidationException ("resourceType", true);
235                 }
236                 
237                 this.requestScope = resourceType.name();
238         }
239         
240         void parseOrchestration (CloudOrchestrationRequest cor) throws ValidationException {
241
242         this.cor = cor;
243
244         try{
245                 ObjectMapper mapper = new ObjectMapper();
246                 requestJSON = mapper.writeValueAsString(cor.getRequestDetails());
247
248         } catch(JsonProcessingException e){
249                 throw new ValidationException ("Parse CloudOrchestrationRequest to JSON string", e);
250         }
251
252         if(cor.getRequestDetails() == null){
253             throw new ValidationException("requestDetails", true);
254         }
255         this.requestInfo = cor.getRequestDetails().getRequestInfo();
256
257         if (this.requestInfo == null) {
258             throw new ValidationException ("requestInfo", true);
259         }
260
261         if (empty (requestInfo.getSource ())) {
262                 throw new ValidationException ("source", true);
263         }
264         if (empty (requestInfo.getRequestorId ())) {
265                 throw new ValidationException ("requestorId", true);
266         }
267     }
268         
269     public void createRequestRecord (Status status, Action action){
270
271                 InfraActiveRequests aq = new InfraActiveRequests ();
272                 aq.setRequestId (requestId);
273
274                 aq.setRequestAction(action.name());
275                 aq.setAction(action.name());
276
277                 Timestamp startTimeStamp = new Timestamp (System.currentTimeMillis());
278
279                 aq.setStartTime (startTimeStamp);
280
281                 if (requestInfo != null) {
282
283                         if(requestInfo.getSource() != null){
284                                 aq.setSource(requestInfo.getSource());
285                         }
286                         if(requestInfo.getRequestorId() != null) {
287                                 aq.setRequestorId(requestInfo.getRequestorId());
288                         }
289                         if(requestInfo.getResourceType() != null) {
290                                 aq.setRequestScope(requestInfo.getResourceType().name());
291                         }
292                 }
293              
294                 if(ResourceType.operationalEnvironment.name().equalsIgnoreCase(requestScope) && requestInfo != null) {
295                         aq.setOperationalEnvId(operationalEnvironmentId);
296                         aq.setOperationalEnvName(requestInfo.getInstanceName());
297                 }
298
299                 aq.setRequestBody (this.requestJSON);
300
301                 aq.setRequestStatus (status.toString ());
302                 aq.setLastModifiedBy (Constants.MODIFIED_BY_APIHANDLER);
303
304                 if ((status == Status.FAILED) || (status == Status.COMPLETE)) {
305                         aq.setStatusMessage (this.errorMessage);
306                         aq.setResponseBody (this.responseBody);
307                         aq.setProgress(Long.valueOf(100));
308
309                         Timestamp endTimeStamp = new Timestamp (System.currentTimeMillis());
310                         aq.setEndTime (endTimeStamp);
311                 } else if(status == Status.IN_PROGRESS) {
312                         aq.setProgress(Constants.PROGRESS_REQUEST_IN_PROGRESS);
313                 }
314                 infraActiveRequestsRepository.save(aq);
315     }
316         
317     
318     public Map<String, String> getOrchestrationFilters (MultivaluedMap<String, String> queryParams) throws ValidationException {
319         String queryParam = null;
320         Map<String, String> orchestrationFilterParams = new HashMap<>();
321
322         for (Entry<String,List<String>> entry : queryParams.entrySet()) {
323             queryParam = entry.getKey();
324             try{
325                           for(String value : entry.getValue()) {
326                                   if(StringUtils.isBlank(value)) {
327                                           throw (new Exception(queryParam + " value"));
328                                   }
329                                   orchestrationFilterParams.put(queryParam, value);
330                           }
331             }catch(Exception e){
332                 throw new ValidationException (e.getMessage(), true);
333                 }
334         }
335
336         return orchestrationFilterParams;
337   }
338
339     /**
340      * Build Error Response for Exception handling.
341      *
342      * @param int
343      * @param httpResponseCode the HTTP response code
344      * @param exceptionType.
345      * @param text the error description
346      * @param messageId
347      * @return the web service response
348      *
349      */
350     public Response buildServiceErrorResponse (int httpResponseCode,
351                                                                                     MsoException exceptionType,
352                                                                                     String text,
353                                                                                     String messageId,
354                                                                                     List<String> variables) {
355
356         this.errorCode = messageId;
357
358         this.errorCode = text != null ? text : "";
359         this.httpResponse = Integer.toString(httpResponseCode);
360         
361         if(errorMessage.length() > 1999){
362             errorMessage = errorMessage.substring(0, 1999);
363         }
364
365         RequestError re = new RequestError();
366
367         if(exceptionType.name().equals("PolicyException")){
368
369                 PolicyException pe = new PolicyException();
370                 pe.setMessageId(messageId);
371                 pe.setText(text);
372                 if(variables != null){
373                         for(String variable: variables){
374                                 pe.getVariables().add(variable);
375                         }
376                 }
377                 re.setPolicyException(pe);
378
379         } else {
380
381                 ServiceException se = new ServiceException();
382                 se.setMessageId(messageId);
383                 se.setText(text);
384                 if(variables != null){
385                         for(String variable: variables){
386                                 se.getVariables().add(variable);
387                         }
388                 }
389                 re.setServiceException(se);
390         }
391
392         String requestErrorStr = null;
393
394         try{
395                 ObjectMapper mapper = new ObjectMapper();
396                 mapper.setSerializationInclusion(Include.NON_DEFAULT);
397                 requestErrorStr = mapper.writeValueAsString(re);
398         }catch(Exception e){
399                 msoLogger.error (MessageEnum.APIH_VALIDATION_ERROR, "", "", MsoLogger.ErrorCode.DataError, "Exception in buildServiceErrorResponse writing exceptionType to string ", e);
400         }
401
402         return Response.status (httpResponseCode).entity(requestErrorStr).build ();
403
404     }
405     
406         private static boolean empty(String s) {
407                 return (s == null || s.trim().isEmpty());
408         }
409         
410     public String getRequestId () {
411         return requestId;
412     }
413     
414     public void setRequestId(String requestId) {
415         this.requestId = requestId;
416     }
417
418         public void updateFinalStatus() {
419                 try {
420                         InfraActiveRequests request = new InfraActiveRequests(requestId);
421                         request.setRequestStatus(status.toString());
422                         request.setStatusMessage(this.errorMessage);
423                         request.setProgress(this.progress);
424                         request.setResponseBody(this.responseBody);
425                         request.setLastModifiedBy(Constants.MODIFIED_BY_APIHANDLER);
426                         infraActiveRequestsRepository.save(request);
427                 } catch (Exception e) {
428                         msoLogger.error(MessageEnum.APIH_DB_UPDATE_EXC, e.getMessage(), "", "", MsoLogger.ErrorCode.DataError, "Exception when updating record in DB");
429                         msoLogger.debug ("Exception: ", e);
430                 }
431         }
432         
433         public void setStatus (RequestStatusType status) {
434         this.status = status;
435         switch (status) {
436         case FAILED:
437         case COMPLETE:
438                 this.progress = Constants.PROGRESS_REQUEST_COMPLETED;
439                 break;
440         case IN_PROGRESS:
441                 this.progress = Constants.PROGRESS_REQUEST_IN_PROGRESS;
442                 break;
443                 case PENDING:
444                         break;
445                 case TIMEOUT:
446                         break;
447                 case UNLOCKED:
448                         break;
449                 default:
450                         break;
451         }
452     }
453
454         public String getOperationalEnvironmentId() {
455                 return operationalEnvironmentId;
456         }
457
458         public void setOperationalEnvironmentId(String operationalEnvironmentId) {
459                 this.operationalEnvironmentId = operationalEnvironmentId;
460         }
461 }