2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2018 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.clds.sdc.controller.installer;
26 import com.att.aft.dme2.internal.apache.commons.io.IOUtils;
27 import com.att.eelf.configuration.EELFLogger;
28 import com.att.eelf.configuration.EELFManager;
29 import com.fasterxml.jackson.databind.node.ObjectNode;
31 import java.io.IOException;
32 import java.util.ArrayList;
33 import java.util.HashMap;
34 import java.util.List;
36 import java.util.Map.Entry;
38 import javax.annotation.PostConstruct;
39 import javax.xml.transform.TransformerException;
41 import org.json.simple.parser.ParseException;
42 import org.onap.clamp.clds.client.DcaeInventoryServices;
43 import org.onap.clamp.clds.config.sdc.BlueprintParserFilesConfiguration;
44 import org.onap.clamp.clds.config.sdc.BlueprintParserMappingConfiguration;
45 import org.onap.clamp.clds.dao.CldsDao;
46 import org.onap.clamp.clds.exception.sdc.controller.SdcArtifactInstallerException;
47 import org.onap.clamp.clds.model.CldsModel;
48 import org.onap.clamp.clds.model.CldsTemplate;
49 import org.onap.clamp.clds.model.dcae.DcaeInventoryResponse;
50 import org.onap.clamp.clds.model.properties.ModelProperties;
51 import org.onap.clamp.clds.service.CldsService;
52 import org.onap.clamp.clds.service.CldsTemplateService;
53 import org.onap.clamp.clds.transform.XslTransformer;
54 import org.onap.clamp.clds.util.JacksonUtils;
55 import org.springframework.beans.factory.annotation.Autowired;
56 import org.springframework.beans.factory.annotation.Value;
57 import org.springframework.context.ApplicationContext;
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 private Map<String, BlueprintParserFilesConfiguration> bpmnMapping = new HashMap<>();
70 public static final String TEMPLATE_NAME_PREFIX = "DCAE-Designer-Template-";
71 public static final String CONTROL_NAME_PREFIX = "ClosedLoop-";
72 public static final String GET_INPUT_BLUEPRINT_PARAM = "get_input";
73 // This will be used later as the policy scope
74 public static final String MODEL_NAME_PREFIX = "CLAMP";
76 * The file name that will be loaded by Spring.
78 @Value("${clamp.config.sdc.blueprint.parser.mapping:'classpath:/clds/blueprint-parser-mapping.json'}")
79 protected String blueprintMappingFile;
81 protected ApplicationContext appContext;
83 private CldsDao cldsDao;
85 CldsTemplateService cldsTemplateService;
87 CldsService cldsService;
89 DcaeInventoryServices dcaeInventoryService;
91 private XslTransformer cldsBpmnTransformer;
94 public void loadConfiguration() throws IOException {
95 BlueprintParserMappingConfiguration
96 .createFromJson(appContext.getResource(blueprintMappingFile).getInputStream()).stream()
97 .forEach(e -> bpmnMapping.put(e.getBlueprintKey(), e.getFiles()));
101 public boolean isCsarAlreadyDeployed(CsarHandler csar) throws SdcArtifactInstallerException {
102 boolean alreadyInstalled = true;
103 for (Entry<String, BlueprintArtifact> blueprint : csar.getMapOfBlueprints().entrySet()) {
104 alreadyInstalled = alreadyInstalled
105 && (CldsModel.retrieve(cldsDao, buildModelName(csar, blueprint.getKey()), true).getId() != null) ? true
108 return alreadyInstalled;
111 public static String buildModelName(CsarHandler csar, String resourceInstanceName)
112 throws SdcArtifactInstallerException {
113 String policyScopePrefix = searchForPolicyScopePrefix(csar.getMapOfBlueprints().get(resourceInstanceName));
114 if (policyScopePrefix.contains("*")) {
115 // This is policy_filter type
116 policyScopePrefix = policyScopePrefix.replaceAll("\\*", "");
118 // This is normally the get_input case
119 policyScopePrefix = MODEL_NAME_PREFIX;
121 return policyScopePrefix + csar.getSdcCsarHelper().getServiceMetadata().getValue("name") + "_v"
122 + csar.getSdcNotification().getServiceVersion().replace('.', '_') + "_"
123 + resourceInstanceName.replaceAll(" ", "");
128 public void installTheCsar(CsarHandler csar) throws SdcArtifactInstallerException, InterruptedException {
130 logger.info("Installing the CSAR " + csar.getFilePath());
131 for (Entry<String, BlueprintArtifact> blueprint : csar.getMapOfBlueprints().entrySet()) {
132 logger.info("Processing blueprint " + blueprint.getValue().getBlueprintArtifactName());
133 createFakeCldsModel(csar, blueprint.getValue(),
134 createFakeCldsTemplate(csar, blueprint.getValue(),
135 this.searchForRightMapping(blueprint.getValue())),
136 queryDcaeToGetServiceTypeId(blueprint.getValue()));
138 logger.info("Successfully installed the CSAR " + csar.getFilePath());
139 } catch (IOException e) {
140 throw new SdcArtifactInstallerException("Exception caught during the Csar installation in database", e);
141 } catch (ParseException e) {
142 throw new SdcArtifactInstallerException("Exception caught during the Dcae query to get ServiceTypeId", e);
146 private BlueprintParserFilesConfiguration searchForRightMapping(BlueprintArtifact blueprintArtifact)
147 throws SdcArtifactInstallerException {
148 List<BlueprintParserFilesConfiguration> listConfig = new ArrayList<>();
149 Yaml yaml = new Yaml();
150 Map<String, Object> templateNodes = ((Map<String, Object>) ((Map<String, Object>) yaml
151 .load(blueprintArtifact.getDcaeBlueprint())).get("node_templates"));
152 bpmnMapping.entrySet().forEach(e -> {
153 if (templateNodes.keySet().stream().anyMatch(t -> t.contains(e.getKey()))) {
154 listConfig.add(e.getValue());
157 if (listConfig.size() > 1) {
158 throw new SdcArtifactInstallerException(
159 "The code does not currently support multiple MicroServices in the blueprint");
160 } else if (listConfig.isEmpty()) {
161 throw new SdcArtifactInstallerException("There is no recognized MicroService found in the blueprint");
163 logger.info("Mapping found for blueprint " + blueprintArtifact.getBlueprintArtifactName() + " is "
164 + listConfig.get(0).getBpmnXmlFilePath());
165 return listConfig.get(0);
168 private static String getAllBlueprintParametersInJson(BlueprintArtifact blueprintArtifact) {
169 ObjectNode node = JacksonUtils.getObjectMapperInstance().createObjectNode();
170 Yaml yaml = new Yaml();
171 Map<String, Object> inputsNodes = ((Map<String, Object>) ((Map<String, Object>) yaml
172 .load(blueprintArtifact.getDcaeBlueprint())).get("inputs"));
173 inputsNodes.entrySet().stream().filter(e -> !e.getKey().contains("policy_id")).forEach(elem -> {
174 Object defaultNode = ((Map<String, Object>) elem.getValue()).get("default");
175 if (defaultNode != null && defaultNode instanceof String) {
176 node.put(elem.getKey(), (String) defaultNode);
177 } else if (defaultNode != null) {
178 node.putPOJO(elem.getKey(), defaultNode);
180 node.put(elem.getKey(), "");
183 node.put("policy_id", "AUTO_GENERATED_POLICY_ID_AT_SUBMIT");
184 return node.toString();
187 private static String searchForPolicyScopePrefix(BlueprintArtifact blueprintArtifact)
188 throws SdcArtifactInstallerException {
189 String policyName = null;
190 Yaml yaml = new Yaml();
191 List<String> policyNameList = new ArrayList<>();
192 Map<String, Object> templateNodes = ((Map<String, Object>) ((Map<String, Object>) yaml
193 .load(blueprintArtifact.getDcaeBlueprint())).get("node_templates"));
194 templateNodes.entrySet().stream().filter(e -> e.getKey().contains("policy")).forEach(ef -> {
195 String filteredPolicyName = (String) ((Map<String, Object>) ((Map<String, Object>) ef.getValue())
196 .get("properties")).get("policy_filter");
197 if (policyName != null) {
198 policyNameList.add(filteredPolicyName);
200 String inputPolicyName = (String) ((Map<String, Object>) ((Map<String, Object>) ((Map<String, Object>) ef
201 .getValue()).get("properties")).get("policy_id")).get(GET_INPUT_BLUEPRINT_PARAM);
202 if (inputPolicyName != null) {
203 policyNameList.add(GET_INPUT_BLUEPRINT_PARAM);
207 if (policyNameList.size() > 1) {
208 throw new SdcArtifactInstallerException(
209 "The code does not currently support multiple Policy MicroServices in the blueprint");
210 } else if (policyNameList.isEmpty()) {
211 throw new SdcArtifactInstallerException(
212 "There is no recognized Policy MicroService found in the blueprint");
214 logger.info("policyName found in blueprint " + blueprintArtifact.getBlueprintArtifactName() + " is "
215 + policyNameList.get(0));
216 return policyNameList.get(0);
220 * This call must be done when deploying the SDC notification as this call get
221 * the latest version of the artifact (version can be specified to DCAE call)
223 * @param blueprintArtifact
224 * @return The DcaeInventoryResponse object containing the dcae values
225 * @throws IOException
226 * @throws ParseException
227 * @throws InterruptedException
229 private DcaeInventoryResponse queryDcaeToGetServiceTypeId(BlueprintArtifact blueprintArtifact)
230 throws IOException, ParseException, InterruptedException {
231 return dcaeInventoryService.getDcaeInformation(blueprintArtifact.getBlueprintArtifactName(),
232 blueprintArtifact.getBlueprintInvariantServiceUuid(),
233 blueprintArtifact.getResourceAttached().getResourceInvariantUUID());
236 private CldsTemplate createFakeCldsTemplate(CsarHandler csar, BlueprintArtifact blueprintArtifact,
237 BlueprintParserFilesConfiguration configFiles) throws IOException, SdcArtifactInstallerException {
238 CldsTemplate template = new CldsTemplate();
239 template.setBpmnId("Sdc-Generated");
241 .setBpmnText(IOUtils.toString(appContext.getResource(configFiles.getBpmnXmlFilePath()).getInputStream()));
242 template.setPropText(
243 "{\"global\":[{\"name\":\"service\",\"value\":[\"" + blueprintArtifact.getDcaeBlueprint() + "\"]}]}");
245 .setImageText(IOUtils.toString(appContext.getResource(configFiles.getSvgXmlFilePath()).getInputStream()));
246 template.setName(TEMPLATE_NAME_PREFIX
247 + buildModelName(csar, blueprintArtifact.getResourceAttached().getResourceInstanceName()));
248 template.save(cldsDao, null);
249 logger.info("Fake Clds Template created for blueprint " + blueprintArtifact.getBlueprintArtifactName()
250 + " with name " + template.getName());
254 private CldsModel createFakeCldsModel(CsarHandler csar, BlueprintArtifact blueprintArtifact,
255 CldsTemplate cldsTemplate, DcaeInventoryResponse dcaeInventoryResponse) throws SdcArtifactInstallerException {
257 CldsModel cldsModel = new CldsModel();
258 cldsModel.setName(buildModelName(csar, blueprintArtifact.getResourceAttached().getResourceInstanceName()));
259 cldsModel.setBlueprintText(blueprintArtifact.getDcaeBlueprint());
260 cldsModel.setTemplateName(cldsTemplate.getName());
261 cldsModel.setTemplateId(cldsTemplate.getId());
262 cldsModel.setBpmnText(cldsTemplate.getBpmnText());
263 cldsModel.setTypeId(dcaeInventoryResponse.getTypeId());
264 cldsModel.setTypeName(dcaeInventoryResponse.getTypeName());
265 cldsModel.setControlNamePrefix(CONTROL_NAME_PREFIX);
266 // We must save it otherwise object won't be created in db
267 // and proptext will always be null
268 cldsModel.setPropText("{\"global\":[]}");
269 // Must save first to have the generated id available to generate
271 cldsModel = cldsModel.save(cldsDao, null);
272 cldsModel = setModelPropText(cldsModel, blueprintArtifact, cldsTemplate);
273 logger.info("Fake Clds Model created for blueprint " + blueprintArtifact.getBlueprintArtifactName()
274 + " with name " + cldsModel.getName());
276 } catch (TransformerException e) {
277 throw new SdcArtifactInstallerException("TransformerException when decoding the BpmnText", e);
281 private CldsModel setModelPropText(CldsModel cldsModel, BlueprintArtifact blueprintArtifact,
282 CldsTemplate cldsTemplate) throws TransformerException {
283 // Do a test to validate the BPMN
284 new ModelProperties(cldsModel.getName(), cldsModel.getControlName(), "PUT", false,
285 cldsBpmnTransformer.doXslTransformToString(cldsTemplate.getBpmnText()), "{}");
286 String inputParams = "{\"name\":\"deployParameters\",\"value\":"
287 + getAllBlueprintParametersInJson(blueprintArtifact) + "}";
288 cldsModel.setPropText("{\"global\":[{\"name\":\"service\",\"value\":[\""
289 + blueprintArtifact.getBlueprintInvariantServiceUuid() + "\"]},{\"name\":\"vf\",\"value\":[\""
290 + blueprintArtifact.getResourceAttached().getResourceInvariantUUID()
291 + "\"]},{\"name\":\"actionSet\",\"value\":[\"vnfRecipe\"]},{\"name\":\"location\",\"value\":[\"DC1\"]},"
292 + inputParams + "]}");
293 return cldsModel.save(cldsDao, null);