51962f2b9e86a60090ac9218eb8a3bb9eb5e013c
[so.git] / mso-api-handlers / mso-api-handler-infra / src / main / java / org / onap / so / apihandlerinfra / InstanceManagement.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * Copyright (C) 2017 Huawei Technologies Co., Ltd. All rights reserved.
7  * ================================================================================
8  * Modifications Copyright (c) 2019 Samsung
9  * ================================================================================
10  * Licensed under the Apache License, Version 2.0 (the "License");
11  * you may not use this file except in compliance with the License.
12  * You may obtain a copy of the License at
13  * 
14  *      http://www.apache.org/licenses/LICENSE-2.0
15  * 
16  * Unless required by applicable law or agreed to in writing, software
17  * distributed under the License is distributed on an "AS IS" BASIS,
18  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19  * See the License for the specific language governing permissions and
20  * limitations under the License.
21  * ============LICENSE_END=========================================================
22  */
23
24 package org.onap.so.apihandlerinfra;
25
26 import io.swagger.annotations.Api;
27 import io.swagger.annotations.ApiOperation;
28 import org.apache.http.HttpStatus;
29 import org.onap.so.apihandler.common.ErrorNumbers;
30 import org.onap.so.apihandler.common.RequestClientParameter;
31 import org.onap.so.apihandlerinfra.exceptions.ApiException;
32 import org.onap.so.apihandlerinfra.exceptions.RecipeNotFoundException;
33 import org.onap.so.apihandlerinfra.exceptions.RequestDbFailureException;
34 import org.onap.so.apihandlerinfra.exceptions.ValidateException;
35 import org.onap.so.apihandlerinfra.logging.ErrorLoggerInfo;
36 import org.onap.so.db.catalog.beans.Workflow;
37 import org.onap.so.db.catalog.client.CatalogDbClient;
38 import org.onap.so.db.request.beans.InfraActiveRequests;
39 import org.onap.so.db.request.client.RequestsDbClient;
40 import org.onap.so.exceptions.ValidationException;
41 import org.onap.so.logger.ErrorCode;
42 import org.onap.so.logger.MessageEnum;
43 import org.onap.so.serviceinstancebeans.ModelType;
44 import org.onap.so.serviceinstancebeans.RequestReferences;
45 import org.onap.so.serviceinstancebeans.ServiceInstancesRequest;
46 import org.onap.so.serviceinstancebeans.ServiceInstancesResponse;
47 import org.slf4j.Logger;
48 import org.slf4j.LoggerFactory;
49 import org.springframework.beans.factory.annotation.Autowired;
50 import org.springframework.stereotype.Component;
51
52 import javax.transaction.Transactional;
53 import javax.ws.rs.Consumes;
54 import javax.ws.rs.POST;
55 import javax.ws.rs.Path;
56 import javax.ws.rs.PathParam;
57 import javax.ws.rs.Produces;
58 import javax.ws.rs.container.ContainerRequestContext;
59 import javax.ws.rs.core.Context;
60 import javax.ws.rs.core.MediaType;
61 import javax.ws.rs.core.Response;
62 import java.io.IOException;
63 import java.util.HashMap;
64
65 @Component
66 @Path("/onap/so/infra/instanceManagement")
67 @Api(value="/onap/so/infra/instanceManagement",description="Infrastructure API Requests for Instance Management")
68 public class InstanceManagement {
69
70         private static Logger logger = LoggerFactory.getLogger(InstanceManagement.class);       
71         private static String uriPrefix = "/instanceManagement/";
72         private static final String SAVE_TO_DB = "save instance to db";
73
74         @Autowired
75         private RequestsDbClient infraActiveRequestsClient;
76         
77         @Autowired
78         private CatalogDbClient catalogDbClient;
79         
80         @Autowired
81         private MsoRequest msoRequest;
82         
83         @Autowired
84         private RequestHandlerUtils requestHandlerUtils;
85         
86         @POST
87         @Path("/{version:[vV][1]}/serviceInstances/{serviceInstanceId}/vnfs/{vnfInstanceId}/workflows/{workflowUuid}")
88         @Consumes(MediaType.APPLICATION_JSON)
89         @Produces(MediaType.APPLICATION_JSON)
90         @ApiOperation(value="Execute custom workflow",response=Response.class)
91         @Transactional
92         public Response executeCustomWorkflow(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId,
93                                           @PathParam("vnfInstanceId") String vnfInstanceId, @PathParam("workflowUuid") String workflowUuid, @Context ContainerRequestContext requestContext) throws ApiException {
94                 String requestId = requestHandlerUtils.getRequestId(requestContext);
95                 HashMap<String, String> instanceIdMap = new HashMap<>();
96                 instanceIdMap.put("serviceInstanceId", serviceInstanceId);
97                 instanceIdMap.put("vnfInstanceId", vnfInstanceId);
98                 instanceIdMap.put("workflowUuid", workflowUuid);        
99                 return processCustomWorkflowRequest(request, Action.inPlaceSoftwareUpdate, instanceIdMap, version, requestId, requestContext);
100         }       
101
102         private Response processCustomWorkflowRequest(String requestJSON, Actions action, HashMap<String, String> instanceIdMap, String version, String requestId, ContainerRequestContext requestContext) throws ApiException {
103                 String serviceInstanceId = null;
104                 if (instanceIdMap != null) {
105                         serviceInstanceId = instanceIdMap.get("serviceInstanceId");
106                 }
107                 Boolean aLaCarte = true;
108                 long startTime = System.currentTimeMillis ();
109                 ServiceInstancesRequest sir = null;
110                 String apiVersion = version.substring(1);
111                 
112                 String requestUri = requestHandlerUtils.getRequestUri(requestContext, uriPrefix);
113                 
114                 sir = requestHandlerUtils.convertJsonToServiceInstanceRequest(requestJSON, action, startTime, sir, msoRequest, requestId, requestUri);
115                 String requestScope = requestHandlerUtils.deriveRequestScope(action, sir, requestUri);
116                 InfraActiveRequests currentActiveReq =  msoRequest.createRequestObject (sir,  action, requestId, Status.IN_PROGRESS, requestJSON, requestScope);
117                                 
118                 try {
119                         requestHandlerUtils.validateHeaders(requestContext);
120                 } catch (ValidationException e) {
121                         logger.error("Exception occurred", e);
122             ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_VALIDATION_ERROR, ErrorCode.SchemaError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
123             ValidateException validateException = new ValidateException.Builder(e.getMessage(), HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).cause(e)
124                         .errorInfo(errorLoggerInfo).build();
125             requestHandlerUtils.updateStatus(currentActiveReq, Status.FAILED, validateException.getMessage());
126             throw validateException;
127                 }
128                 
129                 requestHandlerUtils.parseRequest(sir, instanceIdMap, action, version, requestJSON, aLaCarte, requestId, currentActiveReq);
130                 requestHandlerUtils.setInstanceId(currentActiveReq, requestScope, null, instanceIdMap);
131                  
132                 int requestVersion = Integer.parseInt(version.substring(1));
133                 String vnfType = msoRequest.getVnfType(sir,requestScope,action,requestVersion);
134                                 
135                 if(requestScope.equalsIgnoreCase(ModelType.vnf.name()) && vnfType != null){
136                         currentActiveReq.setVnfType(vnfType);
137                 }
138                 
139                 InfraActiveRequests dup = null;
140                 boolean inProgress = false;             
141
142                 dup = requestHandlerUtils.duplicateCheck(action, instanceIdMap, startTime, msoRequest, null, requestScope, currentActiveReq);
143
144                 if(dup != null){
145                         inProgress = requestHandlerUtils.camundaHistoryCheck(dup, currentActiveReq);
146                 }
147                 
148                 if (dup != null && inProgress) {
149             requestHandlerUtils.buildErrorOnDuplicateRecord(currentActiveReq, action, instanceIdMap, startTime, msoRequest, null, requestScope, dup);
150                 }
151                 ServiceInstancesResponse serviceResponse = new ServiceInstancesResponse();
152
153                 RequestReferences referencesResponse = new RequestReferences();
154
155                 referencesResponse.setRequestId(requestId);
156
157                 serviceResponse.setRequestReferences(referencesResponse);
158                 Boolean isBaseVfModule = false;
159                 
160                 String workflowUuid = null;
161                 if (instanceIdMap !=null) {
162                         workflowUuid = instanceIdMap.get("workflowUuid");
163                 }
164
165         RecipeLookupResult recipeLookupResult = getInstanceManagementWorkflowRecipe(currentActiveReq, workflowUuid);
166                        
167         String serviceInstanceType = requestHandlerUtils.getServiceType(requestScope, sir, true);                                               
168         
169                 serviceInstanceId = requestHandlerUtils.setServiceInstanceId(requestScope, sir);
170                 String vnfId = "";
171                 
172                 if(sir.getVnfInstanceId () != null){
173                         vnfId = sir.getVnfInstanceId ();
174                 }
175                 
176         try{
177             infraActiveRequestsClient.save(currentActiveReq);
178         }catch(Exception e){
179             ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ACCESS_EXC, ErrorCode.DataError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
180             throw new RequestDbFailureException.Builder(SAVE_TO_DB, e.toString(), HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).cause(e)
181                     .errorInfo(errorLoggerInfo).build();
182         }               
183                 
184                 RequestClientParameter requestClientParameter = null;
185                 try {
186                         requestClientParameter = new RequestClientParameter.Builder()
187                                                 .setRequestId(requestId)
188                                                 .setBaseVfModule(isBaseVfModule)
189                                                 .setRecipeTimeout(recipeLookupResult.getRecipeTimeout())
190                                                 .setRequestAction(action.toString())
191                                                 .setServiceInstanceId(serviceInstanceId)                                                
192                                                 .setVnfId(vnfId)                                                
193                                                 .setServiceType(serviceInstanceType)
194                                                 .setVnfType(vnfType)                                            
195                                                 .setRequestDetails(requestHandlerUtils.mapJSONtoMSOStyle(requestJSON, sir, aLaCarte, action))
196                                                 .setApiVersion(apiVersion)
197                                                 .setALaCarte(aLaCarte)
198                                                 .setRequestUri(requestUri)
199                                                 .build();
200                 } catch (IOException e) {
201                         ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, ErrorCode.SchemaError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
202                         throw new ValidateException.Builder("Unable to generate RequestClientParamter object" + e.getMessage(), HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_BAD_PARAMETER)
203                           .errorInfo(errorLoggerInfo).build();
204                 }
205                 return requestHandlerUtils.postBPELRequest(currentActiveReq, requestClientParameter, recipeLookupResult.getOrchestrationURI(), requestScope);
206         }
207         
208         private RecipeLookupResult getInstanceManagementWorkflowRecipe(InfraActiveRequests currentActiveReq, String workflowUuid) throws ApiException {
209                 RecipeLookupResult recipeLookupResult = null;
210         
211         try {
212                 recipeLookupResult = getCustomWorkflowUri(workflowUuid);
213                 } catch (IOException e) {
214                         ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.SchemaError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
215                         ValidateException validateException = new ValidateException.Builder(e.getMessage(), HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).cause(e)
216                 .errorInfo(errorLoggerInfo).build();
217                         requestHandlerUtils.updateStatus(currentActiveReq, Status.FAILED, validateException.getMessage());
218                         throw validateException;
219                 }
220         
221         if (recipeLookupResult == null) {
222             ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ACCESS_EXC, ErrorCode.DataError).errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
223             RecipeNotFoundException recipeNotFoundExceptionException = new RecipeNotFoundException.Builder("Recipe could not be retrieved from catalog DB.", HttpStatus.SC_NOT_FOUND, ErrorNumbers.SVC_GENERAL_SERVICE_ERROR)
224                     .errorInfo(errorLoggerInfo).build();
225             requestHandlerUtils.updateStatus(currentActiveReq, Status.FAILED, recipeNotFoundExceptionException.getMessage());
226             throw recipeNotFoundExceptionException;
227                 }
228         
229         return recipeLookupResult;
230         }
231    
232     private RecipeLookupResult getCustomWorkflowUri(String workflowUuid) throws IOException {
233         
234                 String recipeUri = null;
235                 Workflow workflow = catalogDbClient.findWorkflowByArtifactUUID(workflowUuid);
236                 if (workflow == null) {
237                         return null;
238                 }
239                 else {
240                         String workflowName = workflow.getArtifactName();
241                         recipeUri = "/mso/async/services/" + workflowName;
242                 }
243                 return new RecipeLookupResult(recipeUri, 180);          
244         }       
245 }