2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2019 AT&T Intellectual Property. All rights
7 * ================================================================================
8 * Licensed under the Apache License, Version 2.0 (the "License");
9 * you may not use this file except in compliance with the License.
10 * You may obtain a copy of the License at
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing, software
15 * distributed under the License is distributed on an "AS IS" BASIS,
16 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 * See the License for the specific language governing permissions and
18 * limitations under the License.
19 * ============LICENSE_END============================================
20 * ===================================================================
24 package org.onap.clamp.loop;
26 import com.att.eelf.configuration.EELFLogger;
27 import com.att.eelf.configuration.EELFManager;
28 import com.google.gson.JsonObject;
30 import java.io.IOException;
31 import java.util.Arrays;
32 import java.util.HashSet;
33 import java.util.List;
35 import java.util.Map.Entry;
37 import org.json.simple.parser.ParseException;
38 import org.onap.clamp.clds.client.DcaeInventoryServices;
39 import org.onap.clamp.clds.exception.policy.PolicyModelException;
40 import org.onap.clamp.clds.exception.sdc.controller.SdcArtifactInstallerException;
41 import org.onap.clamp.clds.model.dcae.DcaeInventoryResponse;
42 import org.onap.clamp.clds.sdc.controller.installer.BlueprintArtifact;
43 import org.onap.clamp.clds.sdc.controller.installer.BlueprintParser;
44 import org.onap.clamp.clds.sdc.controller.installer.ChainGenerator;
45 import org.onap.clamp.clds.sdc.controller.installer.CsarHandler;
46 import org.onap.clamp.clds.sdc.controller.installer.CsarInstaller;
47 import org.onap.clamp.clds.sdc.controller.installer.MicroService;
48 import org.onap.clamp.clds.util.JsonUtils;
49 import org.onap.clamp.clds.util.drawing.SvgFacade;
50 import org.onap.clamp.policy.Policy;
51 import org.onap.clamp.policy.microservice.MicroServicePolicy;
52 import org.onap.clamp.policy.operational.OperationalPolicy;
53 import org.onap.sdc.tosca.parser.api.IEntityDetails;
54 import org.onap.sdc.tosca.parser.elements.queries.EntityQuery;
55 import org.onap.sdc.tosca.parser.elements.queries.TopologyTemplateQuery;
56 import org.onap.sdc.tosca.parser.enums.EntityTemplateType;
57 import org.onap.sdc.tosca.parser.enums.SdcTypes;
58 import org.onap.sdc.toscaparser.api.NodeTemplate;
59 import org.onap.sdc.toscaparser.api.Property;
60 import org.springframework.beans.factory.annotation.Autowired;
61 import org.springframework.beans.factory.annotation.Qualifier;
62 import org.springframework.stereotype.Component;
63 import org.springframework.transaction.annotation.Propagation;
64 import org.springframework.transaction.annotation.Transactional;
65 import org.yaml.snakeyaml.Yaml;
68 * This class will be instantiated by spring config, and used by Sdc Controller.
69 * There is no state kept by the bean. It's used to deploy the csar/notification
70 * received from SDC in DB.
73 @Qualifier("loopInstaller")
74 public class LoopCsarInstaller implements CsarInstaller {
76 private static final EELFLogger logger = EELFManager.getInstance().getLogger(LoopCsarInstaller.class);
77 public static final String CONTROL_NAME_PREFIX = "ClosedLoop-";
78 public static final String GET_INPUT_BLUEPRINT_PARAM = "get_input";
79 // This will be used later as the policy scope
80 public static final String MODEL_NAME_PREFIX = "Loop_";
83 LoopsRepository loopRepository;
86 BlueprintParser blueprintParser;
89 ChainGenerator chainGenerator;
92 DcaeInventoryServices dcaeInventoryService;
95 private SvgFacade svgFacade;
98 public boolean isCsarAlreadyDeployed(CsarHandler csar) throws SdcArtifactInstallerException {
99 boolean alreadyInstalled = true;
100 for (Entry<String, BlueprintArtifact> blueprint : csar.getMapOfBlueprints().entrySet()) {
101 alreadyInstalled = alreadyInstalled
102 && loopRepository.existsById(Loop.generateLoopName(csar.getSdcNotification().getServiceName(),
103 csar.getSdcNotification().getServiceVersion(),
104 blueprint.getValue().getResourceAttached().getResourceInstanceName(),
105 blueprint.getValue().getBlueprintArtifactName()));
107 return alreadyInstalled;
111 @Transactional(propagation = Propagation.REQUIRED)
112 public void installTheCsar(CsarHandler csar)
113 throws SdcArtifactInstallerException, InterruptedException, PolicyModelException {
115 logger.info("Installing the CSAR " + csar.getFilePath());
116 for (Entry<String, BlueprintArtifact> blueprint : csar.getMapOfBlueprints().entrySet()) {
117 logger.info("Processing blueprint " + blueprint.getValue().getBlueprintArtifactName());
118 loopRepository.save(createLoopFromBlueprint(csar, blueprint.getValue()));
120 logger.info("Successfully installed the CSAR " + csar.getFilePath());
121 } catch (IOException e) {
122 throw new SdcArtifactInstallerException("Exception caught during the Csar installation in database", e);
123 } catch (ParseException e) {
124 throw new SdcArtifactInstallerException("Exception caught during the Dcae query to get ServiceTypeId", e);
128 private Loop createLoopFromBlueprint(CsarHandler csar, BlueprintArtifact blueprintArtifact)
129 throws IOException, ParseException, InterruptedException {
130 Loop newLoop = new Loop();
131 newLoop.setBlueprint(blueprintArtifact.getDcaeBlueprint());
132 newLoop.setName(Loop.generateLoopName(csar.getSdcNotification().getServiceName(),
133 csar.getSdcNotification().getServiceVersion(),
134 blueprintArtifact.getResourceAttached().getResourceInstanceName(),
135 blueprintArtifact.getBlueprintArtifactName()));
136 newLoop.setLastComputedState(LoopState.DESIGN);
138 List<MicroService> microServicesChain = chainGenerator
139 .getChainOfMicroServices(blueprintParser.getMicroServices(blueprintArtifact.getDcaeBlueprint()));
140 if (microServicesChain.isEmpty()) {
141 microServicesChain = blueprintParser.fallbackToOneMicroService(blueprintArtifact.getDcaeBlueprint());
143 newLoop.setModelPropertiesJson(createModelPropertiesJson(csar));
144 newLoop.setMicroServicePolicies(
145 createMicroServicePolicies(microServicesChain, csar, blueprintArtifact, newLoop));
146 newLoop.setOperationalPolicies(createOperationalPolicies(csar, blueprintArtifact, newLoop));
148 newLoop.setSvgRepresentation(svgFacade.getSvgImage(microServicesChain));
149 newLoop.setGlobalPropertiesJson(createGlobalPropertiesJson(blueprintArtifact, newLoop));
151 DcaeInventoryResponse dcaeResponse = queryDcaeToGetServiceTypeId(blueprintArtifact);
152 newLoop.setDcaeBlueprintId(dcaeResponse.getTypeId());
156 private HashSet<OperationalPolicy> createOperationalPolicies(CsarHandler csar, BlueprintArtifact blueprintArtifact,
158 return new HashSet<>(Arrays.asList(new OperationalPolicy(Policy.generatePolicyName("OPERATIONAL",
159 csar.getSdcNotification().getServiceName(), csar.getSdcNotification().getServiceVersion(),
160 blueprintArtifact.getResourceAttached().getResourceInstanceName(),
161 blueprintArtifact.getBlueprintArtifactName()), newLoop, new JsonObject())));
164 private HashSet<MicroServicePolicy> createMicroServicePolicies(List<MicroService> microServicesChain,
165 CsarHandler csar, BlueprintArtifact blueprintArtifact, Loop newLoop) throws IOException {
166 HashSet<MicroServicePolicy> newSet = new HashSet<>();
168 for (MicroService microService : microServicesChain) {
169 MicroServicePolicy microServicePolicy = new MicroServicePolicy(
170 Policy.generatePolicyName(microService.getName(), csar.getSdcNotification().getServiceName(),
171 csar.getSdcNotification().getServiceVersion(),
172 blueprintArtifact.getResourceAttached().getResourceInstanceName(),
173 blueprintArtifact.getBlueprintArtifactName()),
174 microService.getModelType(), csar.getPolicyModelYaml().orElse(""), false,
175 new HashSet<>(Arrays.asList(newLoop)));
177 newSet.add(microServicePolicy);
178 microService.setMappedNameJpa(microServicePolicy.getName());
183 private JsonObject createGlobalPropertiesJson(BlueprintArtifact blueprintArtifact, Loop newLoop) {
184 JsonObject globalProperties = new JsonObject();
185 globalProperties.add("dcaeDeployParameters", getAllBlueprintParametersInJson(blueprintArtifact, newLoop));
186 return globalProperties;
189 private static JsonObject createVfModuleProperties(CsarHandler csar) {
190 JsonObject vfModuleProps = new JsonObject();
191 // Loop on all Groups defined in the service (VFModule entries type:
192 // org.openecomp.groups.VfModule)
193 for (IEntityDetails entity : csar.getSdcCsarHelper().getEntity(
194 EntityQuery.newBuilder(EntityTemplateType.GROUP).build(),
195 TopologyTemplateQuery.newBuilder(SdcTypes.SERVICE).build(), false)) {
196 // Get all metadata info
197 JsonObject allVfProps = (JsonObject) JsonUtils.GSON.toJsonTree(entity.getMetadata().getAllProperties());
198 vfModuleProps.add(entity.getMetadata().getAllProperties().get("vfModuleModelName"), allVfProps);
199 // now append the properties section so that we can also have isBase,
200 // volume_group, etc ... fields under the VFmodule name
201 for (Entry<String, Property> additionalProp : entity.getProperties().entrySet()) {
202 allVfProps.add(additionalProp.getValue().getName(),
203 JsonUtils.GSON.toJsonTree(additionalProp.getValue().getValue()));
206 return vfModuleProps;
209 private static JsonObject createServicePropertiesByType(CsarHandler csar) {
210 JsonObject resourcesProp = new JsonObject();
211 // Iterate on all types defined in the tosca lib
212 for (SdcTypes type : SdcTypes.values()) {
213 JsonObject resourcesPropByType = new JsonObject();
214 // For each type, get the metadata of each nodetemplate
215 for (NodeTemplate nodeTemplate : csar.getSdcCsarHelper().getServiceNodeTemplateBySdcType(type)) {
216 resourcesPropByType.add(nodeTemplate.getName(),
217 JsonUtils.GSON.toJsonTree(nodeTemplate.getMetaData().getAllProperties()));
219 resourcesProp.add(type.getValue(), resourcesPropByType);
221 return resourcesProp;
224 private static JsonObject createModelPropertiesJson(CsarHandler csar) {
225 JsonObject modelProperties = new JsonObject();
226 // Add service details
227 modelProperties.add("serviceDetails", JsonUtils.GSON.fromJson(
228 JsonUtils.GSON.toJson(csar.getSdcCsarHelper().getServiceMetadataAllProperties()), JsonObject.class));
229 // Add properties details for each type, VfModule, VF, VFC, ....
230 JsonObject resourcesProp = createServicePropertiesByType(csar);
231 resourcesProp.add("VFModule", createVfModuleProperties(csar));
232 modelProperties.add("resourceDetails", resourcesProp);
233 return modelProperties;
236 private JsonObject getAllBlueprintParametersInJson(BlueprintArtifact blueprintArtifact, Loop newLoop) {
237 JsonObject node = new JsonObject();
238 Yaml yaml = new Yaml();
239 Map<String, Object> inputsNodes = ((Map<String, Object>) ((Map<String, Object>) yaml
240 .load(blueprintArtifact.getDcaeBlueprint())).get("inputs"));
241 inputsNodes.entrySet().stream().filter(e -> !e.getKey().contains("policy_id")).forEach(elem -> {
242 Object defaultValue = ((Map<String, Object>) elem.getValue()).get("default");
243 if (defaultValue != null) {
244 addPropertyToNode(node, elem.getKey(), defaultValue);
246 node.addProperty(elem.getKey(), "");
249 // For Dublin only one micro service is expected
250 node.addProperty("policy_id", ((MicroServicePolicy) newLoop.getMicroServicePolicies().toArray()[0]).getName());
255 * ll get the latest version of the artifact (version can be specified to DCAE
258 * @return The DcaeInventoryResponse object containing the dcae values
260 private DcaeInventoryResponse queryDcaeToGetServiceTypeId(BlueprintArtifact blueprintArtifact)
261 throws IOException, ParseException, InterruptedException {
262 return dcaeInventoryService.getDcaeInformation(blueprintArtifact.getBlueprintArtifactName(),
263 blueprintArtifact.getBlueprintInvariantServiceUuid(),
264 blueprintArtifact.getResourceAttached().getResourceInvariantUUID());
267 private void addPropertyToNode(JsonObject node, String key, Object value) {
268 if (value instanceof String) {
269 node.addProperty(key, (String) value);
270 } else if (value instanceof Number) {
271 node.addProperty(key, (Number) value);
272 } else if (value instanceof Boolean) {
273 node.addProperty(key, (Boolean) value);
274 } else if (value instanceof Character) {
275 node.addProperty(key, (Character) value);
277 node.addProperty(key, JsonUtils.GSON.toJson(value));