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.logger.MsoLogger;
58 import org.openecomp.mso.logger.MessageEnum;
59 import org.openecomp.mso.properties.MsoJavaProperties;
60 import org.openecomp.mso.requestsdb.HibernateUtil;
61 import org.openecomp.mso.requestsdb.InfraActiveRequests;
62 import org.openecomp.mso.requestsdb.RequestsDatabase;
64 public class VolumeMsoInfraRequest {
66 private String requestId;
67 private String requestXML;
68 private String requestUri;
69 private RequestInfo rinfo;
70 private VolumeInputs volumeInputs;
71 private String volumeParams;
72 private ActionType action;
73 private String errorMessage;
74 private String httpResponse;
75 private String responseBody;
76 private RequestStatusType status;
77 private long startTime;
78 private long progress = Constants.PROGRESS_REQUEST_RECEIVED;
80 private static MsoLogger msoLogger = MsoLogger.getMsoLogger (MsoLogger.Catalog.APIH);
81 private static final String NOT_PROVIDED = "not provided";
83 VolumeMsoInfraRequest (String requestId) {
84 this.requestId = requestId;
85 this.startTime = System.currentTimeMillis();
86 MsoLogger.setLogContext (requestId, null);
91 void parse (String reqXML, String version, MsoJavaProperties props) throws ValidationException {
93 msoLogger.debug ("Validating the request");
95 this.requestXML = reqXML;
97 VolumeRequest volumeReq = null;
98 boolean isWrongRootElement = false;
101 JAXBContext jaxbContext = JAXBContext.newInstance (VolumeRequest.class);
102 Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller ();
104 InputSource inputSource = new InputSource (new StringReader (reqXML));
105 SAXSource source = new SAXSource (inputSource);
107 if (reqXML.contains ("volume-request") && !reqXML.contains("vnf-request")) {
108 volumeReq = jaxbUnmarshaller.unmarshal (source, VolumeRequest.class).getValue ();
110 isWrongRootElement = true;
113 } catch (Exception e) {
114 msoLogger.error (MessageEnum.APIH_VNFREQUEST_VALIDATION_ERROR, "", "", MsoLogger.ErrorCode.DataError, "Exception when parsing reqXML", e);
115 throw new ValidationException ("format for volume request");
118 if (isWrongRootElement) {
119 msoLogger.error (MessageEnum.APIH_REQUEST_VALIDATION_ERROR_REASON, "root element is not correct", "", "", MsoLogger.ErrorCode.SchemaError, "root element <volume-request> expected");
120 throw new ValidationException ("root element <volume-request> expected");
123 if (volumeReq == null) {
124 throw new ValidationException ("volume-request");
127 this.rinfo = volumeReq.getRequestInfo ();
129 if (this.rinfo == null) {
130 throw new ValidationException ("request-info");
133 action = this.rinfo.getAction ();
134 if (action == null) {
135 throw new ValidationException ("action");
137 this.volumeInputs = volumeReq.getVolumeInputs ();
138 if (this.volumeInputs == null) {
139 throw new ValidationException ("volume-inputs");
142 // Verify that the elements correspond to the version
144 if (version.equals(Constants.SCHEMA_VERSION_V1)) {
145 if (this.volumeInputs.getBackoutOnFailure() != null || this.volumeInputs.getAicCloudRegion() != null ||
146 this.volumeInputs.getVfModuleModelName () != null || this.volumeInputs.getAsdcServiceModelVersion () != null ||
147 this.volumeInputs.getServiceInstanceId () != null || this.volumeInputs.getVnfId () != null) {
148 throw new ValidationException ("format for v1 version of volume request");
151 else if (version.equals(Constants.SCHEMA_VERSION_V2)) {
152 if (this.volumeInputs.getServiceType() != null || this.volumeInputs.getAicNodeClli() != null ||
153 this.volumeInputs.getServiceInstanceId () != null || this.volumeInputs.getVnfId () != null) {
154 throw new ValidationException ("format for v2 version of volume request");
157 else if (version.equals(Constants.SCHEMA_VERSION_V3)) {
158 if (this.volumeInputs.getServiceType() != null || this.volumeInputs.getAicNodeClli() != null) {
159 throw new ValidationException ("format for v3 version of volume request");
164 if (!InfraUtils.isActionAllowed (props, "volume", version, action.value ())) {
165 throw new ValidationException ("action allowable for version " + version + " of volume request");
171 case UPDATE_VF_MODULE_VOL:
172 case DELETE_VF_MODULE_VOL:
173 if (this.volumeInputs.getVolumeGroupId () == null) {
174 throw new ValidationException ("volume-group-id");
181 if (ActionType.CREATE.equals (action) || ActionType.CREATE_VF_MODULE_VOL.equals(action)) {
182 if (this.volumeInputs.getVolumeGroupName () == null) {
183 throw new ValidationException ("volume-group-name");
185 if (!InfraUtils.isValidHeatName(this.volumeInputs.getVolumeGroupName ())) {
186 throw new ValidationException ("volume-group-name: no value meeting heat stack name syntax requirements");
191 if (this.volumeInputs.getVnfType () == null) {
192 throw new ValidationException ("vnf-type");
197 case CREATE_VF_MODULE_VOL:
198 case UPDATE_VF_MODULE_VOL:
199 case DELETE_VF_MODULE_VOL:
200 if (this.volumeInputs.getVfModuleModelName () == null) {
201 throw new ValidationException ("vf-module-model-name");
208 if (!version.equals(Constants.SCHEMA_VERSION_V1) && this.volumeInputs.getServiceId () == null) {
209 throw new ValidationException ("service-id ");
212 if (version.equals(Constants.SCHEMA_VERSION_V1) && this.volumeInputs.getServiceType () != null && this.volumeInputs.getServiceId () != null) {
213 throw new ValidationException ("service-type or service-id ");
216 if (version.equals(Constants.SCHEMA_VERSION_V1) && this.volumeInputs.getAicNodeClli () == null) {
217 throw new ValidationException ("aic-node-clli");
220 if ((version.equals(Constants.SCHEMA_VERSION_V2) || version.equals(Constants.SCHEMA_VERSION_V3)) && (this.volumeInputs.getAicCloudRegion () == null || this.volumeInputs.getAicCloudRegion ().isEmpty())) {
221 throw new ValidationException ("aic-cloud-region");
224 if (version.equals(Constants.SCHEMA_VERSION_V3) && this.volumeInputs.getServiceInstanceId () == null) {
225 throw new ValidationException ("service-instance-id");
228 if (version.equals(Constants.SCHEMA_VERSION_V3) && this.volumeInputs.getVnfId () == null && ActionType.CREATE_VF_MODULE_VOL.equals(action)) {
229 throw new ValidationException ("vnf-id");
232 if (ActionType.CREATE.equals (action) || ActionType.CREATE_VF_MODULE_VOL.equals(action)) {
233 if (this.volumeInputs.getTenantId () == null) {
234 throw new ValidationException ("tenant-id");
239 Object vpN = volumeReq.getVolumeParams ();
242 Node node = (Node) vpN;
243 Document doc = node.getOwnerDocument ();
244 this.volumeParams = domToStr (doc);
247 msoLogger.debug ("VolumeParams: " + this.volumeParams);
250 msoLogger.debug ("Request valid");
252 // Rebuild the request string for BPEL to include request-id
253 rinfo.setRequestId (this.requestId);
254 volumeReq.setRequestInfo (rinfo);
256 StringWriter stringWriter = new StringWriter ();
258 JAXBContext jaxbContext = JAXBContext.newInstance (VolumeRequest.class);
259 Marshaller jaxbMarshaller = jaxbContext.createMarshaller ();
261 // output pretty printed
262 jaxbMarshaller.setProperty (Marshaller.JAXB_FORMATTED_OUTPUT, true);
264 jaxbMarshaller.marshal (volumeReq, stringWriter);
266 } catch (JAXBException e) {
267 msoLogger.debug ("Exception: ", e);
270 this.requestXML = stringWriter.toString ().replace("http://ecomp.att.com/mso/infra/volume-request",
271 "http://ecomp.att.com/mso/infra/vnf-request");
273 msoLogger.debug("REQUEST XML to BPEL: " + this.requestXML);
277 public void createRequestRecord (Status status) {
279 Session session = null;
282 session = HibernateUtil.getSessionFactory ().openSession ();
283 session.beginTransaction ();
285 InfraActiveRequests aq = new InfraActiveRequests ();
286 aq.setRequestId (requestId);
288 Timestamp startTimeStamp = new Timestamp (System.currentTimeMillis());
290 if (rinfo.getAction () != null) {
291 aq.setAction (rinfo.getAction ().value ());
292 aq.setRequestAction (RequestActionMap.getMappedRequestAction (rinfo.getAction ().value ()));
294 aq.setSource (rinfo.getSource ());
296 // Set up mandatory parameters
297 aq.setAction (NOT_PROVIDED);
298 aq.setAction (NOT_PROVIDED);
301 aq.setRequestBody (this.requestXML);
302 aq.setRequestScope (ModelType.volumeGroup.name ());
304 if (volumeInputs != null) {
305 if (volumeInputs.getVolumeGroupId () != null) {
306 aq.setVolumeGroupId (volumeInputs.getVolumeGroupId ());
308 if (volumeInputs.getVolumeGroupName () != null) {
309 aq.setVolumeGroupName (volumeInputs.getVolumeGroupName ());
311 if (volumeInputs.getVnfType () != null) {
312 aq.setVnfType (volumeInputs.getVnfType ());
314 if (volumeInputs.getVnfId () != null) {
315 aq.setVnfId (volumeInputs.getVnfId ());
317 if (volumeInputs.getServiceInstanceId () != null) {
318 aq.setServiceInstanceId (volumeInputs.getServiceInstanceId ());
320 if (volumeInputs.getServiceType () != null) {
321 aq.setServiceType (volumeInputs.getServiceType ());
323 if (volumeInputs.getServiceId () != null) {
324 aq.setAaiServiceId (volumeInputs.getServiceId ());
326 if (volumeInputs.getAicNodeClli () != null) {
327 aq.setAicNodeClli (volumeInputs.getAicNodeClli ());
329 if (volumeInputs.getAicCloudRegion () != null) {
330 aq.setAicCloudRegion (volumeInputs.getAicCloudRegion ());
332 if (volumeInputs.getTenantId () != null) {
333 aq.setTenantId (volumeInputs.getTenantId ());
337 aq.setStartTime (startTimeStamp);
338 aq.setRequestStatus (status.toString ());
339 aq.setLastModifiedBy (Constants.MODIFIED_BY_APIHANDLER);
340 aq.setRequestType ("VOLUME");
342 if (volumeParams != null) {
343 msoLogger.debug ("Storing volumeParams: " + volumeParams);
344 aq.setVnfParams (this.volumeParams);
347 if ((status == Status.FAILED) || (status == Status.COMPLETE)) {
348 aq.setStatusMessage (this.errorMessage);
349 aq.setResponseBody (this.responseBody);
351 Timestamp endTimeStamp = new Timestamp (System.currentTimeMillis());
352 aq.setEndTime (endTimeStamp);
354 aq.setProgress (this.progress);
357 msoLogger.debug ("About to insert a record");
360 session.getTransaction ().commit ();
362 } catch (Exception e) {
363 msoLogger.error (MessageEnum.APIH_DB_INSERT_EXC, "", "", MsoLogger.ErrorCode.DataError, "Exception in createRequestRecord", e);
364 if (session != null) {
367 if (!status.equals (Status.FAILED)) {
373 public void updateFinalStatus (Status status) {
376 result = RequestsDatabase.updateInfraFinalStatus(requestId, status.toString (),
377 this.errorMessage, this.progress, this.responseBody, Constants.MODIFIED_BY_APIHANDLER);
378 } catch (Exception e) {
379 msoLogger.error(MessageEnum.APIH_DB_UPDATE_EXC, e.getMessage(), "", "", MsoLogger.ErrorCode.DataError, "Exception in updateFinalStatus");
380 msoLogger.debug("Exception: ", e);
384 public Response buildResponse (int httpResponseCode, String errorCode, InfraActiveRequests inProgress) {
385 return buildResponseWithError (httpResponseCode, errorCode, inProgress, null);
388 public Response buildResponseWithError (int httpResponseCode,
390 InfraActiveRequests inProgress,
391 String errorString) {
393 ObjectFactory beansObjectFactory = new ObjectFactory ();
395 VolumeRequest vr = beansObjectFactory.createVolumeRequest ();
397 RequestInfo ri = beansObjectFactory.createRequestInfo ();
399 ri.setRequestId (requestId);
400 ri.setRequestStatus (this.status);
401 ri.setAction (this.rinfo.getAction ());
402 ri.setSource (this.rinfo.getSource ());
404 String errorMsg = null;
405 if (errorCode != null) {
406 // If error code is actually an XML error response from BPEL, treat it specially:
407 if (!Messages.errors.containsKey (errorCode)) {
408 if (errorCode.length () > 300) {
409 errorMsg = errorCode.substring (0, 299);
411 errorMsg = errorCode;
416 if (inProgress == null) {
417 if (errorCode.equals(ErrorNumbers.RECIPE_DOES_NOT_EXIST)) {
418 errorMsg = String.format (Messages.errors.get (errorCode), "volume", errorString);
421 errorMsg = String.format (Messages.errors.get (errorCode), errorString);
423 } else if (errorCode.equals (ErrorNumbers.LOCKED_CREATE_ON_THE_SAME_VNF_NAME_IN_PROGRESS)) {
424 errorMsg = String.format (Messages.errors.get (errorCode),
426 inProgress.getVnfName (),
427 inProgress.getRequestStatus (),
429 } else if (errorCode.equals (ErrorNumbers.LOCKED_SAME_ACTION_AND_VNF_ID)) {
430 errorMsg = String.format (Messages.errors.get (errorCode),
432 inProgress.getVnfId (),
433 inProgress.getRequestStatus (),
434 inProgress.getAction (),
439 ri.setStatusMessage (errorMsg);
440 this.errorMessage = errorMsg;
442 ri.setProgress ((int) this.progress);
444 Date startDate = new Date (this.startTime);
445 SimpleDateFormat sdf = new SimpleDateFormat ("yyyy-MM-dd HH:mm:ss.SSS");
446 String startTimeString = sdf.format (startDate);
448 ri.setStartTime (startTimeString);
450 vr.setRequestInfo (ri);
451 vr.setVolumeInputs (this.volumeInputs);
453 StringWriter stringWriter = new StringWriter ();
455 JAXBContext jaxbContext = JAXBContext.newInstance (VolumeRequest.class);
456 Marshaller jaxbMarshaller = jaxbContext.createMarshaller ();
457 jaxbMarshaller.setProperty (Marshaller.JAXB_FORMATTED_OUTPUT, true);
459 jaxbMarshaller.marshal (vr, stringWriter);
461 } catch (JAXBException e) {
462 msoLogger.debug ("Exception: ", e);
465 String response = stringWriter.toString ();
467 this.httpResponse = Integer.toString (httpResponseCode);
468 this.responseBody = response;
470 // Log the failed request into the MSO Requests database
472 return Response.status (httpResponseCode).entity (response).build ();
476 public Response buildResponseFailedValidation (int httpResponseCode, String exceptionMessage) {
478 ObjectFactory beansObjectFactory = new ObjectFactory ();
479 VolumeRequest vr = beansObjectFactory.createVolumeRequest ();
481 RequestInfo ri = beansObjectFactory.createRequestInfo ();
482 ri.setRequestId (requestId);
484 if (this.rinfo != null) {
485 if (this.rinfo.getAction () != null) {
486 ri.setAction (this.rinfo.getAction ());
488 ri.setAction (ActionType.NOT_PROVIDED);
490 if (this.rinfo.getSource () != null) {
491 ri.setSource (this.rinfo.getSource ());
494 ri.setAction (ActionType.NOT_PROVIDED);
497 // Nothing more is expected for this request
499 String errorMsg = String.format (Messages.errors.get (ErrorNumbers.REQUEST_FAILED_SCHEMA_VALIDATION
502 ri.setStatusMessage (errorMsg);
503 this.errorMessage = errorMsg;
505 ri.setProgress ((int) this.progress);
506 ri.setRequestStatus (RequestStatusType.FAILED);
507 Date startDate = new Date (this.startTime);
508 SimpleDateFormat sdf = new SimpleDateFormat ("yyyy-MM-dd HH:mm:ss.SSS");
509 String startTimeString = sdf.format (startDate);
511 ri.setStartTime (startTimeString);
513 vr.setRequestInfo (ri);
514 vr.setVolumeInputs (this.volumeInputs);
516 StringWriter stringWriter = new StringWriter ();
518 JAXBContext jaxbContext = JAXBContext.newInstance (VolumeRequest.class);
519 Marshaller jaxbMarshaller = jaxbContext.createMarshaller ();
521 // output pretty printed
522 jaxbMarshaller.setProperty (Marshaller.JAXB_FORMATTED_OUTPUT, true);
524 jaxbMarshaller.marshal (vr, stringWriter);
526 } catch (JAXBException e) {
527 msoLogger.debug ("Error marshalling", e);
530 String response = stringWriter.toString ();
532 this.httpResponse = Integer.toString (httpResponseCode);
533 this.responseBody = response;
535 return Response.status (httpResponseCode).entity (response).build ();
538 public String getRequestUri () {
542 public void setRequestUri (String requestUri) {
543 this.requestUri = requestUri;
546 public VolumeInputs getVolumeInputs () {
550 public RequestInfo getRequestInfo () {
554 public String getResponseBody () {
558 public void setResponseBody (String responseBody) {
559 this.responseBody = responseBody;
562 public String getHttpResponse () {
566 public void setHttpResponse (String httpResponse) {
567 this.httpResponse = httpResponse;
570 public String getRequestId () {
574 public String getRequestXML () {
578 public void setRequestXML (String requestXML) {
579 this.requestXML = requestXML;
582 public RequestStatusType getStatus () {
586 public void setStatus (RequestStatusType status) {
587 this.status = status;
591 this.progress = Constants.PROGRESS_REQUEST_COMPLETED;
594 this.progress = Constants.PROGRESS_REQUEST_IN_PROGRESS;
599 public String getServiceType () {
600 if (this.volumeInputs.getServiceType () != null)
601 return this.volumeInputs.getServiceType ();
602 if (this.volumeInputs.getServiceId () != null)
603 return this.volumeInputs.getServiceId ();
607 public static String domToStr (Document doc) {
613 StringWriter sw = new StringWriter ();
614 StreamResult sr = new StreamResult (sw);
615 TransformerFactory tf = TransformerFactory.newInstance ();
616 Transformer t = tf.newTransformer ();
617 t.setOutputProperty (OutputKeys.STANDALONE, "yes");
618 NodeList nl = doc.getDocumentElement ().getChildNodes ();
619 DOMSource source = null;
620 for (int x = 0; x < nl.getLength (); x++) {
621 Node e = nl.item (x);
622 if (e instanceof Element) {
623 source = new DOMSource (e);
627 if (source != null) {
628 t.transform (source, sr);
630 String s = sw.toString ();
636 } catch (Exception e) {
637 msoLogger.error (MessageEnum.APIH_DOM2STR_ERROR, "", "", MsoLogger.ErrorCode.AvailabilityError, "Exception in domToStr", e);