Merge "Fix Build"
[so.git] / mso-api-handlers / mso-api-handler-infra / src / main / java / org / onap / so / apihandlerinfra / tenantisolation / TenantIsolationRequest.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Modifications Copyright (c) 2019 Samsung
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  * ============LICENSE_END=========================================================
21  */
22
23 package org.onap.so.apihandlerinfra.tenantisolation;
24
25 import java.sql.Timestamp;
26 import java.util.HashMap;
27 import java.util.List;
28 import java.util.Map;
29 import java.util.Map.Entry;
30
31 import javax.ws.rs.core.MultivaluedMap;
32
33 import org.apache.commons.lang3.StringUtils;
34 import org.onap.so.apihandlerinfra.Constants;
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.client.RequestsDbClient;
49 import org.onap.so.exceptions.ValidationException;
50 import org.onap.so.logger.MessageEnum;
51 import org.onap.so.logger.MsoLogger;
52
53 import org.onap.so.utils.UUIDChecker;
54 import org.slf4j.Logger;
55 import org.slf4j.LoggerFactory;
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.core.JsonProcessingException;
61 import com.fasterxml.jackson.databind.ObjectMapper;
62
63 @Component
64 @Scope("prototype")
65 public class TenantIsolationRequest {
66
67     private String requestId;
68     private String requestJSON;
69     private RequestInfo requestInfo;
70
71     private String errorMessage;
72     private String responseBody;
73     private RequestStatusType status;
74     private String operationalEnvironmentId;
75     private long progress = Constants.PROGRESS_REQUEST_RECEIVED;
76     private String requestScope;
77     private CloudOrchestrationRequest cor;
78     
79     @Autowired
80         private RequestsDbClient requestsDbClient;
81     
82     private static Logger logger = LoggerFactory.getLogger(TenantIsolationRequest.class);
83
84
85         TenantIsolationRequest (String requestId) {
86         this.requestId = requestId;
87         MsoLogger.setLogContext (requestId, null);
88     }
89
90         TenantIsolationRequest () {
91         MsoLogger.setLogContext (requestId, null);
92     }
93     
94         void parse(CloudOrchestrationRequest request, HashMap<String,String> instanceIdMap, Action action) throws ValidationException {
95                 this.cor = request;
96                 this.requestInfo = request.getRequestDetails().getRequestInfo();
97                 
98                 try{
99                         ObjectMapper mapper = new ObjectMapper();
100                 requestJSON = mapper.writeValueAsString(request.getRequestDetails());
101
102         } catch(JsonProcessingException e){
103                 throw new ValidationException ("Parse ServiceInstanceRequest to JSON string", true);
104         }
105                 
106                 String envId = null;
107                 if(instanceIdMap != null) {
108                         envId = instanceIdMap.get("operationalEnvironmentId");
109                         if(envId != null && !UUIDChecker.isValidUUID (envId)){
110                                 throw new ValidationException ("operationalEnvironmentId", true);
111                         }
112                         cor.setOperationalEnvironmentId(envId);
113                 }
114                 
115                 this.operationalEnvironmentId = envId;
116                  
117                 RequestDetails requestDetails = request.getRequestDetails();
118                 RequestParameters requestParameters = requestDetails.getRequestParameters();
119                 
120                 requestInfoValidation(action, requestInfo);
121                 
122                 requestParamsValidation(action, requestParameters);
123                 
124                 relatedInstanceValidation(action, requestDetails, requestParameters);
125                 
126         }
127
128         private void relatedInstanceValidation(Action action, RequestDetails requestDetails, RequestParameters requestParameters) throws ValidationException {
129                 RelatedInstanceList[] instanceList = requestDetails.getRelatedInstanceList();
130                 
131                 if (requestParameters == null) {
132                         throw new ValidationException("requestParameters", true);
133                 }
134                 if((Action.activate.equals(action) || Action.deactivate.equals(action)) && OperationalEnvironment.ECOMP.equals(requestParameters.getOperationalEnvironmentType())) {
135                         throw new ValidationException("operationalEnvironmentType in requestParameters", true);
136                 }
137                 
138                 if(!Action.deactivate.equals(action) && OperationalEnvironment.VNF.equals(requestParameters.getOperationalEnvironmentType())) {
139                         if(instanceList != null && instanceList.length > 0) {
140                                 for(RelatedInstanceList relatedInstanceList : instanceList){
141                                         RelatedInstance relatedInstance = relatedInstanceList.getRelatedInstance();
142                                         
143                                         if(relatedInstance.getResourceType() == null) {
144                                                 throw new ValidationException("ResourceType in relatedInstance", true);
145                                         }
146                                         
147                                         if(!empty(relatedInstance.getInstanceName()) && !relatedInstance.getInstanceName().matches(Constants.VALID_INSTANCE_NAME_FORMAT)) {
148                                                 throw new ValidationException ("instanceName format", true);
149                                         } 
150                                         
151                                         if (empty (relatedInstance.getInstanceId ())) {
152                                                 throw new ValidationException ("instanceId in relatedInstance", true);
153                                         }
154                                         
155                                         if (!UUIDChecker.isValidUUID (relatedInstance.getInstanceId ())) {
156                                                 throw new ValidationException ("instanceId format in relatedInstance", true);
157                                         }
158                                 }
159                         } else {
160                                 throw new ValidationException ("relatedInstanceList", true);
161                         }
162                 }
163         }
164
165         private void requestParamsValidation(Action action, RequestParameters requestParameters) throws ValidationException {
166                 
167                 if(requestParameters != null) {
168                         if(!Action.deactivate.equals(action) && requestParameters.getOperationalEnvironmentType() == null) {
169                                 throw new ValidationException ("OperationalEnvironmentType", true);
170                         }
171                         
172                         if (Action.create.equals(action) && empty(requestParameters.getTenantContext())) {
173                                 throw new ValidationException ("Tenant Context", true);
174                         }
175                         if (!Action.deactivate.equals(action) && empty(requestParameters.getWorkloadContext())) {
176                                 throw new ValidationException ("Workload Context", true);
177                         }
178                         
179                         Manifest manifest = requestParameters.getManifest();
180                         
181                         if(Action.activate.equals(action)) {
182                                 if(manifest == null) {
183                                         throw new ValidationException ("Manifest on Activate", true);
184                                 } else {
185                                         List<ServiceModelList> serviceModelList = manifest.getServiceModelList();
186                                         
187                                         if(serviceModelList.isEmpty()) {
188                                                 throw new ValidationException (" empty ServiceModelList", true);
189                                         }
190                                         
191                                         for(ServiceModelList list : serviceModelList) {
192                                                 if(empty(list.getServiceModelVersionId())) {
193                                                         throw new ValidationException ("ServiceModelVersionId", true);
194                                                 }
195                                                 
196                                                 if (!UUIDChecker.isValidUUID (list.getServiceModelVersionId())) {
197                                                         throw new ValidationException ("ServiceModelVersionId format", true);
198                                                 }
199                                                 
200                                                 if(list.getRecoveryAction() == null) {
201                                                         throw new ValidationException ("RecoveryAction", true);
202                                                 }
203                                         }
204                                 }
205                         }
206                 } else if(!Action.deactivate.equals(action)) {
207                         throw new ValidationException("request Parameters", true);
208                 }
209         }
210
211         private void requestInfoValidation(Action action, RequestInfo requestInfo) throws ValidationException {
212                  
213                 if(Action.create.equals(action) && empty(requestInfo.getInstanceName())) {
214                         throw new ValidationException ("instanceName", true);
215                 } 
216                 
217                 if(!empty(requestInfo.getInstanceName()) && !requestInfo.getInstanceName().matches(Constants.VALID_INSTANCE_NAME_FORMAT)) {
218                         throw new ValidationException ("instanceName format", true);
219                 } 
220                 
221                 if (empty(requestInfo.getSource())) {
222                 throw new ValidationException ("source", true);
223         }
224                 
225                 if(empty(requestInfo.getRequestorId())) {
226                 throw new ValidationException ("requestorId", true);
227         }
228                 
229                 ResourceType resourceType = requestInfo.getResourceType();
230                 if(resourceType == null) {
231                         throw new ValidationException ("resourceType", true);
232                 }
233                 
234                 this.requestScope = resourceType.name();
235         }
236         
237         void parseOrchestration (CloudOrchestrationRequest cor) throws ValidationException {
238
239         this.cor = cor;
240
241         try{
242                 ObjectMapper mapper = new ObjectMapper();
243                 requestJSON = mapper.writeValueAsString(cor.getRequestDetails());
244
245         } catch(JsonProcessingException e){
246                 throw new ValidationException ("Parse CloudOrchestrationRequest to JSON string", e);
247         }
248
249         if(cor.getRequestDetails() == null){
250             throw new ValidationException("requestDetails", true);
251         }
252         this.requestInfo = cor.getRequestDetails().getRequestInfo();
253
254         if (this.requestInfo == null) {
255             throw new ValidationException ("requestInfo", true);
256         }
257
258         if (empty (requestInfo.getSource ())) {
259                 throw new ValidationException ("source", true);
260         }
261         if (empty (requestInfo.getRequestorId ())) {
262                 throw new ValidationException ("requestorId", true);
263         }
264     }
265         
266     public void createRequestRecord (Status status, Action action){
267
268                 InfraActiveRequests aq = new InfraActiveRequests ();
269                 aq.setRequestId (requestId);
270
271                 aq.setRequestAction(action.name());
272                 aq.setAction(action.name());
273
274                 Timestamp startTimeStamp = new Timestamp (System.currentTimeMillis());
275
276                 aq.setStartTime (startTimeStamp);
277
278                 if (requestInfo != null) {
279
280                         if(requestInfo.getSource() != null){
281                                 aq.setSource(requestInfo.getSource());
282                         }
283                         if(requestInfo.getRequestorId() != null) {
284                                 aq.setRequestorId(requestInfo.getRequestorId());
285                         }
286                         if(requestInfo.getResourceType() != null) {
287                                 aq.setRequestScope(requestInfo.getResourceType().name());
288                         }
289                 }
290              
291                 if(ResourceType.operationalEnvironment.name().equalsIgnoreCase(requestScope) && requestInfo != null) {
292                         aq.setOperationalEnvId(operationalEnvironmentId);
293                         aq.setOperationalEnvName(requestInfo.getInstanceName());
294                 }
295
296                 aq.setRequestBody (this.requestJSON);
297
298                 aq.setRequestStatus (status.toString ());
299                 aq.setLastModifiedBy (Constants.MODIFIED_BY_APIHANDLER);
300
301                 if ((status == Status.FAILED) || (status == Status.COMPLETE)) {
302                         aq.setStatusMessage (this.errorMessage);
303                         aq.setResponseBody (this.responseBody);
304                         aq.setProgress(Long.valueOf(100));
305
306                         Timestamp endTimeStamp = new Timestamp (System.currentTimeMillis());
307                         aq.setEndTime (endTimeStamp);
308                 } else if(status == Status.IN_PROGRESS) {
309                         aq.setProgress(Constants.PROGRESS_REQUEST_IN_PROGRESS);
310                 }
311                 requestsDbClient.save(aq);
312     }
313         
314     
315     public Map<String, String> getOrchestrationFilters (MultivaluedMap<String, String> queryParams) throws ValidationException {
316         String queryParam = null;
317         Map<String, String> orchestrationFilterParams = new HashMap<>();
318
319         for (Entry<String,List<String>> entry : queryParams.entrySet()) {
320             queryParam = entry.getKey();
321             try{
322                           for(String value : entry.getValue()) {
323                                   if(StringUtils.isBlank(value)) {
324                                           throw (new Exception(queryParam + " value"));
325                                   }
326                                   orchestrationFilterParams.put(queryParam, value);
327                           }
328             }catch(Exception e){
329                 throw new ValidationException (e.getMessage(), true);
330                 }
331         }
332
333         return orchestrationFilterParams;
334   }
335
336         private static boolean empty(String s) {
337                 return (s == null || s.trim().isEmpty());
338         }
339         
340     public String getRequestId () {
341         return requestId;
342     }
343     
344     public void setRequestId(String requestId) {
345         this.requestId = requestId;
346     }
347
348         public void updateFinalStatus() {
349                 try {
350                         InfraActiveRequests request = new InfraActiveRequests(requestId);
351                         request.setRequestStatus(status.toString());
352                         request.setStatusMessage(this.errorMessage);
353                         request.setProgress(this.progress);
354                         request.setResponseBody(this.responseBody);
355                         request.setLastModifiedBy(Constants.MODIFIED_BY_APIHANDLER);
356                         requestsDbClient.save(request);
357                 } catch (Exception e) {
358                         logger.error("{} {} {} {}", MessageEnum.APIH_DB_UPDATE_EXC.toString(), e.getMessage(),
359                                 MsoLogger.ErrorCode.DataError.getValue(), "Exception when updating record in DB");
360                         logger.debug("Exception: ", e);
361                 }
362         }
363         
364         public void setStatus (RequestStatusType status) {
365         this.status = status;
366         switch (status) {
367         case FAILED:
368         case COMPLETE:
369                 this.progress = Constants.PROGRESS_REQUEST_COMPLETED;
370                 break;
371         case IN_PROGRESS:
372                 this.progress = Constants.PROGRESS_REQUEST_IN_PROGRESS;
373                 break;
374                 case PENDING:
375                         break;
376                 case TIMEOUT:
377                         break;
378                 case UNLOCKED:
379                         break;
380                 default:
381                         break;
382         }
383     }
384
385         public String getOperationalEnvironmentId() {
386                 return operationalEnvironmentId;
387         }
388
389         public void setOperationalEnvironmentId(String operationalEnvironmentId) {
390                 this.operationalEnvironmentId = operationalEnvironmentId;
391         }
392 }