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.sdc.controller.SdcArtifactInstallerException;
40 import org.onap.clamp.clds.model.dcae.DcaeInventoryResponse;
41 import org.onap.clamp.clds.sdc.controller.installer.BlueprintArtifact;
42 import org.onap.clamp.clds.sdc.controller.installer.BlueprintParser;
43 import org.onap.clamp.clds.sdc.controller.installer.ChainGenerator;
44 import org.onap.clamp.clds.sdc.controller.installer.CsarHandler;
45 import org.onap.clamp.clds.sdc.controller.installer.CsarInstaller;
46 import org.onap.clamp.clds.sdc.controller.installer.MicroService;
47 import org.onap.clamp.clds.util.JsonUtils;
48 import org.onap.clamp.clds.util.drawing.SvgFacade;
49 import org.onap.clamp.loop.service.Service;
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) throws SdcArtifactInstallerException, InterruptedException {
114 logger.info("Installing the CSAR " + csar.getFilePath());
115 for (Entry<String, BlueprintArtifact> blueprint : csar.getMapOfBlueprints().entrySet()) {
116 logger.info("Processing blueprint " + blueprint.getValue().getBlueprintArtifactName());
117 loopRepository.save(createLoopFromBlueprint(csar, blueprint.getValue()));
119 logger.info("Successfully installed the CSAR " + csar.getFilePath());
120 } catch (IOException e) {
121 throw new SdcArtifactInstallerException("Exception caught during the Csar installation in database", e);
122 } catch (ParseException e) {
123 throw new SdcArtifactInstallerException("Exception caught during the Dcae query to get ServiceTypeId", e);
127 private Loop createLoopFromBlueprint(CsarHandler csar, BlueprintArtifact blueprintArtifact)
128 throws IOException, ParseException, InterruptedException {
129 Loop newLoop = new Loop();
130 newLoop.setBlueprint(blueprintArtifact.getDcaeBlueprint());
131 newLoop.setName(Loop.generateLoopName(csar.getSdcNotification().getServiceName(),
132 csar.getSdcNotification().getServiceVersion(),
133 blueprintArtifact.getResourceAttached().getResourceInstanceName(),
134 blueprintArtifact.getBlueprintArtifactName()));
135 newLoop.setLastComputedState(LoopState.DESIGN);
137 List<MicroService> microServicesChain = chainGenerator
138 .getChainOfMicroServices(blueprintParser.getMicroServices(blueprintArtifact.getDcaeBlueprint()));
139 if (microServicesChain.isEmpty()) {
140 microServicesChain = blueprintParser.fallbackToOneMicroService(blueprintArtifact.getDcaeBlueprint());
142 newLoop.setModelService(createServiceModel(csar));
143 newLoop.setMicroServicePolicies(
144 createMicroServicePolicies(microServicesChain, csar, blueprintArtifact, newLoop));
145 newLoop.setOperationalPolicies(createOperationalPolicies(csar, blueprintArtifact, newLoop));
147 newLoop.setSvgRepresentation(svgFacade.getSvgImage(microServicesChain));
148 newLoop.setGlobalPropertiesJson(createGlobalPropertiesJson(blueprintArtifact, newLoop));
150 DcaeInventoryResponse dcaeResponse = queryDcaeToGetServiceTypeId(blueprintArtifact);
151 newLoop.setDcaeBlueprintId(dcaeResponse.getTypeId());
155 private HashSet<OperationalPolicy> createOperationalPolicies(CsarHandler csar, BlueprintArtifact blueprintArtifact,
157 return new HashSet<>(Arrays.asList(new OperationalPolicy(Policy.generatePolicyName("OPERATIONAL",
158 csar.getSdcNotification().getServiceName(), csar.getSdcNotification().getServiceVersion(),
159 blueprintArtifact.getResourceAttached().getResourceInstanceName(),
160 blueprintArtifact.getBlueprintArtifactName()), newLoop, new JsonObject())));
163 private HashSet<MicroServicePolicy> createMicroServicePolicies(List<MicroService> microServicesChain,
164 CsarHandler csar, BlueprintArtifact blueprintArtifact, Loop newLoop) throws IOException {
165 HashSet<MicroServicePolicy> newSet = new HashSet<>();
167 for (MicroService microService : microServicesChain) {
168 MicroServicePolicy microServicePolicy = new MicroServicePolicy(
169 Policy.generatePolicyName(microService.getName(), csar.getSdcNotification().getServiceName(),
170 csar.getSdcNotification().getServiceVersion(),
171 blueprintArtifact.getResourceAttached().getResourceInstanceName(),
172 blueprintArtifact.getBlueprintArtifactName()),
173 microService.getModelType(), csar.getPolicyModelYaml().orElse(""), false,
174 new HashSet<>(Arrays.asList(newLoop)));
176 newSet.add(microServicePolicy);
177 microService.setMappedNameJpa(microServicePolicy.getName());
182 private JsonObject createGlobalPropertiesJson(BlueprintArtifact blueprintArtifact, Loop newLoop) {
183 JsonObject globalProperties = new JsonObject();
184 globalProperties.add("dcaeDeployParameters", getAllBlueprintParametersInJson(blueprintArtifact, newLoop));
185 return globalProperties;
188 private static JsonObject createVfModuleProperties(CsarHandler csar) {
189 JsonObject vfModuleProps = new JsonObject();
190 // Loop on all Groups defined in the service (VFModule entries type:
191 // org.openecomp.groups.VfModule)
192 for (IEntityDetails entity : csar.getSdcCsarHelper().getEntity(
193 EntityQuery.newBuilder(EntityTemplateType.GROUP).build(),
194 TopologyTemplateQuery.newBuilder(SdcTypes.SERVICE).build(), false)) {
195 // Get all metadata info
196 JsonObject allVfProps = (JsonObject) JsonUtils.GSON.toJsonTree(entity.getMetadata().getAllProperties());
197 vfModuleProps.add(entity.getMetadata().getAllProperties().get("vfModuleModelName"), allVfProps);
198 // now append the properties section so that we can also have isBase,
199 // volume_group, etc ... fields under the VFmodule name
200 for (Entry<String, Property> additionalProp : entity.getProperties().entrySet()) {
201 allVfProps.add(additionalProp.getValue().getName(),
202 JsonUtils.GSON.toJsonTree(additionalProp.getValue().getValue()));
205 return vfModuleProps;
208 private static JsonObject createServicePropertiesByType(CsarHandler csar) {
209 JsonObject resourcesProp = new JsonObject();
210 // Iterate on all types defined in the tosca lib
211 for (SdcTypes type : SdcTypes.values()) {
212 JsonObject resourcesPropByType = new JsonObject();
213 // For each type, get the metadata of each nodetemplate
214 for (NodeTemplate nodeTemplate : csar.getSdcCsarHelper().getServiceNodeTemplateBySdcType(type)) {
215 resourcesPropByType.add(nodeTemplate.getName(),
216 JsonUtils.GSON.toJsonTree(nodeTemplate.getMetaData().getAllProperties()));
218 resourcesProp.add(type.getValue(), resourcesPropByType);
220 return resourcesProp;
223 private Service createServiceModel(CsarHandler csar) {
224 JsonObject serviceDetails = JsonUtils.GSON.fromJson(
225 JsonUtils.GSON.toJson(csar.getSdcCsarHelper().getServiceMetadataAllProperties()), JsonObject.class);
227 // Add properties details for each type, VfModule, VF, VFC, ....
228 JsonObject resourcesProp = createServicePropertiesByType(csar);
229 resourcesProp.add("VFModule", createVfModuleProperties(csar));
231 Service modelService = new Service(serviceDetails, resourcesProp);
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));