2 * ============LICENSE_START=======================================================
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
21 package org.openecomp.mso.apihandlerinfra;
23 import java.io.StringReader;
24 import java.io.StringWriter;
25 import java.sql.Timestamp;
26 import java.text.SimpleDateFormat;
27 import java.util.Date;
29 import javax.ws.rs.core.Response;
30 import javax.xml.bind.JAXBContext;
31 import javax.xml.bind.JAXBException;
32 import javax.xml.bind.Marshaller;
33 import javax.xml.bind.Unmarshaller;
34 import javax.xml.transform.OutputKeys;
35 import javax.xml.transform.Transformer;
36 import javax.xml.transform.TransformerFactory;
37 import javax.xml.transform.dom.DOMSource;
38 import javax.xml.transform.sax.SAXSource;
39 import javax.xml.transform.stream.StreamResult;
41 import org.hibernate.Query;
42 import org.hibernate.Session;
43 import org.w3c.dom.Document;
44 import org.w3c.dom.Element;
45 import org.w3c.dom.Node;
46 import org.w3c.dom.NodeList;
47 import org.xml.sax.InputSource;
49 import org.openecomp.mso.apihandler.common.ErrorNumbers;
50 import org.openecomp.mso.apihandler.common.ValidationException;
51 import org.openecomp.mso.apihandlerinfra.volumebeans.ActionType;
52 import org.openecomp.mso.apihandlerinfra.volumebeans.VolumeInputs;
53 import org.openecomp.mso.apihandlerinfra.volumebeans.ObjectFactory;
54 import org.openecomp.mso.apihandlerinfra.volumebeans.RequestInfo;
55 import org.openecomp.mso.apihandlerinfra.volumebeans.RequestStatusType;
56 import org.openecomp.mso.apihandlerinfra.volumebeans.VolumeRequest;
57 import org.openecomp.mso.db.AbstractSessionFactoryManager;
58 import org.openecomp.mso.logger.MsoLogger;
59 import org.openecomp.mso.logger.MessageEnum;
60 import org.openecomp.mso.properties.MsoJavaProperties;
61 import org.openecomp.mso.requestsdb.RequestsDbSessionFactoryManager;
62 import org.openecomp.mso.requestsdb.InfraActiveRequests;
63 import org.openecomp.mso.requestsdb.RequestsDatabase;
65 public class VolumeMsoInfraRequest {
67 private String requestId;
68 private String requestXML;
69 private String requestUri;
70 private RequestInfo rinfo;
71 private VolumeInputs volumeInputs;
72 private String volumeParams;
73 private ActionType action;
74 private String errorMessage;
75 private String httpResponse;
76 private String responseBody;
77 private RequestStatusType status;
78 private long startTime;
79 private long progress = Constants.PROGRESS_REQUEST_RECEIVED;
81 protected AbstractSessionFactoryManager requestsDbSessionFactoryManager = new RequestsDbSessionFactoryManager ();
83 private static MsoLogger msoLogger = MsoLogger.getMsoLogger (MsoLogger.Catalog.APIH);
84 private static final String NOT_PROVIDED = "not provided";
86 VolumeMsoInfraRequest (String requestId) {
87 this.requestId = requestId;
88 this.startTime = System.currentTimeMillis();
89 MsoLogger.setLogContext (requestId, null);
94 void parse (String reqXML, String version, MsoJavaProperties props) throws ValidationException {
96 msoLogger.debug ("Validating the request");
98 this.requestXML = reqXML;
100 VolumeRequest volumeReq = null;
101 boolean isWrongRootElement = false;
104 JAXBContext jaxbContext = JAXBContext.newInstance (VolumeRequest.class);
105 Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller ();
107 InputSource inputSource = new InputSource (new StringReader (reqXML));
108 SAXSource source = new SAXSource (inputSource);
110 if (reqXML.contains ("volume-request") && !reqXML.contains("vnf-request")) {
111 volumeReq = jaxbUnmarshaller.unmarshal (source, VolumeRequest.class).getValue ();
113 isWrongRootElement = true;
116 } catch (Exception e) {
117 msoLogger.error (MessageEnum.APIH_VNFREQUEST_VALIDATION_ERROR, "", "", MsoLogger.ErrorCode.DataError, "Exception when parsing reqXML", e);
118 throw new ValidationException ("format for volume request");
121 if (isWrongRootElement) {
122 msoLogger.error (MessageEnum.APIH_REQUEST_VALIDATION_ERROR_REASON, "root element is not correct", "", "", MsoLogger.ErrorCode.SchemaError, "root element <volume-request> expected");
123 throw new ValidationException ("root element <volume-request> expected");
126 if (volumeReq == null) {
127 throw new ValidationException ("volume-request");
130 this.rinfo = volumeReq.getRequestInfo ();
132 if (this.rinfo == null) {
133 throw new ValidationException ("request-info");
136 action = this.rinfo.getAction ();
137 if (action == null) {
138 throw new ValidationException ("action");
140 this.volumeInputs = volumeReq.getVolumeInputs ();
141 if (this.volumeInputs == null) {
142 throw new ValidationException ("volume-inputs");
145 // Verify that the elements correspond to the version
148 case Constants.SCHEMA_VERSION_V1:
149 if (this.volumeInputs.getBackoutOnFailure() != null || this.volumeInputs.getAicCloudRegion() != null ||
150 this.volumeInputs.getVfModuleModelName() != null
151 || this.volumeInputs.getAsdcServiceModelVersion() != null ||
152 this.volumeInputs.getServiceInstanceId() != null || this.volumeInputs.getVnfId() != null) {
153 throw new ValidationException("format for v1 version of volume request");
156 case Constants.SCHEMA_VERSION_V2:
157 if (this.volumeInputs.getServiceType() != null || this.volumeInputs.getAicNodeClli() != null ||
158 this.volumeInputs.getServiceInstanceId() != null || this.volumeInputs.getVnfId() != null) {
159 throw new ValidationException("format for v2 version of volume request");
162 case Constants.SCHEMA_VERSION_V3:
163 if (this.volumeInputs.getServiceType() != null || this.volumeInputs.getAicNodeClli() != null) {
164 throw new ValidationException("format for v3 version of volume request");
170 if (!InfraUtils.isActionAllowed (props, "volume", version, action.value ())) {
171 throw new ValidationException ("action allowable for version " + version + " of volume request");
177 case UPDATE_VF_MODULE_VOL:
178 case DELETE_VF_MODULE_VOL:
179 if (this.volumeInputs.getVolumeGroupId () == null) {
180 throw new ValidationException ("volume-group-id");
187 if (ActionType.CREATE.equals (action) || ActionType.CREATE_VF_MODULE_VOL.equals(action)) {
188 if (this.volumeInputs.getVolumeGroupName () == null) {
189 throw new ValidationException ("volume-group-name");
191 if (!InfraUtils.isValidHeatName(this.volumeInputs.getVolumeGroupName ())) {
192 throw new ValidationException ("volume-group-name: no value meeting heat stack name syntax requirements");
197 if (this.volumeInputs.getVnfType () == null) {
198 throw new ValidationException ("vnf-type");
203 case CREATE_VF_MODULE_VOL:
204 case UPDATE_VF_MODULE_VOL:
205 case DELETE_VF_MODULE_VOL:
206 if (this.volumeInputs.getVfModuleModelName () == null) {
207 throw new ValidationException ("vf-module-model-name");
214 if (!version.equals(Constants.SCHEMA_VERSION_V1) && this.volumeInputs.getServiceId () == null) {
215 throw new ValidationException ("service-id ");
218 if (version.equals(Constants.SCHEMA_VERSION_V1) && this.volumeInputs.getServiceType () != null && this.volumeInputs.getServiceId () != null) {
219 throw new ValidationException ("service-type or service-id ");
222 if (version.equals(Constants.SCHEMA_VERSION_V1) && this.volumeInputs.getAicNodeClli () == null) {
223 throw new ValidationException ("aic-node-clli");
226 if ((version.equals(Constants.SCHEMA_VERSION_V2) || version.equals(Constants.SCHEMA_VERSION_V3)) && (this.volumeInputs.getAicCloudRegion () == null || this.volumeInputs.getAicCloudRegion ().isEmpty())) {
227 throw new ValidationException ("aic-cloud-region");
230 if (version.equals(Constants.SCHEMA_VERSION_V3) && this.volumeInputs.getServiceInstanceId () == null) {
231 throw new ValidationException ("service-instance-id");
234 if (version.equals(Constants.SCHEMA_VERSION_V3) && this.volumeInputs.getVnfId () == null && ActionType.CREATE_VF_MODULE_VOL.equals(action)) {
235 throw new ValidationException ("vnf-id");
238 if (ActionType.CREATE.equals (action) || ActionType.CREATE_VF_MODULE_VOL.equals(action)) {
239 if (this.volumeInputs.getTenantId () == null) {
240 throw new ValidationException ("tenant-id");
245 Object vpN = volumeReq.getVolumeParams ();
248 Node node = (Node) vpN;
249 Document doc = node.getOwnerDocument ();
250 this.volumeParams = domToStr (doc);
253 msoLogger.debug ("VolumeParams: " + this.volumeParams);
256 msoLogger.debug ("Request valid");
258 // Rebuild the request string for BPEL to include request-id
259 rinfo.setRequestId (this.requestId);
260 volumeReq.setRequestInfo (rinfo);
262 StringWriter stringWriter = new StringWriter ();
264 JAXBContext jaxbContext = JAXBContext.newInstance (VolumeRequest.class);
265 Marshaller jaxbMarshaller = jaxbContext.createMarshaller ();
267 // output pretty printed
268 jaxbMarshaller.setProperty (Marshaller.JAXB_FORMATTED_OUTPUT, true);
270 jaxbMarshaller.marshal (volumeReq, stringWriter);
272 } catch (JAXBException e) {
273 msoLogger.debug ("Exception: ", e);
276 this.requestXML = stringWriter.toString ().replace("http://org.openecomp/mso/infra/volume-request",
277 "http://org.openecomp/mso/infra/vnf-request");
279 msoLogger.debug("REQUEST XML to BPEL: " + this.requestXML);
283 public void createRequestRecord (Status status) {
285 Session session = null;
288 session = requestsDbSessionFactoryManager.getSessionFactory ().openSession ();
289 session.beginTransaction ();
291 InfraActiveRequests aq = new InfraActiveRequests ();
292 aq.setRequestId (requestId);
294 Timestamp startTimeStamp = new Timestamp (System.currentTimeMillis());
296 if (rinfo.getAction () != null) {
297 aq.setAction (rinfo.getAction ().value ());
298 aq.setRequestAction (RequestActionMap.getMappedRequestAction (rinfo.getAction ().value ()));
300 aq.setSource (rinfo.getSource ());
302 // Set up mandatory parameters
303 aq.setAction (NOT_PROVIDED);
304 aq.setRequestAction (NOT_PROVIDED);
307 aq.setRequestBody (this.requestXML);
308 aq.setRequestScope (ModelType.volumeGroup.name ());
310 if (volumeInputs != null) {
311 if (volumeInputs.getVolumeGroupId () != null) {
312 aq.setVolumeGroupId (volumeInputs.getVolumeGroupId ());
314 if (volumeInputs.getVolumeGroupName () != null) {
315 aq.setVolumeGroupName (volumeInputs.getVolumeGroupName ());
317 if (volumeInputs.getVnfType () != null) {
318 aq.setVnfType (volumeInputs.getVnfType ());
320 if (volumeInputs.getVnfId () != null) {
321 aq.setVnfId (volumeInputs.getVnfId ());
323 if (volumeInputs.getServiceInstanceId () != null) {
324 aq.setServiceInstanceId (volumeInputs.getServiceInstanceId ());
326 if (volumeInputs.getServiceType () != null) {
327 aq.setServiceType (volumeInputs.getServiceType ());
329 if (volumeInputs.getServiceId () != null) {
330 aq.setAaiServiceId (volumeInputs.getServiceId ());
332 if (volumeInputs.getAicNodeClli () != null) {
333 aq.setAicNodeClli (volumeInputs.getAicNodeClli ());
335 if (volumeInputs.getAicCloudRegion () != null) {
336 aq.setAicCloudRegion (volumeInputs.getAicCloudRegion ());
338 if (volumeInputs.getTenantId () != null) {
339 aq.setTenantId (volumeInputs.getTenantId ());
343 aq.setStartTime (startTimeStamp);
344 aq.setRequestStatus (status.toString ());
345 aq.setLastModifiedBy (Constants.MODIFIED_BY_APIHANDLER);
346 aq.setRequestType ("VOLUME");
348 if (volumeParams != null) {
349 msoLogger.debug ("Storing volumeParams: " + volumeParams);
350 aq.setVnfParams (this.volumeParams);
353 if ((status == Status.FAILED) || (status == Status.COMPLETE)) {
354 aq.setStatusMessage (this.errorMessage);
355 aq.setResponseBody (this.responseBody);
357 Timestamp endTimeStamp = new Timestamp (System.currentTimeMillis());
358 aq.setEndTime (endTimeStamp);
360 aq.setProgress (this.progress);
363 msoLogger.debug ("About to insert a record");
366 session.getTransaction ().commit ();
368 } catch (Exception e) {
369 msoLogger.error (MessageEnum.APIH_DB_INSERT_EXC, "", "", MsoLogger.ErrorCode.DataError, "Exception in createRequestRecord", e);
370 if (session != null) {
373 if (!status.equals (Status.FAILED)) {
379 public void updateFinalStatus (Status status) {
382 result = (RequestsDatabase.getInstance()).updateInfraFinalStatus(requestId, status.toString (),
383 this.errorMessage, this.progress, this.responseBody, Constants.MODIFIED_BY_APIHANDLER);
384 } catch (Exception e) {
385 msoLogger.error(MessageEnum.APIH_DB_UPDATE_EXC, e.getMessage(), "", "", MsoLogger.ErrorCode.DataError, "Exception in updateFinalStatus");
386 msoLogger.debug("Exception: ", e);
390 public Response buildResponse (int httpResponseCode, String errorCode, InfraActiveRequests inProgress) {
391 return buildResponseWithError (httpResponseCode, errorCode, inProgress, null);
394 public Response buildResponseWithError (int httpResponseCode,
396 InfraActiveRequests inProgress,
397 String errorString) {
399 ObjectFactory beansObjectFactory = new ObjectFactory ();
401 VolumeRequest vr = beansObjectFactory.createVolumeRequest ();
403 RequestInfo ri = beansObjectFactory.createRequestInfo ();
405 ri.setRequestId (requestId);
406 ri.setRequestStatus (this.status);
407 ri.setAction (this.rinfo.getAction ());
408 ri.setSource (this.rinfo.getSource ());
410 String errorMsg = null;
411 if (errorCode != null) {
412 // If error code is actually an XML error response from BPEL, treat it specially:
413 if (!Messages.errors.containsKey (errorCode)) {
414 if (errorCode.length () > 300) {
415 errorMsg = errorCode.substring (0, 299);
417 errorMsg = errorCode;
422 if (inProgress == null) {
423 if (errorCode.equals(ErrorNumbers.RECIPE_DOES_NOT_EXIST)) {
424 errorMsg = String.format (Messages.errors.get (errorCode), "volume", errorString);
427 errorMsg = String.format (Messages.errors.get (errorCode), errorString);
429 } else if (errorCode.equals (ErrorNumbers.LOCKED_CREATE_ON_THE_SAME_VNF_NAME_IN_PROGRESS)) {
430 errorMsg = String.format (Messages.errors.get (errorCode),
432 inProgress.getVnfName (),
433 inProgress.getRequestStatus (),
435 } else if (errorCode.equals (ErrorNumbers.LOCKED_SAME_ACTION_AND_VNF_ID)) {
436 errorMsg = String.format (Messages.errors.get (errorCode),
438 inProgress.getVnfId (),
439 inProgress.getRequestStatus (),
440 inProgress.getAction (),
445 ri.setStatusMessage (errorMsg);
446 this.errorMessage = errorMsg;
448 ri.setProgress ((int) this.progress);
450 Date startDate = new Date (this.startTime);
451 SimpleDateFormat sdf = new SimpleDateFormat ("yyyy-MM-dd HH:mm:ss.SSS");
452 String startTimeString = sdf.format (startDate);
454 ri.setStartTime (startTimeString);
456 vr.setRequestInfo (ri);
457 vr.setVolumeInputs (this.volumeInputs);
459 StringWriter stringWriter = new StringWriter ();
461 JAXBContext jaxbContext = JAXBContext.newInstance (VolumeRequest.class);
462 Marshaller jaxbMarshaller = jaxbContext.createMarshaller ();
463 jaxbMarshaller.setProperty (Marshaller.JAXB_FORMATTED_OUTPUT, true);
465 jaxbMarshaller.marshal (vr, stringWriter);
467 } catch (JAXBException e) {
468 msoLogger.debug ("Exception: ", e);
471 String response = stringWriter.toString ();
473 this.httpResponse = Integer.toString (httpResponseCode);
474 this.responseBody = response;
476 // Log the failed request into the MSO Requests database
478 return Response.status (httpResponseCode).entity (response).build ();
482 public Response buildResponseFailedValidation (int httpResponseCode, String exceptionMessage) {
484 ObjectFactory beansObjectFactory = new ObjectFactory ();
485 VolumeRequest vr = beansObjectFactory.createVolumeRequest ();
487 RequestInfo ri = beansObjectFactory.createRequestInfo ();
488 ri.setRequestId (requestId);
490 if (this.rinfo != null) {
491 if (this.rinfo.getAction () != null) {
492 ri.setAction (this.rinfo.getAction ());
494 ri.setAction (ActionType.NOT_PROVIDED);
496 if (this.rinfo.getSource () != null) {
497 ri.setSource (this.rinfo.getSource ());
500 ri.setAction (ActionType.NOT_PROVIDED);
503 // Nothing more is expected for this request
505 String errorMsg = String.format (Messages.errors.get (ErrorNumbers.REQUEST_FAILED_SCHEMA_VALIDATION
508 ri.setStatusMessage (errorMsg);
509 this.errorMessage = errorMsg;
511 ri.setProgress ((int) this.progress);
512 ri.setRequestStatus (RequestStatusType.FAILED);
513 Date startDate = new Date (this.startTime);
514 SimpleDateFormat sdf = new SimpleDateFormat ("yyyy-MM-dd HH:mm:ss.SSS");
515 String startTimeString = sdf.format (startDate);
517 ri.setStartTime (startTimeString);
519 vr.setRequestInfo (ri);
520 vr.setVolumeInputs (this.volumeInputs);
522 StringWriter stringWriter = new StringWriter ();
524 JAXBContext jaxbContext = JAXBContext.newInstance (VolumeRequest.class);
525 Marshaller jaxbMarshaller = jaxbContext.createMarshaller ();
527 // output pretty printed
528 jaxbMarshaller.setProperty (Marshaller.JAXB_FORMATTED_OUTPUT, true);
530 jaxbMarshaller.marshal (vr, stringWriter);
532 } catch (JAXBException e) {
533 msoLogger.debug ("Error marshalling", e);
536 String response = stringWriter.toString ();
538 this.httpResponse = Integer.toString (httpResponseCode);
539 this.responseBody = response;
541 return Response.status (httpResponseCode).entity (response).build ();
544 public String getRequestUri () {
548 public void setRequestUri (String requestUri) {
549 this.requestUri = requestUri;
552 public VolumeInputs getVolumeInputs () {
556 public RequestInfo getRequestInfo () {
560 public String getResponseBody () {
564 public void setResponseBody (String responseBody) {
565 this.responseBody = responseBody;
568 public String getHttpResponse () {
572 public void setHttpResponse (String httpResponse) {
573 this.httpResponse = httpResponse;
576 public String getRequestId () {
580 public String getRequestXML () {
584 public void setRequestXML (String requestXML) {
585 this.requestXML = requestXML;
588 public RequestStatusType getStatus () {
592 public void setStatus (RequestStatusType status) {
593 this.status = status;
597 this.progress = Constants.PROGRESS_REQUEST_COMPLETED;
600 this.progress = Constants.PROGRESS_REQUEST_IN_PROGRESS;
605 public String getServiceType () {
606 if (this.volumeInputs.getServiceType () != null)
607 return this.volumeInputs.getServiceType ();
608 if (this.volumeInputs.getServiceId () != null)
609 return this.volumeInputs.getServiceId ();
613 public static String domToStr (Document doc) {
619 StringWriter sw = new StringWriter ();
620 StreamResult sr = new StreamResult (sw);
621 TransformerFactory tf = TransformerFactory.newInstance ();
622 Transformer t = tf.newTransformer ();
623 t.setOutputProperty (OutputKeys.STANDALONE, "yes");
624 NodeList nl = doc.getDocumentElement ().getChildNodes ();
625 DOMSource source = null;
626 for (int x = 0; x < nl.getLength (); x++) {
627 Node e = nl.item (x);
628 if (e instanceof Element) {
629 source = new DOMSource (e);
633 if (source != null) {
634 t.transform (source, sr);
636 String s = sw.toString ();
642 } catch (Exception e) {
643 msoLogger.error (MessageEnum.APIH_DOM2STR_ERROR, "", "", MsoLogger.ErrorCode.AvailabilityError, "Exception in domToStr", e);