2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 - 2018 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.onap.so.bpmn.buildingblock;
23 import static org.apache.commons.lang3.StringUtils.*;
25 import java.time.Duration;
26 import java.util.List;
28 import java.util.UUID;
30 import org.apache.commons.lang.SerializationUtils;
31 import org.camunda.bpm.engine.delegate.BpmnError;
32 import org.json.JSONArray;
33 import org.json.JSONObject;
34 import org.onap.so.bpmn.common.BuildingBlockExecution;
35 import org.onap.so.bpmn.core.json.JsonUtils;
36 import org.onap.so.bpmn.servicedecomposition.bbobjects.AllottedResource;
37 import org.onap.so.bpmn.servicedecomposition.bbobjects.CloudRegion;
38 import org.onap.so.bpmn.servicedecomposition.bbobjects.Customer;
39 import org.onap.so.bpmn.servicedecomposition.bbobjects.GenericVnf;
40 import org.onap.so.bpmn.servicedecomposition.bbobjects.Pnf;
41 import org.onap.so.bpmn.servicedecomposition.bbobjects.ServiceInstance;
42 import org.onap.so.bpmn.servicedecomposition.bbobjects.ServiceProxy;
43 import org.onap.so.bpmn.servicedecomposition.bbobjects.VpnBondingLink;
44 import org.onap.so.bpmn.servicedecomposition.entities.GeneralBuildingBlock;
45 import org.onap.so.bpmn.servicedecomposition.generalobjects.License;
46 import org.onap.so.bpmn.servicedecomposition.generalobjects.RequestContext;
47 import org.onap.so.bpmn.servicedecomposition.generalobjects.RequestParameters;
48 import org.onap.so.bpmn.servicedecomposition.homingobjects.Candidate;
49 import org.onap.so.bpmn.servicedecomposition.homingobjects.CandidateType;
50 import org.onap.so.bpmn.servicedecomposition.homingobjects.SolutionCandidates;
51 import org.onap.so.bpmn.servicedecomposition.homingobjects.SolutionInfo;
52 import org.onap.so.bpmn.servicedecomposition.modelinfo.ModelInfoMetadata;
53 import org.onap.so.bpmn.servicedecomposition.modelinfo.ModelInfoServiceInstance;
54 import org.onap.so.client.exception.BadResponseException;
55 import org.onap.so.client.exception.ExceptionBuilder;
57 import org.onap.so.client.sniro.SniroClient;
58 import static org.onap.so.client.sniro.SniroValidator.*;
60 import org.onap.so.client.sniro.beans.SniroManagerRequest;
61 import org.onap.so.db.catalog.beans.OrchestrationStatus;
62 import org.onap.so.logger.MsoLogger;
63 import org.springframework.beans.factory.annotation.Autowired;
64 import org.springframework.core.env.Environment;
65 import org.springframework.stereotype.Component;
66 import org.springframework.web.util.UriUtils;
70 * The sniro homing building block obtains licensing and homing solutions for a given
71 * resource or set of resources.
76 @Component("SniroHoming")
77 public class SniroHomingV2 {
78 private static final MsoLogger log = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, SniroHomingV2.class);
79 private JsonUtils jsonUtils = new JsonUtils();
81 private Environment env;
83 private SniroClient client;
85 private ExceptionBuilder exceptionUtil;
86 private static final String MODEL_NAME = "modelName";
87 private static final String MODEL_INVARIANT_ID = "modelInvariantId";
88 private static final String MODEL_VERSION_ID = "modelVersionId";
89 private static final String MODEL_VERSION = "modelVersion";
90 private static final String SERVICE_RESOURCE_ID = "serviceResourceId";
91 private static final String RESOURCE_MODULE_NAME = "resourceModuleName";
92 private static final String RESOURCE_MODEL_INFO = "resourceModelInfo";
93 private static final String IDENTIFIER_TYPE = "identifierType";
94 private static final String INVENTORY_TYPE = "inventoryType";
95 private static final String SOLUTIONS = "solutions";
96 private static final String RESOURCE_MISSING_DATA = "Resource does not contain: ";
97 private static final String SERVICE_MISSING_DATA = "Service Instance does not contain: ";
98 private static final String UNPROCESSABLE = "422";
99 private static final int INTERNAL = 500;
102 * Generates the request payload then sends to sniro manager to perform homing and
103 * licensing for the provided demands
107 public void callSniro(BuildingBlockExecution execution){
108 log.trace("Started Sniro Homing Call Sniro");
110 GeneralBuildingBlock bb = execution.getGeneralBuildingBlock();
112 RequestContext requestContext = bb.getRequestContext();
113 RequestParameters requestParams = requestContext.getRequestParameters();
114 String requestId = requestContext.getMsoRequestId();
116 ServiceInstance serviceInstance = bb.getCustomer().getServiceSubscription().getServiceInstances().get(0);
117 Customer customer = bb.getCustomer();
119 String timeout = execution.getVariable("timeout");
120 if(isBlank(timeout)){
121 timeout = env.getProperty("sniro.manager.timeout", "PT30M");
124 SniroManagerRequest request = new SniroManagerRequest(); //TODO Add additional pojos for each section
126 JSONObject requestInfo = buildRequestInfo(requestId, timeout);
127 request.setRequestInformation(requestInfo.toString());
129 JSONObject serviceInfo = buildServiceInfo(serviceInstance);
130 request.setServiceInformation(serviceInfo.toString());
132 JSONObject placementInfo = buildPlacementInfo(customer, requestParams);
134 JSONArray placementDemands = buildPlacementDemands(serviceInstance);
135 placementInfo.put("placementDemands", placementDemands);
136 request.setPlacementInformation(placementInfo.toString());
138 JSONArray licenseDemands = buildLicenseDemands(serviceInstance);
139 request.setLicenseInformation(licenseDemands.toString());
141 if(placementDemands.length() > 0 || licenseDemands.length() > 0){
142 client.postDemands(request);
144 log.debug(SERVICE_MISSING_DATA + "resources eligible for homing or licensing");
145 throw new BpmnError(UNPROCESSABLE, SERVICE_MISSING_DATA + "resources eligible for homing or licensing");
148 //Variables for ReceiveWorkflowMessage subflow
149 execution.setVariable("asyncCorrelator", requestId);
150 execution.setVariable("asyncMessageType", "SNIROResponse");
151 execution.setVariable("asyncTimeout", timeout);
153 log.trace("Completed Sniro Homing Call Sniro");
155 exceptionUtil.buildAndThrowWorkflowException(execution, Integer.parseInt(e.getErrorCode()), e.getMessage());
156 }catch(BadResponseException e){
157 exceptionUtil.buildAndThrowWorkflowException(execution, 400, e.getMessage());
159 exceptionUtil.buildAndThrowWorkflowException(execution, INTERNAL, "Internal Error - occurred while preparing sniro request: " + e.getMessage());
164 * Validates, processes, and sets the homing and licensing solutions that are returned by
168 * @param asyncResponse
170 public void processSolution(BuildingBlockExecution execution, String asyncResponse){
171 log.trace("Started Sniro Homing Process Solution");
173 //TODO improve handling multiple solutions but is dependent on sniro enhancing api + work with sniro conductor to improve "inventoryType" representation
174 validateSolution(asyncResponse);
175 ServiceInstance serviceInstance = execution.getGeneralBuildingBlock().getCustomer().getServiceSubscription().getServiceInstances().get(0);
177 log.debug("Processing sniro manager asyncronous response");
178 JSONObject response = new JSONObject(asyncResponse);
179 if(response.has(SOLUTIONS)){
180 JSONObject allSolutions = response.getJSONObject(SOLUTIONS);
181 if(allSolutions.has("placementSolutions")){
182 JSONArray placementSolutions = allSolutions.getJSONArray("placementSolutions");
183 for(int i = 0; i < placementSolutions.length(); i++){
184 JSONArray placements = placementSolutions.getJSONArray(i);
185 processPlacementSolution(serviceInstance, placements, i);
188 if(allSolutions.has("licenseSolutions")){
189 JSONArray licenseSolutions = allSolutions.getJSONArray("licenseSolutions");
190 if(licenseSolutions.length() > 0){
191 processLicenseSolution(serviceInstance, licenseSolutions);
195 throw new BpmnError(UNPROCESSABLE, "Sniro Managers response does not contain: " + SOLUTIONS);
198 execution.setVariable("generalBuildingBlock", execution.getGeneralBuildingBlock());
200 log.trace("Completed Sniro Homing Process Solution");
202 exceptionUtil.buildAndThrowWorkflowException(execution, Integer.parseInt(e.getErrorCode()), e.getMessage());
203 }catch(BadResponseException e){
204 exceptionUtil.buildAndThrowWorkflowException(execution, 400, e.getMessage());
206 exceptionUtil.buildAndThrowWorkflowException(execution, INTERNAL, "Internal Error - occurred while processing sniro asynchronous response: " + e.getMessage());
211 * Builds the request information section for the homing/licensing request
215 private JSONObject buildRequestInfo(String requestId, String timeout) throws Exception{
216 log.trace("Building request information");
217 JSONObject requestInfo = new JSONObject();
218 if(requestId != null){
219 String host = env.getProperty("mso.workflow.message.endpoint");
220 String callbackUrl = host + "/" + UriUtils.encodePathSegment("SNIROResponse", "UTF-8") + "/" + UriUtils.encodePathSegment(requestId, "UTF-8");
222 Duration d = Duration.parse(timeout);
223 long timeoutSeconds = d.getSeconds();
225 requestInfo.put("transactionId", requestId).put("requestId", requestId).put("callbackUrl", callbackUrl).put("sourceId", "mso").put("requestType", "create")
226 .put("timeout", timeoutSeconds);
228 throw new BpmnError(UNPROCESSABLE, "Request Context does not contain: requestId");
234 * Builds the request information section for the homing/licensing request
237 private JSONObject buildServiceInfo(ServiceInstance serviceInstance){
238 log.trace("Building service information");
239 JSONObject info = new JSONObject();
240 ModelInfoServiceInstance modelInfo = serviceInstance.getModelInfoServiceInstance();
241 if(isNotBlank(modelInfo.getModelInvariantUuid()) && isNotBlank(modelInfo.getModelUuid())){
242 info.put("serviceInstanceId", serviceInstance.getServiceInstanceId());
243 if(modelInfo.getServiceType() != null){ //temp solution
244 info.put("serviceName", serviceInstance.getModelInfoServiceInstance().getServiceType());
246 info.put("modelInfo", buildModelInfo(serviceInstance.getModelInfoServiceInstance()));
248 throw new BpmnError(UNPROCESSABLE, SERVICE_MISSING_DATA + MODEL_VERSION_ID + ", " + MODEL_INVARIANT_ID);
254 * Builds initial section of placement info for the homing/licensing request
257 private JSONObject buildPlacementInfo(Customer customer, RequestParameters requestParams){
258 JSONObject placementInfo = new JSONObject();
259 if(customer != null){
260 log.debug("Adding subscriber to placement information");
261 placementInfo.put("subscriberInfo", new JSONObject().put("globalSubscriberId", customer.getGlobalCustomerId()).put("subscriberName", customer.getSubscriberName()).put("subscriberCommonSiteId", customer.getSubscriberCommonSiteId()));
262 if(requestParams != null){
263 log.debug("Adding request parameters to placement information");
264 placementInfo.put("requestParameters", new JSONObject(requestParams.toJsonString()));
267 throw new BpmnError(UNPROCESSABLE, SERVICE_MISSING_DATA + "customer");
269 return placementInfo;
274 * Builds the placement demand list for the homing/licensing request
277 private JSONArray buildPlacementDemands(ServiceInstance serviceInstance){
278 log.trace("Building placement information demands");
279 JSONArray placementDemands = new JSONArray();
281 List<AllottedResource> allottedResourceList = serviceInstance.getAllottedResources();
282 if(!allottedResourceList.isEmpty()){
283 log.debug("Adding allotted resources to placement demands list");
284 for(AllottedResource ar : allottedResourceList){
285 if(isBlank(ar.getId())){
286 ar.setId(UUID.randomUUID().toString());
288 JSONObject demand = buildDemand(ar.getId(), ar.getModelInfoAllottedResource());
289 addCandidates(ar, demand);
290 placementDemands.put(demand);
293 List<VpnBondingLink> vpnBondingLinkList = serviceInstance.getVpnBondingLinks();
294 if(!vpnBondingLinkList.isEmpty()){
295 log.debug("Adding vpn bonding links to placement demands list");
296 for(VpnBondingLink vbl:vpnBondingLinkList){
297 List<ServiceProxy> serviceProxyList = vbl.getServiceProxies();
298 for(ServiceProxy sp : serviceProxyList){
299 if(isBlank(sp.getId())){
300 sp.setId(UUID.randomUUID().toString());
302 JSONObject demand = buildDemand(sp.getId(), sp.getModelInfoServiceProxy());
303 addCandidates(sp, demand);
304 placementDemands.put(demand);
308 return placementDemands;
312 * Builds the license demand list for the homing/licensing request
315 private JSONArray buildLicenseDemands(ServiceInstance serviceInstance){
316 log.trace("Building license information");
317 JSONArray licenseDemands = new JSONArray();
318 List<GenericVnf> vnfList = serviceInstance.getVnfs();
319 if(!vnfList.isEmpty()){
320 log.debug("Adding vnfs to license demands list");
321 for(GenericVnf vnf : vnfList){
322 JSONObject demand = buildDemand(vnf.getVnfId(), vnf.getModelInfoGenericVnf());
323 licenseDemands.put(demand);
326 return licenseDemands;
330 * Builds a single demand object
333 private JSONObject buildDemand(String id, ModelInfoMetadata metadata){
334 log.debug("Building demand for service or resource: " + id);
335 JSONObject demand = new JSONObject();
336 if(isNotBlank(id) && isNotBlank(metadata.getModelInstanceName())){
337 demand.put(SERVICE_RESOURCE_ID, id);
338 demand.put(RESOURCE_MODULE_NAME, metadata.getModelInstanceName());
339 demand.put(RESOURCE_MODEL_INFO, buildModelInfo(metadata));
341 throw new BpmnError(UNPROCESSABLE, RESOURCE_MISSING_DATA + "modelInstanceName");
347 * Builds the resource model info section
350 private JSONObject buildModelInfo(ModelInfoMetadata metadata){
351 JSONObject object = new JSONObject();
352 String invariantUuid = metadata.getModelInvariantUuid();
353 String modelUuid = metadata.getModelUuid();
354 if(isNotBlank(invariantUuid) && isNotBlank(modelUuid)){
355 object.put(MODEL_INVARIANT_ID, invariantUuid).put(MODEL_VERSION_ID, modelUuid).put(MODEL_NAME, metadata.getModelName()).put(MODEL_VERSION, metadata.getModelVersion());
356 }else if(isNotBlank(invariantUuid)){
357 throw new BpmnError(UNPROCESSABLE, RESOURCE_MISSING_DATA + MODEL_VERSION_ID);
359 throw new BpmnError(UNPROCESSABLE, RESOURCE_MISSING_DATA + MODEL_INVARIANT_ID);
365 * Adds required, excluded, and existing candidates to a demand
368 private void addCandidates(SolutionCandidates candidates, JSONObject demand){
369 List<Candidate> required = candidates.getRequiredCandidates();
370 List<Candidate> excluded = candidates.getExcludedCandidates();
371 if(!required.isEmpty()){
372 demand.put("requiredCandidates", required);
374 if(!excluded.isEmpty()){
375 demand.put("excludedCandidates", excluded);
377 //TODO support existing candidates
381 * Processes the license solutions and sets to the corresponding generic vnf
384 private void processLicenseSolution(ServiceInstance serviceInstance, JSONArray licenseSolutions){
385 List<GenericVnf> vnfs = serviceInstance.getVnfs();
387 log.debug("Processing the license solution");
388 for(int i = 0; i < licenseSolutions.length(); i++){
389 JSONObject licenseSolution = licenseSolutions.getJSONObject(i);
390 for(GenericVnf vnf:vnfs){
391 if(licenseSolution.getString(SERVICE_RESOURCE_ID).equals(vnf.getVnfId())){
392 License license = new License();
393 JSONArray entitlementPools = licenseSolution.getJSONArray("entitlementPoolUUID");
394 List<String> entitlementPoolsList = jsonUtils.StringArrayToList(entitlementPools);
395 license.setEntitlementPoolUuids(entitlementPoolsList);
396 JSONArray licenseKeys = licenseSolution.getJSONArray("licenseKeyGroupUUID");
397 List<String> licenseKeysList = jsonUtils.StringArrayToList(licenseKeys);
398 license.setLicenseKeyGroupUuids(licenseKeysList);
400 vnf.setLicense(license);
407 * Processes a placement solution list then correlates and sets each placement solution
408 * to its corresponding resource
411 private void processPlacementSolution(ServiceInstance serviceInstance, JSONArray placements, int i){
412 List<VpnBondingLink> links = serviceInstance.getVpnBondingLinks();
413 List<AllottedResource> allottes = serviceInstance.getAllottedResources();
414 List<GenericVnf> vnfs = serviceInstance.getVnfs();
416 log.debug("Processing placement solution " + i+1);
417 for(int p = 0; p < placements.length(); p++){
418 JSONObject placement = placements.getJSONObject(p);
419 SolutionInfo solutionInfo = new SolutionInfo();
420 solutionInfo.setSolutionId(i + 1);
422 for(VpnBondingLink vbl:links){
423 List<ServiceProxy> proxies = vbl.getServiceProxies();
424 for(ServiceProxy sp:proxies){
425 if(placement.getString(SERVICE_RESOURCE_ID).equals(sp.getId())){
428 VpnBondingLink vblNew = (VpnBondingLink) SerializationUtils.clone(vbl);
429 vblNew.setVpnBondingLinkId(UUID.randomUUID().toString());
432 links.get(links.size() - 1).getServiceProxy(sp.getId()).setServiceInstance(setSolution(solutionInfo, placement));
434 sp.setServiceInstance(setSolution(solutionInfo, placement));
440 for(AllottedResource ar:allottes){
441 if(placement.getString(SERVICE_RESOURCE_ID).equals(ar.getId())){
442 ar.setParentServiceInstance(setSolution(solutionInfo, placement));
446 for(GenericVnf vnf:vnfs){
447 if(placement.getString(SERVICE_RESOURCE_ID).equals(vnf.getVnfId())){
448 ServiceInstance si = setSolution(solutionInfo, placement);
449 serviceInstance.setSolutionInfo(si.getSolutionInfo());
450 serviceInstance.getVnfs().add(si.getVnfs().get(0));
460 * Creates and sets necessary pojos with placement solution data for a given demand
463 private ServiceInstance setSolution(SolutionInfo solutionInfo, JSONObject placement){
464 log.debug("Mapping placement solution");
465 String invalidMessage = "Sniro Managers Response contains invalid: ";
467 JSONObject solution = placement.getJSONObject("solution");
468 String identifierType = solution.getString(IDENTIFIER_TYPE);
469 List<String> identifiersList = jsonUtils.StringArrayToList(solution.getJSONArray("identifiers").toString());
470 String identifierValue = identifiersList.get(0);
472 JSONArray assignments = placement.getJSONArray("assignmentInfo");
473 Map<String, String> assignmentsMap = jsonUtils.entryArrayToMap(assignments.toString(), "key", "value");
474 solutionInfo.setRehome(Boolean.parseBoolean(assignmentsMap.get("isRehome")));
475 String type = placement.getString(INVENTORY_TYPE);
477 ServiceInstance si = new ServiceInstance();
478 CloudRegion cloud = setCloud(assignmentsMap);
479 if(type.equals("service")){
480 if(identifierType.equals(CandidateType.SERVICE_INSTANCE_ID.toString())){
481 solutionInfo.setHomed(true);
482 si.setServiceInstanceId(identifierValue);
483 si.setOrchestrationStatus(OrchestrationStatus.CREATED);
484 cloud.setLcpCloudRegionId(assignmentsMap.get("cloudRegionId"));
485 if(assignmentsMap.containsKey("vnfHostName")){
486 log.debug("Resources has been homed to a vnf");
487 GenericVnf vnf = setVnf(assignmentsMap);
488 vnf.setCloudRegion(cloud);
489 si.getVnfs().add(vnf);
491 }else if(assignmentsMap.containsKey("primaryPnfName")){
492 log.debug("Resources has been homed to a pnf");
493 Pnf priPnf = setPnf(assignmentsMap, "primary");
494 priPnf.setCloudRegion(cloud);
495 si.getPnfs().add(priPnf);
496 if(assignmentsMap.containsKey("secondaryPnfName")){
497 Pnf secPnf = setPnf(assignmentsMap, "secondary");
498 secPnf.setCloudRegion(cloud);
499 si.getPnfs().add(secPnf);
503 log.debug(invalidMessage + IDENTIFIER_TYPE);
504 throw new BpmnError(UNPROCESSABLE, invalidMessage + IDENTIFIER_TYPE);
506 }else if(type.equals("cloud")){
507 if(identifierType.equals(CandidateType.CLOUD_REGION_ID.toString())){
508 log.debug("Resources has been homed to a cloud region");
509 cloud.setLcpCloudRegionId(identifierValue);
510 solutionInfo.setHomed(false);
511 solutionInfo.setTargetedCloudRegion(cloud);
512 si.setOrchestrationStatus(OrchestrationStatus.PRECREATED);
514 log.debug(invalidMessage + IDENTIFIER_TYPE);
515 throw new BpmnError(UNPROCESSABLE, invalidMessage + IDENTIFIER_TYPE);
518 log.debug(invalidMessage + INVENTORY_TYPE);
519 throw new BpmnError(UNPROCESSABLE, invalidMessage + INVENTORY_TYPE);
521 si.setSolutionInfo(solutionInfo);
526 * Sets the cloud data to a cloud region object
529 private CloudRegion setCloud(Map<String, String> assignmentsMap){
530 CloudRegion cloud = new CloudRegion();
531 cloud.setCloudOwner(assignmentsMap.get("cloudOwner"));
532 cloud.setCloudRegionVersion(assignmentsMap.get("aicVersion"));
533 cloud.setComplex(assignmentsMap.get("aicClli"));
538 * Sets the vnf data to a generic vnf object
541 private GenericVnf setVnf(Map<String, String> assignmentsMap){
542 GenericVnf vnf = new GenericVnf();
543 vnf.setOrchestrationStatus(OrchestrationStatus.CREATED);
544 vnf.setVnfName(assignmentsMap.get("vnfHostName"));
545 vnf.setVnfId(assignmentsMap.get("vnfId"));
550 * Sets the pnf data to a pnf object
553 private Pnf setPnf(Map<String, String> assignmentsMap, String role){
556 pnf.setOrchestrationStatus(OrchestrationStatus.CREATED);
557 pnf.setPnfName(assignmentsMap.get(role + "PnfName"));