2 * ============LICENSE_START=======================================================
3 * Copyright (C) 2021 Nordix Foundation.
4 * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
5 * ================================================================================
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
10 * http://www.apache.org/licenses/LICENSE-2.0
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
18 * SPDX-License-Identifier: Apache-2.0
19 * ============LICENSE_END=========================================================
22 package org.onap.policy.clamp.controlloop.runtime.commissioning;
24 import com.fasterxml.jackson.core.JsonProcessingException;
25 import com.fasterxml.jackson.databind.ObjectMapper;
26 import com.fasterxml.jackson.databind.PropertyNamingStrategies;
27 import com.fasterxml.jackson.module.jsonSchema.factories.SchemaFactoryWrapper;
28 import java.util.ArrayList;
29 import java.util.Collections;
30 import java.util.HashMap;
31 import java.util.List;
33 import java.util.stream.Collectors;
34 import javax.ws.rs.core.Response.Status;
35 import org.apache.commons.collections4.CollectionUtils;
36 import org.apache.commons.collections4.MapUtils;
37 import org.onap.policy.clamp.controlloop.models.controlloop.concepts.Participant;
38 import org.onap.policy.clamp.controlloop.models.controlloop.persistence.provider.ControlLoopProvider;
39 import org.onap.policy.clamp.controlloop.models.controlloop.persistence.provider.ParticipantProvider;
40 import org.onap.policy.clamp.controlloop.models.messages.dmaap.participant.ParticipantUpdate;
41 import org.onap.policy.clamp.controlloop.models.messages.rest.commissioning.CommissioningResponse;
42 import org.onap.policy.clamp.controlloop.runtime.supervision.SupervisionHandler;
43 import org.onap.policy.models.base.PfModelException;
44 import org.onap.policy.models.provider.PolicyModelsProvider;
45 import org.onap.policy.models.tosca.authorative.concepts.ToscaCapabilityType;
46 import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier;
47 import org.onap.policy.models.tosca.authorative.concepts.ToscaDataType;
48 import org.onap.policy.models.tosca.authorative.concepts.ToscaNodeTemplate;
49 import org.onap.policy.models.tosca.authorative.concepts.ToscaNodeType;
50 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyType;
51 import org.onap.policy.models.tosca.authorative.concepts.ToscaProperty;
52 import org.onap.policy.models.tosca.authorative.concepts.ToscaRelationshipType;
53 import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate;
54 import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplates;
55 import org.onap.policy.models.tosca.authorative.concepts.ToscaTopologyTemplate;
56 import org.onap.policy.models.tosca.authorative.concepts.ToscaTypedEntityFilter;
57 import org.springframework.stereotype.Component;
60 * This class provides the create, read and delete actions on Commissioning of Control Loop concepts in the database to
64 public class CommissioningProvider {
65 public static final String CONTROL_LOOP_NODE_TYPE = "org.onap.policy.clamp.controlloop.ControlLoop";
66 private static final String INSTANCE_TEXT = "_Instance";
68 private final PolicyModelsProvider modelsProvider;
69 private final ControlLoopProvider clProvider;
70 private final ObjectMapper mapper = new ObjectMapper();
71 private final ParticipantProvider participantProvider;
72 private final SupervisionHandler supervisionHandler;
74 private static final Object lockit = new Object();
77 * Create a commissioning provider.
79 * @param modelsProvider the PolicyModelsProvider
80 * @param clProvider the ControlLoopProvider
82 public CommissioningProvider(PolicyModelsProvider modelsProvider,
83 ControlLoopProvider clProvider,
84 SupervisionHandler supervisionHandler,
85 ParticipantProvider participantProvider) {
86 this.modelsProvider = modelsProvider;
87 this.clProvider = clProvider;
88 this.supervisionHandler = supervisionHandler;
89 this.participantProvider = participantProvider;
90 mapper.setPropertyNamingStrategy(PropertyNamingStrategies.SNAKE_CASE);
94 * Create control loops from a service template.
96 * @param serviceTemplate the service template
97 * @return the result of the commissioning operation
98 * @throws PfModelException on creation errors
100 public CommissioningResponse createControlLoopDefinitions(ToscaServiceTemplate serviceTemplate)
101 throws PfModelException {
103 if (verifyIfInstancePropertiesExists()) {
104 throw new PfModelException(Status.BAD_REQUEST,
105 "Delete instances, to commission control loop definitions");
108 synchronized (lockit) {
109 modelsProvider.createServiceTemplate(serviceTemplate);
110 List<Participant> participantList =
111 participantProvider.getParticipants(null,
114 if (participantList != null) {
115 for (Participant participant: participantList) {
116 var participantType = new ToscaConceptIdentifier();
117 participantType.setName(participant.getType());
118 participantType.setVersion(participant.getTypeVersion());
120 var participantUpdate = new ParticipantUpdate();
121 participantUpdate.setParticipantId(participant.getDefinition());
122 participantUpdate.setParticipantType(participantType);
124 this.supervisionHandler.handleSendCommissionMessage(participantUpdate);
130 var response = new CommissioningResponse();
132 response.setAffectedControlLoopDefinitions(serviceTemplate.getToscaTopologyTemplate().getNodeTemplates()
135 .map(template -> template.getKey().asIdentifier())
136 .collect(Collectors.toList()));
143 * Delete the control loop definition with the given name and version.
145 * @param name the name of the control loop definition to delete
146 * @param version the version of the control loop to delete
147 * @return the result of the deletion
148 * @throws PfModelException on deletion errors
150 public CommissioningResponse deleteControlLoopDefinition(String name, String version)
151 throws PfModelException {
153 if (verifyIfInstancePropertiesExists()) {
154 throw new PfModelException(Status.BAD_REQUEST,
155 "Delete instances, to commission control loop definitions");
158 synchronized (lockit) {
159 List<Participant> participantList =
160 participantProvider.getParticipants(null,
163 if (participantList != null) {
164 for (Participant participant : participantList) {
165 var participantType = new ToscaConceptIdentifier();
166 participantType.setName(participant.getType());
167 participantType.setVersion(participant.getTypeVersion());
169 var participantUpdate = new ParticipantUpdate();
170 participantUpdate.setParticipantId(participant.getDefinition());
171 participantUpdate.setParticipantType(participantType);
173 this.supervisionHandler.handleSendDeCommissionMessage(participantUpdate);
177 modelsProvider.deleteServiceTemplate(name, version);
180 var response = new CommissioningResponse();
181 response.setAffectedControlLoopDefinitions(
182 Collections.singletonList(new ToscaConceptIdentifier(name, version)));
188 * Get control loop node templates.
190 * @param clName the name of the control loop, null for all
191 * @param clVersion the version of the control loop, null for all
192 * @return list of control loop node templates
193 * @throws PfModelException on errors getting control loop definitions
195 public List<ToscaNodeTemplate> getControlLoopDefinitions(String clName, String clVersion) throws PfModelException {
198 ToscaTypedEntityFilter<ToscaNodeTemplate> nodeTemplateFilter = ToscaTypedEntityFilter
199 .<ToscaNodeTemplate>builder()
202 .type(CONTROL_LOOP_NODE_TYPE)
206 return clProvider.getFilteredNodeTemplates(nodeTemplateFilter);
210 * Get the control loop elements from a control loop node template.
212 * @param controlLoopNodeTemplate the control loop node template
213 * @return a list of the control loop element node templates in a control loop node template
214 * @throws PfModelException on errors get control loop element node templates
216 public List<ToscaNodeTemplate> getControlLoopElementDefinitions(ToscaNodeTemplate controlLoopNodeTemplate)
217 throws PfModelException {
218 if (!CONTROL_LOOP_NODE_TYPE.equals(controlLoopNodeTemplate.getType())) {
219 return Collections.emptyList();
222 if (MapUtils.isEmpty(controlLoopNodeTemplate.getProperties())) {
223 return Collections.emptyList();
226 @SuppressWarnings("unchecked")
227 List<Map<String, String>> controlLoopElements =
228 (List<Map<String, String>>) controlLoopNodeTemplate.getProperties().get("elements");
230 if (CollectionUtils.isEmpty(controlLoopElements)) {
231 return Collections.emptyList();
234 List<ToscaNodeTemplate> controlLoopElementList = new ArrayList<>();
236 controlLoopElementList.addAll(
239 .map(elementMap -> clProvider.getNodeTemplates(elementMap.get("name"),
240 elementMap.get("version")))
241 .flatMap(List::stream)
242 .collect(Collectors.toList())
246 return controlLoopElementList;
250 * Get the initial node types with common or instance properties.
252 * @param fullNodeTypes map of all the node types in the specified template
253 * @param common boolean to indicate whether common or instance properties are required
254 * @return node types map that only has common properties
255 * @throws PfModelException on errors getting node type with common properties
257 private Map<String, ToscaNodeType> getInitialNodeTypesMap(Map<String, ToscaNodeType> fullNodeTypes,
260 var tempNodeTypesMap = new HashMap<String, ToscaNodeType>();
262 fullNodeTypes.forEach((key, nodeType) -> {
263 var tempToscaNodeType = new ToscaNodeType();
264 tempToscaNodeType.setName(key);
266 var resultantPropertyMap = findCommonOrInstancePropsInNodeTypes(nodeType, common);
268 if (!resultantPropertyMap.isEmpty()) {
269 tempToscaNodeType.setProperties(resultantPropertyMap);
270 tempNodeTypesMap.put(key, tempToscaNodeType);
273 return tempNodeTypesMap;
276 private Map<String, ToscaProperty> findCommonOrInstancePropsInNodeTypes(ToscaNodeType nodeType, boolean common) {
278 var tempCommonPropertyMap = new HashMap<String, ToscaProperty>();
279 var tempInstancePropertyMap = new HashMap<String, ToscaProperty>();
281 nodeType.getProperties().forEach((propKey, prop) -> {
283 if (prop.getMetadata() != null) {
284 prop.getMetadata().forEach((k, v) -> {
285 if (k.equals("common") && v.equals("true") && common) {
286 tempCommonPropertyMap.put(propKey, prop);
287 } else if (k.equals("common") && v.equals("false") && !common) {
288 tempInstancePropertyMap.put(propKey, prop);
293 tempInstancePropertyMap.put(propKey, prop);
297 if (tempCommonPropertyMap.isEmpty() && !common) {
298 return tempInstancePropertyMap;
300 return tempCommonPropertyMap;
305 * Get the node types derived from those that have common properties.
307 * @param initialNodeTypes map of all the node types in the specified template
308 * @param filteredNodeTypes map of all the node types that have common or instance properties
309 * @return all node types that have common properties including their children
310 * @throws PfModelException on errors getting node type with common properties
312 private Map<String, ToscaNodeType> getFinalNodeTypesMap(Map<String, ToscaNodeType> initialNodeTypes,
313 Map<String, ToscaNodeType> filteredNodeTypes) {
314 for (var i = 0; i < initialNodeTypes.size(); i++) {
315 initialNodeTypes.forEach((key, nodeType) -> {
316 var tempToscaNodeType = new ToscaNodeType();
317 tempToscaNodeType.setName(key);
319 if (filteredNodeTypes.get(nodeType.getDerivedFrom()) != null) {
320 tempToscaNodeType.setName(key);
322 var finalProps = new HashMap<String, ToscaProperty>(
323 filteredNodeTypes.get(nodeType.getDerivedFrom()).getProperties());
325 tempToscaNodeType.setProperties(finalProps);
329 filteredNodeTypes.putIfAbsent(key, tempToscaNodeType);
333 return filteredNodeTypes;
337 * Get the requested node types with common or instance properties.
339 * @param common boolean indicating common or instance properties
340 * @param name the name of the definition to get, null for all definitions
341 * @param version the version of the definition to get, null for all definitions
342 * @return the node types with common or instance properties
343 * @throws PfModelException on errors getting node type properties
345 private Map<String, ToscaNodeType> getCommonOrInstancePropertiesFromNodeTypes(boolean common, String name,
346 String version) throws PfModelException {
347 var serviceTemplates = new ToscaServiceTemplates();
348 serviceTemplates.setServiceTemplates(modelsProvider.getServiceTemplateList(name, version));
349 var tempNodeTypesMap =
350 this.getInitialNodeTypesMap(serviceTemplates.getServiceTemplates().get(0).getNodeTypes(), common);
352 return this.getFinalNodeTypesMap(serviceTemplates.getServiceTemplates().get(0).getNodeTypes(),
358 * Get node templates with appropriate common or instance properties added.
360 * @param initialNodeTemplates map of all the node templates in the specified template
361 * @param nodeTypeProps map of all the node types that have common or instance properties including children
362 * @return all node templates with appropriate common or instance properties added
363 * @throws PfModelException on errors getting map of node templates with common or instance properties added
365 private Map<String, ToscaNodeTemplate> getDerivedCommonOrInstanceNodeTemplates(
366 Map<String, ToscaNodeTemplate> initialNodeTemplates, Map<String, ToscaNodeType> nodeTypeProps) {
368 var finalNodeTemplatesMap = new HashMap<String, ToscaNodeTemplate>();
370 initialNodeTemplates.forEach((templateKey, template) -> {
371 if (nodeTypeProps.containsKey(template.getType())) {
372 var finalMergedProps = new HashMap<String, Object>();
374 nodeTypeProps.get(template.getType()).getProperties().forEach(finalMergedProps::putIfAbsent);
376 template.setProperties(finalMergedProps);
378 finalNodeTemplatesMap.put(templateKey, template);
383 return finalNodeTemplatesMap;
387 * Get node templates with common properties added.
389 * @param common boolean indicating common or instance properties to be used
390 * @param name the name of the definition to use, null for all definitions
391 * @param version the version of the definition to use, null for all definitions
392 * @return the nodes templates with common or instance properties
393 * @throws PfModelException on errors getting common or instance properties from node_templates
395 public Map<String, ToscaNodeTemplate> getNodeTemplatesWithCommonOrInstanceProperties(boolean common, String name,
396 String version) throws PfModelException {
398 if (common && verifyIfInstancePropertiesExists()) {
399 throw new PfModelException(Status.BAD_REQUEST,
400 "Cannot create or edit common properties, delete all the instantiations first");
403 var commonOrInstanceNodeTypeProps =
404 this.getCommonOrInstancePropertiesFromNodeTypes(common, name, version);
406 var serviceTemplates = new ToscaServiceTemplates();
407 serviceTemplates.setServiceTemplates(filterToscaNodeTemplateInstance(
408 modelsProvider.getServiceTemplateList(name, version)));
410 return this.getDerivedCommonOrInstanceNodeTemplates(
411 serviceTemplates.getServiceTemplates().get(0).getToscaTopologyTemplate().getNodeTemplates(),
412 commonOrInstanceNodeTypeProps);
416 * Get the requested control loop definitions.
418 * @param name the name of the definition to get, null for all definitions
419 * @param version the version of the definition to get, null for all definitions
420 * @return the control loop definitions
421 * @throws PfModelException on errors getting control loop definitions
423 public ToscaServiceTemplate getToscaServiceTemplate(String name, String version) throws PfModelException {
424 var serviceTemplates = new ToscaServiceTemplates();
425 serviceTemplates.setServiceTemplates(modelsProvider.getServiceTemplateList(name, version));
426 return serviceTemplates.getServiceTemplates().get(0);
430 * Get the tosca service template with only required sections.
432 * @param name the name of the template to get, null for all definitions
433 * @param version the version of the template to get, null for all definitions
434 * @return the tosca service template
435 * @throws PfModelException on errors getting tosca service template
437 public String getToscaServiceTemplateReduced(String name, String version)
438 throws PfModelException {
440 var serviceTemplates = new ToscaServiceTemplates();
441 serviceTemplates.setServiceTemplates(modelsProvider.getServiceTemplateList(name, version));
443 ToscaServiceTemplate fullTemplate = filterToscaNodeTemplateInstance(
444 serviceTemplates.getServiceTemplates()).get(0);
446 var template = new HashMap<String, Object>();
447 template.put("tosca_definitions_version", fullTemplate.getToscaDefinitionsVersion());
448 template.put("data_types", fullTemplate.getDataTypes());
449 template.put("policy_types", fullTemplate.getPolicyTypes());
450 template.put("node_types", fullTemplate.getNodeTypes());
451 template.put("topology_template", fullTemplate.getToscaTopologyTemplate());
454 return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(template);
456 } catch (JsonProcessingException e) {
457 throw new PfModelException(Status.BAD_REQUEST, "Converion to Json Schema failed", e);
462 * Get the requested json schema.
464 * @param section section of the tosca service template to get schema for
465 * @return the specified tosca service template or section Json Schema
466 * @throws PfModelException on errors with retrieving the classes
468 public String getToscaServiceTemplateSchema(String section) throws PfModelException {
469 var visitor = new SchemaFactoryWrapper();
474 mapper.acceptJsonFormatVisitor(mapper.constructType(ToscaDataType.class), visitor);
476 case "capability_types":
477 mapper.acceptJsonFormatVisitor(mapper.constructType(ToscaCapabilityType.class), visitor);
480 mapper.acceptJsonFormatVisitor(mapper.constructType(ToscaNodeType.class), visitor);
482 case "relationship_types":
483 mapper.acceptJsonFormatVisitor(mapper.constructType(ToscaRelationshipType.class), visitor);
486 mapper.acceptJsonFormatVisitor(mapper.constructType(ToscaPolicyType.class), visitor);
488 case "topology_template":
489 mapper.acceptJsonFormatVisitor(mapper.constructType(ToscaTopologyTemplate.class), visitor);
491 case "node_templates":
492 mapper.acceptJsonFormatVisitor(
493 mapper.getTypeFactory().constructCollectionType(List.class, ToscaNodeTemplate.class),
497 mapper.acceptJsonFormatVisitor(mapper.constructType(ToscaServiceTemplate.class), visitor);
500 var jsonSchema = visitor.finalSchema();
501 return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonSchema);
502 } catch (JsonProcessingException e) {
503 throw new PfModelException(Status.BAD_REQUEST, "Converion to Json Schema failed", e);
507 private List<ToscaServiceTemplate> filterToscaNodeTemplateInstance(List<ToscaServiceTemplate> serviceTemplates) {
509 List<ToscaServiceTemplate> toscaServiceTemplates = new ArrayList<>();
511 serviceTemplates.stream().forEach(serviceTemplate -> {
513 Map<String, ToscaNodeTemplate> toscaNodeTemplates = new HashMap<>();
515 serviceTemplate.getToscaTopologyTemplate().getNodeTemplates().forEach((key, nodeTemplate) -> {
516 if (!nodeTemplate.getName().contains(INSTANCE_TEXT)) {
517 toscaNodeTemplates.put(key, nodeTemplate);
521 serviceTemplate.getToscaTopologyTemplate().getNodeTemplates().clear();
522 serviceTemplate.getToscaTopologyTemplate().setNodeTemplates(toscaNodeTemplates);
524 toscaServiceTemplates.add(serviceTemplate);
527 return toscaServiceTemplates;
531 * Validates to see if there is any instance properties saved.
533 * @return true if exists instance properties
535 private boolean verifyIfInstancePropertiesExists() {
536 return clProvider.getNodeTemplates(null, null).stream()
537 .anyMatch(nodeTemplate -> nodeTemplate.getKey().getName().contains(INSTANCE_TEXT));