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.camunda.bpm.engine.delegate.DelegateExecution;
33 import org.json.JSONArray;
34 import org.json.JSONObject;
35 import org.onap.so.bpmn.common.BuildingBlockExecution;
36 import org.onap.so.bpmn.core.json.JsonUtils;
37 import org.onap.so.bpmn.servicedecomposition.bbobjects.AllottedResource;
38 import org.onap.so.bpmn.servicedecomposition.bbobjects.CloudRegion;
39 import org.onap.so.bpmn.servicedecomposition.bbobjects.Customer;
40 import org.onap.so.bpmn.servicedecomposition.bbobjects.GenericVnf;
41 import org.onap.so.bpmn.servicedecomposition.bbobjects.Pnf;
42 import org.onap.so.bpmn.servicedecomposition.bbobjects.ServiceInstance;
43 import org.onap.so.bpmn.servicedecomposition.bbobjects.ServiceProxy;
44 import org.onap.so.bpmn.servicedecomposition.bbobjects.VpnBondingLink;
45 import org.onap.so.bpmn.servicedecomposition.entities.GeneralBuildingBlock;
46 import org.onap.so.bpmn.servicedecomposition.generalobjects.License;
47 import org.onap.so.bpmn.servicedecomposition.generalobjects.RequestContext;
48 import org.onap.so.bpmn.servicedecomposition.generalobjects.RequestParameters;
49 import org.onap.so.bpmn.servicedecomposition.homingobjects.Candidate;
50 import org.onap.so.bpmn.servicedecomposition.homingobjects.CandidateType;
51 import org.onap.so.bpmn.servicedecomposition.homingobjects.SolutionCandidates;
52 import org.onap.so.bpmn.servicedecomposition.homingobjects.SolutionInfo;
53 import org.onap.so.bpmn.servicedecomposition.modelinfo.ModelInfoMetadata;
54 import org.onap.so.bpmn.servicedecomposition.modelinfo.ModelInfoServiceInstance;
55 import org.onap.so.client.exception.BadResponseException;
56 import org.onap.so.client.exception.ExceptionBuilder;
58 import org.onap.so.client.sniro.SniroClient;
59 import static org.onap.so.client.sniro.SniroValidator.*;
61 import org.onap.so.client.sniro.beans.SniroManagerRequest;
62 import org.onap.so.db.catalog.beans.OrchestrationStatus;
63 import org.onap.so.logger.MsoLogger;
64 import org.springframework.beans.factory.annotation.Autowired;
65 import org.springframework.core.env.Environment;
66 import org.springframework.stereotype.Component;
67 import org.springframework.web.util.UriUtils;
71 * The sniro homing building block obtains licensing and homing solutions for a given
72 * resource or set of resources.
77 @Component("SniroHoming")
78 public class SniroHomingV2 {
80 private static final MsoLogger log = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, SniroHomingV2.class);
81 private JsonUtils jsonUtils = new JsonUtils();
83 private Environment env;
85 private SniroClient client;
87 private ExceptionBuilder exceptionUtil;
88 private static final String MODEL_NAME = "modelName";
89 private static final String MODEL_INVARIANT_ID = "modelInvariantId";
90 private static final String MODEL_VERSION_ID = "modelVersionId";
91 private static final String MODEL_VERSION = "modelVersion";
92 private static final String SERVICE_RESOURCE_ID = "serviceResourceId";
93 private static final String RESOURCE_MODULE_NAME = "resourceModuleName";
94 private static final String RESOURCE_MODEL_INFO = "resourceModelInfo";
95 private static final String IDENTIFIER_TYPE = "identifierType";
96 private static final String INVENTORY_TYPE = "inventoryType";
97 private static final String SOLUTIONS = "solutions";
98 private static final String RESOURCE_MISSING_DATA = "Resource does not contain: ";
99 private static final String SERVICE_MISSING_DATA = "Service Instance does not contain: ";
100 private static final String UNPROCESSABLE = "422";
101 private static final int INTERNAL = 500;
104 * Generates the request payload then sends to sniro manager to perform homing and
105 * licensing for the provided demands
109 public void callSniro(BuildingBlockExecution execution){
110 log.trace("Started Sniro Homing Call Sniro");
112 GeneralBuildingBlock bb = execution.getGeneralBuildingBlock();
114 RequestContext requestContext = bb.getRequestContext();
115 RequestParameters requestParams = requestContext.getRequestParameters();
116 String requestId = requestContext.getMsoRequestId();
118 ServiceInstance serviceInstance = bb.getCustomer().getServiceSubscription().getServiceInstances().get(0);
119 Customer customer = bb.getCustomer();
121 String timeout = execution.getVariable("timeout");
122 if(isBlank(timeout)){
123 timeout = env.getProperty("sniro.manager.timeout", "PT30M");
126 SniroManagerRequest request = new SniroManagerRequest(); //TODO Add additional pojos for each section
128 JSONObject requestInfo = buildRequestInfo(requestId, timeout);
129 request.setRequestInformation(requestInfo.toString());
131 JSONObject serviceInfo = buildServiceInfo(serviceInstance);
132 request.setServiceInformation(serviceInfo.toString());
134 JSONObject placementInfo = buildPlacementInfo(customer, requestParams);
136 JSONArray placementDemands = buildPlacementDemands(serviceInstance);
137 placementInfo.put("placementDemands", placementDemands);
138 request.setPlacementInformation(placementInfo.toString());
140 JSONObject licenseInfo = new JSONObject();
142 JSONArray licenseDemands = buildLicenseDemands(serviceInstance);
143 licenseInfo.put("licenseDemands", licenseDemands);
144 request.setLicenseInformation(licenseInfo.toString());
146 if(placementDemands.length() > 0 || licenseDemands.length() > 0){
147 client.postDemands(request);
149 log.debug(SERVICE_MISSING_DATA + "resources eligible for homing or licensing");
150 throw new BpmnError(UNPROCESSABLE, SERVICE_MISSING_DATA + "resources eligible for homing or licensing");
153 //Variables for ReceiveWorkflowMessage subflow
154 execution.setVariable("asyncCorrelator", requestId);
155 execution.setVariable("asyncMessageType", "SNIROResponse");
156 execution.setVariable("asyncTimeout", timeout);
158 log.trace("Completed Sniro Homing Call Sniro");
160 exceptionUtil.buildAndThrowWorkflowException(execution, Integer.parseInt(e.getErrorCode()), e.getMessage());
161 }catch(BadResponseException e){
162 exceptionUtil.buildAndThrowWorkflowException(execution, 400, e.getMessage());
164 exceptionUtil.buildAndThrowWorkflowException(execution, INTERNAL, "Internal Error - occurred while preparing sniro request: " + e.getMessage());
169 * Validates, processes, and sets the homing and licensing solutions that are returned by
173 * @param asyncResponse
175 public void processSolution(BuildingBlockExecution execution, String asyncResponse){
176 log.trace("Started Sniro Homing Process Solution");
178 //TODO improve handling multiple solutions but is dependent on sniro enhancing api + work with sniro conductor to improve "inventoryType" representation
179 validateSolution(asyncResponse);
180 ServiceInstance serviceInstance = execution.getGeneralBuildingBlock().getCustomer().getServiceSubscription().getServiceInstances().get(0);
182 log.debug("Processing sniro manager asyncronous response");
183 JSONObject response = new JSONObject(asyncResponse);
184 if(response.has(SOLUTIONS)){
185 JSONObject allSolutions = response.getJSONObject(SOLUTIONS);
186 if(allSolutions.has("placementSolutions")){
187 JSONArray placementSolutions = allSolutions.getJSONArray("placementSolutions");
188 for(int i = 0; i < placementSolutions.length(); i++){
189 JSONArray placements = placementSolutions.getJSONArray(i);
190 processPlacementSolution(serviceInstance, placements, i);
193 if(allSolutions.has("licenseSolutions")){
194 JSONArray licenseSolutions = allSolutions.getJSONArray("licenseSolutions");
195 if(licenseSolutions.length() > 0){
196 processLicenseSolution(serviceInstance, licenseSolutions);
200 throw new BpmnError(UNPROCESSABLE, "Sniro Managers response does not contain: " + SOLUTIONS);
203 execution.setVariable("generalBuildingBlock", execution.getGeneralBuildingBlock());
205 log.trace("Completed Sniro Homing Process Solution");
207 exceptionUtil.buildAndThrowWorkflowException(execution, Integer.parseInt(e.getErrorCode()), e.getMessage());
208 }catch(BadResponseException e){
209 exceptionUtil.buildAndThrowWorkflowException(execution, 400, e.getMessage());
211 exceptionUtil.buildAndThrowWorkflowException(execution, INTERNAL, "Internal Error - occurred while processing sniro asynchronous response: " + e.getMessage());
216 * Builds the request information section for the homing/licensing request
220 private JSONObject buildRequestInfo(String requestId, String timeout) throws Exception{
221 log.trace("Building request information");
222 JSONObject requestInfo = new JSONObject();
223 if(requestId != null){
224 String host = env.getProperty("mso.workflow.message.endpoint");
225 String callbackUrl = host + "/" + UriUtils.encodePathSegment("SNIROResponse", "UTF-8") + "/" + UriUtils.encodePathSegment(requestId, "UTF-8");
227 Duration d = Duration.parse(timeout);
228 long timeoutSeconds = d.getSeconds();
230 requestInfo.put("transactionId", requestId).put("requestId", requestId).put("callbackUrl", callbackUrl).put("sourceId", "mso").put("requestType", "create")
231 .put("timeout", timeoutSeconds);
233 throw new BpmnError(UNPROCESSABLE, "Request Context does not contain: requestId");
239 * Builds the request information section for the homing/licensing request
242 private JSONObject buildServiceInfo(ServiceInstance serviceInstance){
243 log.trace("Building service information");
244 JSONObject info = new JSONObject();
245 ModelInfoServiceInstance modelInfo = serviceInstance.getModelInfoServiceInstance();
246 if(isNotBlank(modelInfo.getModelInvariantUuid()) && isNotBlank(modelInfo.getModelUuid())){
247 info.put("serviceInstanceId", serviceInstance.getServiceInstanceId());
248 if(modelInfo.getServiceType() != null && modelInfo.getServiceType().length() > 0){ //temp solution
249 info.put("serviceName", modelInfo.getServiceType());
251 info.put("modelInfo", buildModelInfo(serviceInstance.getModelInfoServiceInstance()));
253 throw new BpmnError(UNPROCESSABLE, SERVICE_MISSING_DATA + MODEL_VERSION_ID + ", " + MODEL_INVARIANT_ID);
259 * Builds initial section of placement info for the homing/licensing request
262 private JSONObject buildPlacementInfo(Customer customer, RequestParameters requestParams){
263 JSONObject placementInfo = new JSONObject();
264 if(customer != null){
265 log.debug("Adding subscriber to placement information");
266 placementInfo.put("subscriberInfo", new JSONObject().put("globalSubscriberId", customer.getGlobalCustomerId()).put("subscriberName", customer.getSubscriberName()).put("subscriberCommonSiteId", customer.getSubscriberCommonSiteId()));
267 if(requestParams != null){
268 log.debug("Adding request parameters to placement information");
269 placementInfo.put("requestParameters", new JSONObject(requestParams.toJsonString()));
272 throw new BpmnError(UNPROCESSABLE, SERVICE_MISSING_DATA + "customer");
274 return placementInfo;
279 * Builds the placement demand list for the homing/licensing request
282 private JSONArray buildPlacementDemands(ServiceInstance serviceInstance){
283 log.trace("Building placement information demands");
284 JSONArray placementDemands = new JSONArray();
286 List<AllottedResource> allottedResourceList = serviceInstance.getAllottedResources();
287 if(!allottedResourceList.isEmpty()){
288 log.debug("Adding allotted resources to placement demands list");
289 for(AllottedResource ar : allottedResourceList){
290 if(isBlank(ar.getId())){
291 ar.setId(UUID.randomUUID().toString());
293 JSONObject demand = buildDemand(ar.getId(), ar.getModelInfoAllottedResource());
294 addCandidates(ar, demand);
295 placementDemands.put(demand);
298 List<VpnBondingLink> vpnBondingLinkList = serviceInstance.getVpnBondingLinks();
299 if(!vpnBondingLinkList.isEmpty()){
300 log.debug("Adding vpn bonding links to placement demands list");
301 for(VpnBondingLink vbl:vpnBondingLinkList){
302 List<ServiceProxy> serviceProxyList = vbl.getServiceProxies();
303 for(ServiceProxy sp : serviceProxyList){
304 if(isBlank(sp.getId())){
305 sp.setId(UUID.randomUUID().toString());
307 JSONObject demand = buildDemand(sp.getId(), sp.getModelInfoServiceProxy());
308 addCandidates(sp, demand);
309 placementDemands.put(demand);
313 return placementDemands;
317 * Builds the license demand list for the homing/licensing request
320 private JSONArray buildLicenseDemands(ServiceInstance serviceInstance){
321 log.trace("Building license information");
322 JSONArray licenseDemands = new JSONArray();
323 List<GenericVnf> vnfList = serviceInstance.getVnfs();
324 if(!vnfList.isEmpty()){
325 log.debug("Adding vnfs to license demands list");
326 for(GenericVnf vnf : vnfList){
327 JSONObject demand = buildDemand(vnf.getVnfId(), vnf.getModelInfoGenericVnf());
328 licenseDemands.put(demand);
331 return licenseDemands;
335 * Builds a single demand object
338 private JSONObject buildDemand(String id, ModelInfoMetadata metadata){
339 log.debug("Building demand for service or resource: " + id);
340 JSONObject demand = new JSONObject();
341 if(isNotBlank(id) && isNotBlank(metadata.getModelInstanceName())){
342 demand.put(SERVICE_RESOURCE_ID, id);
343 demand.put(RESOURCE_MODULE_NAME, metadata.getModelInstanceName());
344 demand.put(RESOURCE_MODEL_INFO, buildModelInfo(metadata));
346 throw new BpmnError(UNPROCESSABLE, RESOURCE_MISSING_DATA + "modelInstanceName");
352 * Builds the resource model info section
355 private JSONObject buildModelInfo(ModelInfoMetadata metadata){
356 JSONObject object = new JSONObject();
357 String invariantUuid = metadata.getModelInvariantUuid();
358 String modelUuid = metadata.getModelUuid();
359 if(isNotBlank(invariantUuid) && isNotBlank(modelUuid)){
360 object.put(MODEL_INVARIANT_ID, invariantUuid).put(MODEL_VERSION_ID, modelUuid).put(MODEL_NAME, metadata.getModelName()).put(MODEL_VERSION, metadata.getModelVersion());
361 }else if(isNotBlank(invariantUuid)){
362 throw new BpmnError(UNPROCESSABLE, RESOURCE_MISSING_DATA + MODEL_VERSION_ID);
364 throw new BpmnError(UNPROCESSABLE, RESOURCE_MISSING_DATA + MODEL_INVARIANT_ID);
370 * Adds required, excluded, and existing candidates to a demand
373 private void addCandidates(SolutionCandidates candidates, JSONObject demand){
374 List<Candidate> required = candidates.getRequiredCandidates();
375 List<Candidate> excluded = candidates.getExcludedCandidates();
376 if(!required.isEmpty()){
377 demand.put("requiredCandidates", required);
379 if(!excluded.isEmpty()){
380 demand.put("excludedCandidates", excluded);
382 //TODO support existing candidates
386 * Processes the license solutions and sets to the corresponding generic vnf
389 private void processLicenseSolution(ServiceInstance serviceInstance, JSONArray licenseSolutions){
390 List<GenericVnf> vnfs = serviceInstance.getVnfs();
392 log.debug("Processing the license solution");
393 for(int i = 0; i < licenseSolutions.length(); i++){
394 JSONObject licenseSolution = licenseSolutions.getJSONObject(i);
395 for(GenericVnf vnf:vnfs){
396 if(licenseSolution.getString(SERVICE_RESOURCE_ID).equals(vnf.getVnfId())){
397 License license = new License();
398 JSONArray entitlementPools = licenseSolution.getJSONArray("entitlementPoolUUID");
399 List<String> entitlementPoolsList = jsonUtils.StringArrayToList(entitlementPools);
400 license.setEntitlementPoolUuids(entitlementPoolsList);
401 JSONArray licenseKeys = licenseSolution.getJSONArray("licenseKeyGroupUUID");
402 List<String> licenseKeysList = jsonUtils.StringArrayToList(licenseKeys);
403 license.setLicenseKeyGroupUuids(licenseKeysList);
405 vnf.setLicense(license);
412 * Processes a placement solution list then correlates and sets each placement solution
413 * to its corresponding resource
416 private void processPlacementSolution(ServiceInstance serviceInstance, JSONArray placements, int i){
417 List<VpnBondingLink> links = serviceInstance.getVpnBondingLinks();
418 List<AllottedResource> allottes = serviceInstance.getAllottedResources();
419 List<GenericVnf> vnfs = serviceInstance.getVnfs();
421 log.debug("Processing placement solution " + i+1);
422 for(int p = 0; p < placements.length(); p++){
423 JSONObject placement = placements.getJSONObject(p);
424 SolutionInfo solutionInfo = new SolutionInfo();
425 solutionInfo.setSolutionId(i + 1);
427 for(VpnBondingLink vbl:links){
428 List<ServiceProxy> proxies = vbl.getServiceProxies();
429 for(ServiceProxy sp:proxies){
430 if(placement.getString(SERVICE_RESOURCE_ID).equals(sp.getId())){
433 VpnBondingLink vblNew = (VpnBondingLink) SerializationUtils.clone(vbl);
434 vblNew.setVpnBondingLinkId(UUID.randomUUID().toString());
437 links.get(links.size() - 1).getServiceProxy(sp.getId()).setServiceInstance(setSolution(solutionInfo, placement));
439 sp.setServiceInstance(setSolution(solutionInfo, placement));
445 for(AllottedResource ar:allottes){
446 if(placement.getString(SERVICE_RESOURCE_ID).equals(ar.getId())){
447 ar.setParentServiceInstance(setSolution(solutionInfo, placement));
451 for(GenericVnf vnf:vnfs){
452 if(placement.getString(SERVICE_RESOURCE_ID).equals(vnf.getVnfId())){
453 ServiceInstance si = setSolution(solutionInfo, placement);
454 serviceInstance.setSolutionInfo(si.getSolutionInfo());
455 serviceInstance.getVnfs().add(si.getVnfs().get(0));
465 * Creates and sets necessary pojos with placement solution data for a given demand
468 private ServiceInstance setSolution(SolutionInfo solutionInfo, JSONObject placement){
469 log.debug("Mapping placement solution");
470 String invalidMessage = "Sniro Managers Response contains invalid: ";
472 JSONObject solution = placement.getJSONObject("solution");
473 String identifierType = solution.getString(IDENTIFIER_TYPE);
474 List<String> identifiersList = jsonUtils.StringArrayToList(solution.getJSONArray("identifiers").toString());
475 String identifierValue = identifiersList.get(0);
477 JSONArray assignments = placement.getJSONArray("assignmentInfo");
478 Map<String, String> assignmentsMap = jsonUtils.entryArrayToMap(assignments.toString(), "key", "value");
479 solutionInfo.setRehome(Boolean.parseBoolean(assignmentsMap.get("isRehome")));
480 String type = placement.getString(INVENTORY_TYPE);
482 ServiceInstance si = new ServiceInstance();
483 CloudRegion cloud = setCloud(assignmentsMap);
484 if(type.equals("service")){
485 if(identifierType.equals(CandidateType.SERVICE_INSTANCE_ID.toString())){
486 solutionInfo.setHomed(true);
487 si.setServiceInstanceId(identifierValue);
488 si.setOrchestrationStatus(OrchestrationStatus.CREATED);
489 cloud.setLcpCloudRegionId(assignmentsMap.get("cloudRegionId"));
490 if(assignmentsMap.containsKey("vnfHostName")){
491 log.debug("Resources has been homed to a vnf");
492 GenericVnf vnf = setVnf(assignmentsMap);
493 vnf.setCloudRegion(cloud);
494 si.getVnfs().add(vnf);
496 }else if(assignmentsMap.containsKey("primaryPnfName")){
497 log.debug("Resources has been homed to a pnf");
498 Pnf priPnf = setPnf(assignmentsMap, "primary");
499 priPnf.setCloudRegion(cloud);
500 si.getPnfs().add(priPnf);
501 if(assignmentsMap.containsKey("secondaryPnfName")){
502 Pnf secPnf = setPnf(assignmentsMap, "secondary");
503 secPnf.setCloudRegion(cloud);
504 si.getPnfs().add(secPnf);
508 log.debug(invalidMessage + IDENTIFIER_TYPE);
509 throw new BpmnError(UNPROCESSABLE, invalidMessage + IDENTIFIER_TYPE);
511 }else if(type.equals("cloud")){
512 if(identifierType.equals(CandidateType.CLOUD_REGION_ID.toString())){
513 log.debug("Resources has been homed to a cloud region");
514 cloud.setLcpCloudRegionId(identifierValue);
515 solutionInfo.setHomed(false);
516 solutionInfo.setTargetedCloudRegion(cloud);
517 si.setOrchestrationStatus(OrchestrationStatus.PRECREATED);
519 log.debug(invalidMessage + IDENTIFIER_TYPE);
520 throw new BpmnError(UNPROCESSABLE, invalidMessage + IDENTIFIER_TYPE);
523 log.debug(invalidMessage + INVENTORY_TYPE);
524 throw new BpmnError(UNPROCESSABLE, invalidMessage + INVENTORY_TYPE);
526 si.setSolutionInfo(solutionInfo);
531 * Sets the cloud data to a cloud region object
534 private CloudRegion setCloud(Map<String, String> assignmentsMap){
535 CloudRegion cloud = new CloudRegion();
536 cloud.setCloudOwner(assignmentsMap.get("cloudOwner"));
537 cloud.setCloudRegionVersion(assignmentsMap.get("aicVersion"));
538 cloud.setComplex(assignmentsMap.get("aicClli"));
543 * Sets the vnf data to a generic vnf object
546 private GenericVnf setVnf(Map<String, String> assignmentsMap){
547 GenericVnf vnf = new GenericVnf();
548 vnf.setOrchestrationStatus(OrchestrationStatus.CREATED);
549 vnf.setVnfName(assignmentsMap.get("vnfHostName"));
550 vnf.setVnfId(assignmentsMap.get("vnfId"));
555 * Sets the pnf data to a pnf object
558 private Pnf setPnf(Map<String, String> assignmentsMap, String role){
561 pnf.setOrchestrationStatus(OrchestrationStatus.CREATED);
562 pnf.setPnfName(assignmentsMap.get(role + "PnfName"));