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