382c1d7769785fc3ee0437c7ce5e2f1c4129f02f
[clamp.git] / src / main / java / org / onap / clamp / clds / sdc / controller / installer / CsarInstallerImpl.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP CLAMP
4  * ================================================================================
5  * Copyright (C) 2018 AT&T Intellectual Property. All rights
6  *                             reserved.
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
11  *
12  * http://www.apache.org/licenses/LICENSE-2.0
13  *
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  * ===================================================================
21  *
22  */
23
24 package org.onap.clamp.clds.sdc.controller.installer;
25
26 import com.att.eelf.configuration.EELFLogger;
27 import com.att.eelf.configuration.EELFManager;
28 import com.fasterxml.jackson.databind.node.ObjectNode;
29
30 import java.io.IOException;
31 import java.util.ArrayList;
32 import java.util.HashMap;
33 import java.util.List;
34 import java.util.Map;
35 import java.util.Map.Entry;
36
37 import javax.annotation.PostConstruct;
38 import javax.xml.transform.TransformerException;
39
40 import org.apache.commons.io.IOUtils;
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;
60
61 /**
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.
65  */
66 public class CsarInstallerImpl implements CsarInstaller {
67
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";
75     /**
76      * The file name that will be loaded by Spring.
77      */
78     @Value("${clamp.config.sdc.blueprint.parser.mapping:'classpath:/clds/blueprint-parser-mapping.json'}")
79     protected String blueprintMappingFile;
80     @Autowired
81     protected ApplicationContext appContext;
82     @Autowired
83     private CldsDao cldsDao;
84     @Autowired
85     CldsTemplateService cldsTemplateService;
86     @Autowired
87     CldsService cldsService;
88     @Autowired
89     DcaeInventoryServices dcaeInventoryService;
90     @Autowired
91     private XslTransformer cldsBpmnTransformer;
92
93     @PostConstruct
94     public void loadConfiguration() throws IOException {
95         BlueprintParserMappingConfiguration
96             .createFromJson(appContext.getResource(blueprintMappingFile).getInputStream()).stream()
97             .forEach(e -> bpmnMapping.put(e.getBlueprintKey(), e.getFiles()));
98     }
99
100     @Override
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
106                     : false;
107         }
108         return alreadyInstalled;
109     }
110
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("\\*", "");
117         } else {
118             // This is normally the get_input case
119             policyScopePrefix = MODEL_NAME_PREFIX;
120         }
121         return policyScopePrefix + csar.getSdcCsarHelper().getServiceMetadata().getValue("name") + "_v"
122             + csar.getSdcNotification().getServiceVersion().replace('.', '_') + "_"
123             + resourceInstanceName.replaceAll(" ", "");
124     }
125
126     @Override
127     @Transactional
128     public void installTheCsar(CsarHandler csar) throws SdcArtifactInstallerException, InterruptedException {
129         try {
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()));
137             }
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);
143         }
144     }
145
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());
155             }
156         });
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");
162         }
163         logger.info("Mapping found for blueprint " + blueprintArtifact.getBlueprintArtifactName() + " is "
164             + listConfig.get(0).getBpmnXmlFilePath());
165         return listConfig.get(0);
166     }
167
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);
179             } else {
180                 node.put(elem.getKey(), "");
181             }
182         });
183         node.put("policy_id", "AUTO_GENERATED_POLICY_ID_AT_SUBMIT");
184         return node.toString();
185     }
186
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);
199             } else {
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);
204                 }
205             }
206         });
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");
213         }
214         logger.info("policyName found in blueprint " + blueprintArtifact.getBlueprintArtifactName() + " is "
215             + policyNameList.get(0));
216         return policyNameList.get(0);
217     }
218
219     /**
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)
222      *
223      * @param blueprintArtifact
224      * @return The DcaeInventoryResponse object containing the dcae values
225      * @throws IOException
226      * @throws ParseException
227      * @throws InterruptedException
228      */
229     private DcaeInventoryResponse queryDcaeToGetServiceTypeId(BlueprintArtifact blueprintArtifact)
230         throws IOException, ParseException, InterruptedException {
231         return dcaeInventoryService.getDcaeInformation(blueprintArtifact.getBlueprintArtifactName(),
232             blueprintArtifact.getBlueprintInvariantServiceUuid(),
233             blueprintArtifact.getResourceAttached().getResourceInvariantUUID());
234     }
235
236     private CldsTemplate createFakeCldsTemplate(CsarHandler csar, BlueprintArtifact blueprintArtifact,
237         BlueprintParserFilesConfiguration configFiles) throws IOException, SdcArtifactInstallerException {
238         CldsTemplate template = new CldsTemplate();
239         template.setBpmnId("Sdc-Generated");
240         template
241             .setBpmnText(IOUtils.toString(appContext.getResource(configFiles.getBpmnXmlFilePath()).getInputStream()));
242         template.setPropText(
243             "{\"global\":[{\"name\":\"service\",\"value\":[\"" + blueprintArtifact.getDcaeBlueprint() + "\"]}]}");
244         template
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());
251         return template;
252     }
253
254     private CldsModel createFakeCldsModel(CsarHandler csar, BlueprintArtifact blueprintArtifact,
255         CldsTemplate cldsTemplate, DcaeInventoryResponse dcaeInventoryResponse) throws SdcArtifactInstallerException {
256         try {
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
270             // the policyId
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());
275             return cldsModel;
276         } catch (TransformerException e) {
277             throw new SdcArtifactInstallerException("TransformerException when decoding the BpmnText", e);
278         }
279     }
280
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);
294     }
295 }