fec512ac44bdf0d1134e7c92224649138c47236b
[so.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  * Copyright (C) 2017 - 2019 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.infra.rest.handler;
22
23 import java.net.URL;
24 import java.sql.Timestamp;
25 import java.util.Map;
26 import java.util.Optional;
27 import javax.ws.rs.container.ContainerRequestContext;
28 import org.apache.http.HttpStatus;
29 import org.onap.logging.filter.base.ErrorCode;
30 import org.onap.so.apihandler.common.CamundaClient;
31 import org.onap.so.apihandler.common.ErrorNumbers;
32 import org.onap.so.apihandler.common.RequestClientParameter;
33 import org.onap.so.apihandlerinfra.Action;
34 import org.onap.so.apihandlerinfra.Actions;
35 import org.onap.so.apihandlerinfra.Constants;
36 import org.onap.so.apihandlerinfra.MsoRequest;
37 import org.onap.so.apihandlerinfra.exceptions.ApiException;
38 import org.onap.so.apihandlerinfra.exceptions.RequestDbFailureException;
39 import org.onap.so.apihandlerinfra.exceptions.ValidateException;
40 import org.onap.so.apihandlerinfra.infra.rest.exception.RequestConflictedException;
41 import org.onap.so.apihandlerinfra.infra.rest.exception.WorkflowEngineConnectionException;
42 import org.onap.so.apihandlerinfra.logging.ErrorLoggerInfo;
43 import org.onap.so.constants.Status;
44 import org.onap.so.db.catalog.client.CatalogDbClient;
45 import org.onap.so.db.request.beans.InfraActiveRequests;
46 import org.onap.so.db.request.client.RequestsDbClient;
47 import org.onap.so.logger.LogConstants;
48 import org.onap.so.logger.MessageEnum;
49 import org.onap.so.serviceinstancebeans.ModelType;
50 import org.onap.so.serviceinstancebeans.RequestReferences;
51 import org.onap.so.serviceinstancebeans.ServiceInstancesResponse;
52 import org.onap.so.utils.UUIDChecker;
53 import org.slf4j.Logger;
54 import org.slf4j.LoggerFactory;
55 import org.slf4j.MDC;
56 import org.springframework.beans.factory.annotation.Autowired;
57 import org.springframework.stereotype.Component;
58
59 @Component
60 public abstract class AbstractRestHandler {
61
62     private static final Logger logger = LoggerFactory.getLogger(AbstractRestHandler.class);
63
64     public static final String CONFLICT_FAIL_MESSAGE = "Error: Locked instance - This %s (%s) "
65             + "already has a request being worked with a status of %s (RequestId - %s). The existing request must finish or be cleaned up before proceeding.";
66
67
68     @Autowired
69     protected CatalogDbClient catalogDbClient;
70
71     @Autowired
72     protected RequestsDbClient infraActiveRequestsClient;
73
74     @Autowired
75     private CamundaClient camundaClient;
76
77     public String getRequestUri(ContainerRequestContext context) {
78         String requestUri = context.getUriInfo().getPath();
79         String httpUrl = MDC.get(LogConstants.URI_BASE).concat(requestUri);
80         MDC.put(LogConstants.HTTP_URL, httpUrl);
81         requestUri = requestUri.substring(requestUri.indexOf("/serviceInstantiation/") + 22);
82         return requestUri;
83     }
84
85     public String getRequestId(ContainerRequestContext requestContext) throws ValidateException {
86         String requestId = null;
87         if (requestContext.getProperty("requestId") != null) {
88             requestId = requestContext.getProperty("requestId").toString();
89         }
90         if (UUIDChecker.isValidUUID(requestId)) {
91             return requestId;
92         } else {
93             ErrorLoggerInfo errorLoggerInfo =
94                     new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, ErrorCode.SchemaError)
95                             .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
96             throw new ValidateException.Builder("Request Id " + requestId + " is not a valid UUID",
97                     HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_BAD_PARAMETER).errorInfo(errorLoggerInfo)
98                             .build();
99         }
100     }
101
102     public InfraActiveRequests duplicateCheck(Actions action, Map<String, String> instanceIdMap, long startTime,
103             MsoRequest msoRequest, String instanceName, String requestScope, InfraActiveRequests currentActiveReq)
104             throws ApiException {
105         return duplicateCheck(action, instanceIdMap, startTime, instanceName, requestScope, currentActiveReq);
106     }
107
108     public InfraActiveRequests duplicateCheck(Actions action, Map<String, String> instanceIdMap, long startTime,
109             String instanceName, String requestScope, InfraActiveRequests currentActiveReq) throws ApiException {
110         InfraActiveRequests dup = null;
111         try {
112             if (!(instanceName == null && "service".equals(requestScope) && (action == Action.createInstance
113                     || action == Action.activateInstance || action == Action.assignInstance))) {
114                 dup = infraActiveRequestsClient.checkInstanceNameDuplicate(instanceIdMap, instanceName, requestScope);
115             }
116         } catch (Exception e) {
117             ErrorLoggerInfo errorLoggerInfo =
118                     new ErrorLoggerInfo.Builder(MessageEnum.APIH_DUPLICATE_CHECK_EXC, ErrorCode.DataError)
119                             .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
120             RequestDbFailureException requestDbFailureException =
121                     new RequestDbFailureException.Builder("check for duplicate instance", e.toString(),
122                             HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).cause(e)
123                                     .errorInfo(errorLoggerInfo).build();
124             updateStatus(currentActiveReq, Status.FAILED, requestDbFailureException.getMessage());
125             throw requestDbFailureException;
126         }
127         return dup;
128     }
129
130     public void updateStatus(InfraActiveRequests aq, Status status, String errorMessage)
131             throws RequestDbFailureException {
132         if ((aq != null) && ((status == Status.FAILED) || (status == Status.COMPLETE))) {
133
134             aq.setStatusMessage(errorMessage);
135             aq.setProgress(100L);
136             aq.setRequestStatus(status.toString());
137             Timestamp endTimeStamp = new Timestamp(System.currentTimeMillis());
138             aq.setEndTime(endTimeStamp);
139             try {
140                 infraActiveRequestsClient.updateInfraActiveRequests(aq);
141             } catch (Exception e) {
142                 logger.error("Error updating status", e);
143             }
144
145         }
146     }
147
148
149
150     public void callWorkflowEngine(RequestClientParameter requestClientParameter, String orchestrationUri)
151             throws WorkflowEngineConnectionException {
152         try {
153             camundaClient.post(requestClientParameter, orchestrationUri);
154         } catch (ApiException e) {
155             logger.error("Error Calling Workflow Engine", e);
156             throw new WorkflowEngineConnectionException("Error Calling Workflow Engine", e);
157         }
158     }
159
160     public Optional<URL> buildSelfLinkUrl(String url, String requestId) {
161         Optional<URL> selfLinkUrl = Optional.empty();
162         String version = "";
163         try {
164             URL aUrl = new URL(url);
165             String aPath = aUrl.getPath();
166             int indexOfVersion = Math.max(aPath.indexOf("/V"), aPath.indexOf("/v"));
167             version = aPath.substring(indexOfVersion, indexOfVersion + 4);
168
169             String pathWithSOAction = aPath.substring(0, indexOfVersion);
170             String pathWithoutSOAction = pathWithSOAction.substring(0, pathWithSOAction.lastIndexOf("/"));
171
172             String selfLinkPath =
173                     pathWithoutSOAction.concat(Constants.ORCHESTRATION_REQUESTS_PATH).concat(version).concat(requestId);
174             selfLinkUrl = Optional.of(new URL(aUrl.getProtocol(), aUrl.getHost(), aUrl.getPort(), selfLinkPath));
175         } catch (Exception e) {
176             selfLinkUrl = Optional.empty(); // ignore
177             logger.error("Exception in buildSelfLinkUrl", e);
178         }
179         return selfLinkUrl;
180     }
181
182     /**
183      * @param instanceId
184      * @param requestId
185      * @param requestContext
186      */
187     public ServiceInstancesResponse createResponse(String instanceId, String requestId,
188             ContainerRequestContext requestContext) {
189         ServiceInstancesResponse response = new ServiceInstancesResponse();
190         RequestReferences requestReferences = new RequestReferences();
191         requestReferences.setInstanceId(instanceId);
192         requestReferences.setRequestId(requestId);
193         Optional<URL> optionalUrl = buildSelfLinkUrl(getRequestUri(requestContext), requestId);
194         if (optionalUrl.isPresent()) {
195             requestReferences.setRequestSelfLink(optionalUrl.get());
196         }
197         response.setRequestReferences(requestReferences);
198         return response;
199     }
200
201     public void checkDuplicateRequest(Map<String, String> instanceIdMap, ModelType modelType, String instanceName,
202             String requestId) throws RequestConflictedException {
203         InfraActiveRequests conflictedRequest =
204                 infraActiveRequestsClient.checkInstanceNameDuplicate(instanceIdMap, instanceName, modelType.toString());
205         if (conflictedRequest != null && !conflictedRequest.getRequestId().equals(requestId)) {
206             throw new RequestConflictedException(String.format(CONFLICT_FAIL_MESSAGE, modelType.toString(),
207                     instanceName, conflictedRequest.getRequestStatus(), conflictedRequest.getRequestId()));
208         }
209     }
210
211
212
213 }