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.Gson;
29 import com.google.gson.JsonObject;
31 import java.io.IOException;
32 import java.util.Arrays;
33 import java.util.HashSet;
34 import java.util.List;
36 import java.util.Map.Entry;
38 import org.json.simple.parser.ParseException;
39 import org.onap.clamp.clds.client.DcaeInventoryServices;
40 import org.onap.clamp.clds.exception.policy.PolicyModelException;
41 import org.onap.clamp.clds.exception.sdc.controller.SdcArtifactInstallerException;
42 import org.onap.clamp.clds.model.dcae.DcaeInventoryResponse;
43 import org.onap.clamp.clds.sdc.controller.installer.BlueprintArtifact;
44 import org.onap.clamp.clds.sdc.controller.installer.BlueprintParser;
45 import org.onap.clamp.clds.sdc.controller.installer.ChainGenerator;
46 import org.onap.clamp.clds.sdc.controller.installer.CsarHandler;
47 import org.onap.clamp.clds.sdc.controller.installer.CsarInstaller;
48 import org.onap.clamp.clds.sdc.controller.installer.MicroService;
49 import org.onap.clamp.clds.util.JsonUtils;
50 import org.onap.clamp.clds.util.drawing.SvgFacade;
51 import org.onap.clamp.policy.Policy;
52 import org.onap.clamp.policy.microservice.MicroServicePolicy;
53 import org.onap.clamp.policy.operational.OperationalPolicy;
54 import org.onap.sdc.tosca.parser.enums.SdcTypes;
55 import org.onap.sdc.toscaparser.api.NodeTemplate;
56 import org.springframework.beans.factory.annotation.Autowired;
57 import org.springframework.transaction.annotation.Propagation;
58 import org.springframework.transaction.annotation.Transactional;
59 import org.yaml.snakeyaml.Yaml;
62 * This class will be instantiated by spring config, and used by Sdc Controller.
63 * There is no state kept by the bean. It's used to deploy the csar/notification
64 * received from SDC in DB.
66 public class CsarInstallerImpl implements CsarInstaller {
68 private static final EELFLogger logger = EELFManager.getInstance().getLogger(CsarInstallerImpl.class);
69 public static final String TEMPLATE_NAME_PREFIX = "DCAE-Designer-Template-";
70 public static final String CONTROL_NAME_PREFIX = "ClosedLoop-";
71 public static final String GET_INPUT_BLUEPRINT_PARAM = "get_input";
72 // This will be used later as the policy scope
73 public static final String MODEL_NAME_PREFIX = "Loop_";
76 LoopsRepository loopRepository;
79 BlueprintParser blueprintParser;
82 ChainGenerator chainGenerator;
85 DcaeInventoryServices dcaeInventoryService;
88 private SvgFacade svgFacade;
91 public boolean isCsarAlreadyDeployed(CsarHandler csar) throws SdcArtifactInstallerException {
92 boolean alreadyInstalled = true;
93 for (Entry<String, BlueprintArtifact> blueprint : csar.getMapOfBlueprints().entrySet()) {
94 alreadyInstalled = alreadyInstalled
95 && loopRepository.existsById(Loop.generateLoopName(csar.getSdcNotification().getServiceName(),
96 csar.getSdcNotification().getServiceVersion(),
97 blueprint.getValue().getResourceAttached().getResourceInstanceName(),
98 blueprint.getValue().getBlueprintArtifactName()));
100 return alreadyInstalled;
104 @Transactional(propagation = Propagation.REQUIRED)
105 public void installTheCsar(CsarHandler csar)
106 throws SdcArtifactInstallerException, InterruptedException, PolicyModelException {
108 logger.info("Installing the CSAR " + csar.getFilePath());
109 for (Entry<String, BlueprintArtifact> blueprint : csar.getMapOfBlueprints().entrySet()) {
110 logger.info("Processing blueprint " + blueprint.getValue().getBlueprintArtifactName());
111 loopRepository.save(createLoopFromBlueprint(csar, blueprint.getValue()));
113 logger.info("Successfully installed the CSAR " + csar.getFilePath());
114 } catch (IOException e) {
115 throw new SdcArtifactInstallerException("Exception caught during the Csar installation in database", e);
116 } catch (ParseException e) {
117 throw new SdcArtifactInstallerException("Exception caught during the Dcae query to get ServiceTypeId", e);
121 private String getSvgInLoop(BlueprintArtifact blueprintArtifact) {
122 List<MicroService> microServicesChain = chainGenerator
123 .getChainOfMicroServices(blueprintParser.getMicroServices(blueprintArtifact.getDcaeBlueprint()));
124 if (microServicesChain.isEmpty()) {
125 microServicesChain = blueprintParser.fallbackToOneMicroService(blueprintArtifact.getDcaeBlueprint());
127 return svgFacade.getSvgImage(microServicesChain);
131 private Loop createLoopFromBlueprint(CsarHandler csar, BlueprintArtifact blueprintArtifact)
132 throws IOException, ParseException, InterruptedException {
133 Loop newLoop = new Loop();
134 newLoop.setBlueprint(blueprintArtifact.getDcaeBlueprint());
135 newLoop.setName(Loop.generateLoopName(csar.getSdcNotification().getServiceName(),
136 csar.getSdcNotification().getServiceVersion(),
137 blueprintArtifact.getResourceAttached().getResourceInstanceName(),
138 blueprintArtifact.getBlueprintArtifactName()));
139 newLoop.setLastComputedState(LoopState.DESIGN);
140 newLoop.setMicroServicePolicies(createMicroServicePolicies(csar, blueprintArtifact, newLoop));
141 newLoop.setOperationalPolicies(createOperationalPolicies(csar, blueprintArtifact, newLoop));
143 newLoop.setSvgRepresentation(getSvgInLoop(blueprintArtifact));
144 newLoop.setGlobalPropertiesJson(createGlobalPropertiesJson(blueprintArtifact));
145 newLoop.setModelPropertiesJson(createModelPropertiesJson(csar));
146 DcaeInventoryResponse dcaeResponse = queryDcaeToGetServiceTypeId(blueprintArtifact);
147 newLoop.setDcaeBlueprintId(dcaeResponse.getTypeId());
151 private HashSet<OperationalPolicy> createOperationalPolicies(CsarHandler csar, BlueprintArtifact blueprintArtifact,
153 return new HashSet<>(Arrays.asList(new OperationalPolicy(Policy.generatePolicyName("OPERATIONAL",
154 csar.getSdcNotification().getServiceName(), csar.getSdcNotification().getServiceVersion(),
155 blueprintArtifact.getResourceAttached().getResourceInstanceName(),
156 blueprintArtifact.getBlueprintArtifactName()), newLoop, new JsonObject())));
159 private HashSet<MicroServicePolicy> createMicroServicePolicies(CsarHandler csar,
160 BlueprintArtifact blueprintArtifact, Loop newLoop) throws IOException {
161 HashSet<MicroServicePolicy> newSet = new HashSet<>();
162 List<MicroService> microServicesChain = chainGenerator
163 .getChainOfMicroServices(blueprintParser.getMicroServices(blueprintArtifact.getDcaeBlueprint()));
164 if (microServicesChain.isEmpty()) {
165 microServicesChain = blueprintParser.fallbackToOneMicroService(blueprintArtifact.getDcaeBlueprint());
167 for (MicroService microService : microServicesChain) {
168 newSet.add(new MicroServicePolicy(
169 Policy.generatePolicyName(microService.getName(), csar.getSdcNotification().getServiceName(),
170 csar.getSdcNotification().getServiceVersion(),
171 blueprintArtifact.getResourceAttached().getResourceInstanceName(),
172 blueprintArtifact.getBlueprintArtifactName()),
173 csar.getPolicyModelYaml().orElse(""), false, new HashSet<>(Arrays.asList(newLoop))));
178 private JsonObject createGlobalPropertiesJson(BlueprintArtifact blueprintArtifact) {
179 JsonObject globalProperties = new JsonObject();
180 globalProperties.add("dcaeDeployParameters", getAllBlueprintParametersInJson(blueprintArtifact));
181 return globalProperties;
185 private JsonObject createModelPropertiesJson(CsarHandler csar) {
186 JsonObject modelProperties = new JsonObject();
187 Gson gson = new Gson();
188 modelProperties.add("serviceDetails",
189 gson.fromJson(gson.toJson(csar.getSdcCsarHelper().getServiceMetadataAllProperties()), JsonObject.class));
191 JsonObject resourcesProp = new JsonObject();
192 for (SdcTypes type : SdcTypes.values()) {
193 JsonObject resourcesPropByType = new JsonObject();
194 for (NodeTemplate nodeTemplate : csar.getSdcCsarHelper().getServiceNodeTemplateBySdcType(type)) {
195 resourcesPropByType.add(nodeTemplate.getName(), JsonUtils.GSON_JPA_MODEL
196 .fromJson(new Gson().toJson(nodeTemplate.getMetaData().getAllProperties()), JsonObject.class));
198 resourcesProp.add(type.getValue(), resourcesPropByType);
200 modelProperties.add("resourceDetails", resourcesProp);
201 return modelProperties;
204 private JsonObject getAllBlueprintParametersInJson(BlueprintArtifact blueprintArtifact) {
205 JsonObject node = new JsonObject();
206 Yaml yaml = new Yaml();
207 Map<String, Object> inputsNodes = ((Map<String, Object>) ((Map<String, Object>) yaml
208 .load(blueprintArtifact.getDcaeBlueprint())).get("inputs"));
209 inputsNodes.entrySet().stream().filter(e -> !e.getKey().contains("policy_id")).forEach(elem -> {
210 Object defaultValue = ((Map<String, Object>) elem.getValue()).get("default");
211 if (defaultValue != null) {
212 addPropertyToNode(node, elem.getKey(), defaultValue);
214 node.addProperty(elem.getKey(), "");
217 node.addProperty("policy_id", "AUTO_GENERATED_POLICY_ID_AT_SUBMIT");
222 * ll get the latest version of the artifact (version can be specified to DCAE
225 * @return The DcaeInventoryResponse object containing the dcae values
227 private DcaeInventoryResponse queryDcaeToGetServiceTypeId(BlueprintArtifact blueprintArtifact)
228 throws IOException, ParseException, InterruptedException {
229 return dcaeInventoryService.getDcaeInformation(blueprintArtifact.getBlueprintArtifactName(),
230 blueprintArtifact.getBlueprintInvariantServiceUuid(),
231 blueprintArtifact.getResourceAttached().getResourceInvariantUUID());
234 private void addPropertyToNode(JsonObject node, String key, Object value) {
235 if (value instanceof String) {
236 node.addProperty(key, (String) value);
237 } else if (value instanceof Number) {
238 node.addProperty(key, (Number) value);
239 } else if (value instanceof Boolean) {
240 node.addProperty(key, (Boolean) value);
241 } else if (value instanceof Character) {
242 node.addProperty(key, (Character) value);
244 node.addProperty(key, JsonUtils.GSON.toJson(value));