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;
30 import java.io.IOException;
31 import java.util.ArrayList;
32 import java.util.HashMap;
33 import java.util.List;
35 import java.util.Map.Entry;
37 import javax.annotation.PostConstruct;
38 import javax.xml.transform.TransformerException;
40 import org.json.simple.parser.ParseException;
41 import org.onap.clamp.clds.client.DcaeInventoryServices;
42 import org.onap.clamp.clds.config.sdc.BlueprintParserFilesConfiguration;
43 import org.onap.clamp.clds.config.sdc.BlueprintParserMappingConfiguration;
44 import org.onap.clamp.clds.dao.CldsDao;
45 import org.onap.clamp.clds.exception.sdc.controller.SdcArtifactInstallerException;
46 import org.onap.clamp.clds.model.CldsModel;
47 import org.onap.clamp.clds.model.CldsTemplate;
48 import org.onap.clamp.clds.model.dcae.DcaeInventoryResponse;
49 import org.onap.clamp.clds.model.properties.ModelProperties;
50 import org.onap.clamp.clds.service.CldsService;
51 import org.onap.clamp.clds.service.CldsTemplateService;
52 import org.onap.clamp.clds.transform.XslTransformer;
53 import org.springframework.beans.factory.annotation.Autowired;
54 import org.springframework.beans.factory.annotation.Value;
55 import org.springframework.context.ApplicationContext;
56 import org.springframework.transaction.annotation.Transactional;
57 import org.yaml.snakeyaml.Yaml;
60 * This class will be instantiated by spring config, and used by Sdc Controller.
61 * There is no state kept by the bean. It's used to deploy the csar/notification
62 * received from SDC in DB.
64 public class CsarInstallerImpl implements CsarInstaller {
66 private static final EELFLogger logger = EELFManager.getInstance().getLogger(CsarInstallerImpl.class);
67 private Map<String, BlueprintParserFilesConfiguration> bpmnMapping = new HashMap<>();
68 public static final String TEMPLATE_NAME_PREFIX = "DCAE-Designer-Template-";
69 public static final String CONTROL_NAME_PREFIX = "ClosedLoop-";
70 public static final String GET_INPUT_BLUEPRINT_PARAM = "get_input";
71 // This will be used later as the policy scope
72 public static final String MODEL_NAME_PREFIX = "CLAMP";
74 * The file name that will be loaded by Spring.
76 @Value("${clamp.config.sdc.blueprint.parser.mapping:'classpath:/clds/blueprint-parser-mapping.json'}")
77 protected String blueprintMappingFile;
79 protected ApplicationContext appContext;
81 private CldsDao cldsDao;
83 CldsTemplateService cldsTemplateService;
85 CldsService cldsService;
87 DcaeInventoryServices dcaeInventoryService;
89 private XslTransformer cldsBpmnTransformer;
92 public void loadConfiguration() throws IOException {
93 BlueprintParserMappingConfiguration
94 .createFromJson(appContext.getResource(blueprintMappingFile).getInputStream()).stream()
95 .forEach(e -> bpmnMapping.put(e.getBlueprintKey(), e.getFiles()));
99 public boolean isCsarAlreadyDeployed(CsarHandler csar) throws SdcArtifactInstallerException {
100 boolean alreadyInstalled = true;
101 for (Entry<String, BlueprintArtifact> blueprint : csar.getMapOfBlueprints().entrySet()) {
102 alreadyInstalled = alreadyInstalled
103 && (CldsModel.retrieve(cldsDao, buildModelName(csar, blueprint.getKey()), true).getId() != null)
107 return alreadyInstalled;
110 public static String buildModelName(CsarHandler csar, String resourceInstanceName)
111 throws SdcArtifactInstallerException {
112 String policyScopePrefix = searchForPolicyScopePrefix(csar.getMapOfBlueprints().get(resourceInstanceName));
113 if (policyScopePrefix.contains("*")) {
114 // This is policy_filter type
115 policyScopePrefix = policyScopePrefix.replaceAll("\\*", "");
117 // This is normally the get_input case
118 policyScopePrefix = MODEL_NAME_PREFIX;
120 return policyScopePrefix + csar.getSdcCsarHelper().getServiceMetadata().getValue("name") + "_v"
121 + csar.getSdcNotification().getServiceVersion().replace('.', '_') + "_"
122 + resourceInstanceName.replaceAll(" ", "");
127 public void installTheCsar(CsarHandler csar) throws SdcArtifactInstallerException {
129 logger.info("Installing the CSAR " + csar.getFilePath());
130 for (Entry<String, BlueprintArtifact> blueprint : csar.getMapOfBlueprints().entrySet()) {
131 logger.info("Processing blueprint " + blueprint.getValue().getBlueprintArtifactName());
132 createFakeCldsModel(csar, blueprint.getValue(),
133 createFakeCldsTemplate(csar, blueprint.getValue(),
134 this.searchForRightMapping(blueprint.getValue())),
135 queryDcaeToGetServiceTypeId(blueprint.getValue()));
137 logger.info("Successfully installed the CSAR " + csar.getFilePath());
138 } catch (IOException e) {
139 throw new SdcArtifactInstallerException("Exception caught during the Csar installation in database", e);
140 } catch (ParseException | InterruptedException e) {
141 throw new SdcArtifactInstallerException("Exception caught during the Dcae query to get ServiceTypeId", e);
145 private BlueprintParserFilesConfiguration searchForRightMapping(BlueprintArtifact blueprintArtifact)
146 throws SdcArtifactInstallerException {
147 List<BlueprintParserFilesConfiguration> listConfig = new ArrayList<>();
148 Yaml yaml = new Yaml();
149 Map<String, Object> templateNodes = ((Map<String, Object>) ((Map<String, Object>) yaml
150 .load(blueprintArtifact.getDcaeBlueprint())).get("node_templates"));
151 bpmnMapping.entrySet().forEach(e -> {
152 if (templateNodes.keySet().stream().anyMatch(t -> t.contains(e.getKey()))) {
153 listConfig.add(e.getValue());
156 if (listConfig.size() > 1) {
157 throw new SdcArtifactInstallerException(
158 "The code does not currently support multiple MicroServices in the blueprint");
159 } else if (listConfig.isEmpty()) {
160 throw new SdcArtifactInstallerException("There is no recognized MicroService found in the blueprint");
162 logger.info("Mapping found for blueprint " + blueprintArtifact.getBlueprintArtifactName() + " is "
163 + listConfig.get(0).getBpmnXmlFilePath());
164 return listConfig.get(0);
167 private static String searchForPolicyScopePrefix(BlueprintArtifact blueprintArtifact)
168 throws SdcArtifactInstallerException {
169 String policyName = null;
170 Yaml yaml = new Yaml();
171 List<String> policyNameList = new ArrayList<>();
172 Map<String, Object> templateNodes = ((Map<String, Object>) ((Map<String, Object>) yaml
173 .load(blueprintArtifact.getDcaeBlueprint())).get("node_templates"));
174 templateNodes.entrySet().stream().filter(e -> e.getKey().contains("policy")).forEach(ef -> {
175 String filteredPolicyName = (String) ((Map<String, Object>) ((Map<String, Object>) ef.getValue())
176 .get("properties")).get("policy_filter");
177 if (policyName != null) {
178 policyNameList.add(filteredPolicyName);
180 String inputPolicyName = (String) ((Map<String, Object>) ((Map<String, Object>) ((Map<String, Object>) ef
181 .getValue()).get("properties")).get("policy_id")).get(GET_INPUT_BLUEPRINT_PARAM);
182 if (inputPolicyName != null) {
183 policyNameList.add(GET_INPUT_BLUEPRINT_PARAM);
187 if (policyNameList.size() > 1) {
188 throw new SdcArtifactInstallerException(
189 "The code does not currently support multiple Policy MicroServices in the blueprint");
190 } else if (policyNameList.isEmpty()) {
191 throw new SdcArtifactInstallerException(
192 "There is no recognized Policy MicroService found in the blueprint");
194 logger.info("policyName found in blueprint " + blueprintArtifact.getBlueprintArtifactName() + " is "
195 + policyNameList.get(0));
196 return policyNameList.get(0);
200 * This call must be done when deploying the SDC notification as this call
201 * get the latest version of the artifact (version can be specified to DCAE
204 * @param blueprintArtifact
205 * @return The DcaeInventoryResponse object containing the dcae values
206 * @throws IOException
207 * @throws ParseException
208 * @throws InterruptedException
210 private DcaeInventoryResponse queryDcaeToGetServiceTypeId(BlueprintArtifact blueprintArtifact)
211 throws IOException, ParseException, InterruptedException {
212 return dcaeInventoryService.getDcaeInformation(blueprintArtifact.getBlueprintArtifactName(),
213 blueprintArtifact.getBlueprintInvariantServiceUuid(),
214 blueprintArtifact.getResourceAttached().getResourceInvariantUUID());
217 private CldsTemplate createFakeCldsTemplate(CsarHandler csar, BlueprintArtifact blueprintArtifact,
218 BlueprintParserFilesConfiguration configFiles) throws IOException, SdcArtifactInstallerException {
219 CldsTemplate template = new CldsTemplate();
220 template.setBpmnId("Sdc-Generated");
221 template.setBpmnText(
222 IOUtils.toString(appContext.getResource(configFiles.getBpmnXmlFilePath()).getInputStream()));
223 template.setPropText(
224 "{\"global\":[{\"name\":\"service\",\"value\":[\"" + blueprintArtifact.getDcaeBlueprint() + "\"]}]}");
225 template.setImageText(
226 IOUtils.toString(appContext.getResource(configFiles.getSvgXmlFilePath()).getInputStream()));
227 template.setName(TEMPLATE_NAME_PREFIX
228 + buildModelName(csar, blueprintArtifact.getResourceAttached().getResourceInstanceName()));
229 template.save(cldsDao, null);
230 logger.info("Fake Clds Template created for blueprint " + blueprintArtifact.getBlueprintArtifactName()
231 + " with name " + template.getName());
235 private CldsModel createFakeCldsModel(CsarHandler csar, BlueprintArtifact blueprintArtifact,
236 CldsTemplate cldsTemplate, DcaeInventoryResponse dcaeInventoryResponse)
237 throws SdcArtifactInstallerException {
239 CldsModel cldsModel = new CldsModel();
240 cldsModel.setName(buildModelName(csar, blueprintArtifact.getResourceAttached().getResourceInstanceName()));
241 cldsModel.setBlueprintText(blueprintArtifact.getDcaeBlueprint());
242 cldsModel.setTemplateName(cldsTemplate.getName());
243 cldsModel.setTemplateId(cldsTemplate.getId());
244 cldsModel.setBpmnText(cldsTemplate.getBpmnText());
245 cldsModel.setTypeId(dcaeInventoryResponse.getTypeId());
246 cldsModel.setTypeName(dcaeInventoryResponse.getTypeName());
247 cldsModel.setControlNamePrefix(CONTROL_NAME_PREFIX);
248 // We must save it otherwise object won't be created in db
249 // and proptext will always be null
250 cldsModel.setPropText("{\"global\":[]}");
251 // Must save first to have the generated id available to generate
253 cldsModel = cldsModel.save(cldsDao, null);
254 cldsModel = setModelPropText(cldsModel, blueprintArtifact, cldsTemplate);
255 logger.info("Fake Clds Model created for blueprint " + blueprintArtifact.getBlueprintArtifactName()
256 + " with name " + cldsModel.getName());
258 } catch (TransformerException e) {
259 throw new SdcArtifactInstallerException("TransformerException when decoding the BpmnText", e);
263 private CldsModel setModelPropText(CldsModel cldsModel, BlueprintArtifact blueprintArtifact,
264 CldsTemplate cldsTemplate) throws TransformerException {
265 // Do a test to validate the BPMN
266 new ModelProperties(cldsModel.getName(), cldsModel.getControlName(), "PUT", false,
267 cldsBpmnTransformer.doXslTransformToString(cldsTemplate.getBpmnText()), "{}");
268 String inputParams = "{\"name\":\"deployParameters\",\"value\":{\n" + "\"policy_id\": \""
269 + "AUTO_GENERATED_POLICY_ID_AT_SUBMIT" + "\"" + "}}";
270 cldsModel.setPropText("{\"global\":[{\"name\":\"service\",\"value\":[\""
271 + blueprintArtifact.getBlueprintInvariantServiceUuid() + "\"]},{\"name\":\"vf\",\"value\":[\""
272 + blueprintArtifact.getResourceAttached().getResourceInvariantUUID()
273 + "\"]},{\"name\":\"actionSet\",\"value\":[\"vnfRecipe\"]},{\"name\":\"location\",\"value\":[\"DC1\"]},"
274 + inputParams + "]}");
275 return cldsModel.save(cldsDao, null);