Remove SDC query
[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
29 import com.google.gson.JsonObject;
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.JsonUtils;
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. There is no state kept by the bean.
63  * It's used to deploy the csar/notification received from SDC in DB.
64  */
65 public class CsarInstallerImpl implements CsarInstaller {
66
67     private static final EELFLogger logger = EELFManager.getInstance().getLogger(CsarInstallerImpl.class);
68     private Map<String, BlueprintParserFilesConfiguration> bpmnMapping = new HashMap<>();
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 = "CLAMP";
74     /**
75      * The file name that will be loaded by Spring.
76      */
77     @Value("${clamp.config.sdc.blueprint.parser.mapping:'classpath:/clds/blueprint-parser-mapping.json'}")
78     protected String blueprintMappingFile;
79     @Autowired
80     protected ApplicationContext appContext;
81     @Autowired
82     private CldsDao cldsDao;
83     @Autowired
84     CldsTemplateService cldsTemplateService;
85     @Autowired
86     CldsService cldsService;
87     @Autowired
88     DcaeInventoryServices dcaeInventoryService;
89     @Autowired
90     private XslTransformer cldsBpmnTransformer;
91
92     @PostConstruct
93     public void loadConfiguration() throws IOException {
94         BlueprintParserMappingConfiguration
95             .createFromJson(appContext.getResource(blueprintMappingFile).getInputStream()).stream()
96             .forEach(e -> bpmnMapping.put(e.getBlueprintKey(), e.getFiles()));
97     }
98
99     @Override
100     public boolean isCsarAlreadyDeployed(CsarHandler csar) throws SdcArtifactInstallerException {
101         boolean alreadyInstalled = true;
102         for (Entry<String, BlueprintArtifact> blueprint : csar.getMapOfBlueprints().entrySet()) {
103             alreadyInstalled = alreadyInstalled
104                 && (CldsModel.retrieve(cldsDao, buildModelName(csar, blueprint.getKey()), true).getId() != null) ? true
105                 : false;
106         }
107         return alreadyInstalled;
108     }
109
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("\\*", "");
116         } else {
117             // This is normally the get_input case
118             policyScopePrefix = MODEL_NAME_PREFIX;
119         }
120         return policyScopePrefix + csar.getSdcCsarHelper().getServiceMetadata().getValue("name") + "_v"
121             + csar.getSdcNotification().getServiceVersion().replace('.', '_') + "_"
122             + resourceInstanceName.replaceAll(" ", "");
123     }
124
125     @Override
126     @Transactional
127     public void installTheCsar(CsarHandler csar) throws SdcArtifactInstallerException, InterruptedException {
128         try {
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()));
136             }
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 e) {
141             throw new SdcArtifactInstallerException("Exception caught during the Dcae query to get ServiceTypeId", e);
142         }
143     }
144
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());
154             }
155         });
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");
161         }
162         logger.info("Mapping found for blueprint " + blueprintArtifact.getBlueprintArtifactName() + " is "
163             + listConfig.get(0).getBpmnXmlFilePath());
164         return listConfig.get(0);
165     }
166
167     String getAllBlueprintParametersInJson(BlueprintArtifact blueprintArtifact) {
168         JsonObject node = new JsonObject();
169         Yaml yaml = new Yaml();
170         Map<String, Object> inputsNodes = ((Map<String, Object>) ((Map<String, Object>) yaml
171             .load(blueprintArtifact.getDcaeBlueprint())).get("inputs"));
172         inputsNodes.entrySet().stream().filter(e -> !e.getKey().contains("policy_id")).forEach(elem -> {
173             Object defaultValue = ((Map<String, Object>) elem.getValue()).get("default");
174             if (defaultValue != null) {
175                 addPropertyToNode(node, elem.getKey(), defaultValue);
176             } else {
177                 node.addProperty(elem.getKey(), "");
178             }
179         });
180         node.addProperty("policy_id", "AUTO_GENERATED_POLICY_ID_AT_SUBMIT");
181         return node.toString();
182     }
183
184     private static String searchForPolicyScopePrefix(BlueprintArtifact blueprintArtifact)
185         throws SdcArtifactInstallerException {
186         String policyName = null;
187         Yaml yaml = new Yaml();
188         List<String> policyNameList = new ArrayList<>();
189         Map<String, Object> templateNodes = ((Map<String, Object>) ((Map<String, Object>) yaml
190             .load(blueprintArtifact.getDcaeBlueprint())).get("node_templates"));
191         templateNodes.entrySet().stream().filter(e -> e.getKey().contains("policy")).forEach(ef -> {
192             String filteredPolicyName = (String) ((Map<String, Object>) ((Map<String, Object>) ef.getValue())
193                 .get("properties")).get("policy_filter");
194             if (policyName != null) {
195                 policyNameList.add(filteredPolicyName);
196             } else {
197                 String inputPolicyName = (String) ((Map<String, Object>) ((Map<String, Object>) ((Map<String, Object>) ef
198                     .getValue()).get("properties")).get("policy_id")).get(GET_INPUT_BLUEPRINT_PARAM);
199                 if (inputPolicyName != null) {
200                     policyNameList.add(GET_INPUT_BLUEPRINT_PARAM);
201                 }
202             }
203         });
204         if (policyNameList.size() > 1) {
205             throw new SdcArtifactInstallerException(
206                 "The code does not currently support multiple Policy MicroServices in the blueprint");
207         } else if (policyNameList.isEmpty()) {
208             throw new SdcArtifactInstallerException(
209                 "There is no recognized Policy MicroService found in the blueprint");
210         }
211         logger.info("policyName found in blueprint " + blueprintArtifact.getBlueprintArtifactName() + " is "
212             + policyNameList.get(0));
213         return policyNameList.get(0);
214     }
215
216     /**
217      * This call must be done when deploying the SDC notification as this call get the latest version of the artifact
218      * (version can be specified to DCAE call)
219      *
220      * @return The DcaeInventoryResponse object containing the dcae values
221      */
222     private DcaeInventoryResponse queryDcaeToGetServiceTypeId(BlueprintArtifact blueprintArtifact)
223         throws IOException, ParseException, InterruptedException {
224         return dcaeInventoryService.getDcaeInformation(blueprintArtifact.getBlueprintArtifactName(),
225             blueprintArtifact.getBlueprintInvariantServiceUuid(),
226             blueprintArtifact.getResourceAttached().getResourceInvariantUUID());
227     }
228
229     private CldsTemplate createFakeCldsTemplate(CsarHandler csar, BlueprintArtifact blueprintArtifact,
230         BlueprintParserFilesConfiguration configFiles) throws IOException, SdcArtifactInstallerException {
231         CldsTemplate template = new CldsTemplate();
232         template.setBpmnId("Sdc-Generated");
233         template
234             .setBpmnText(IOUtils.toString(appContext.getResource(configFiles.getBpmnXmlFilePath()).getInputStream()));
235         template.setPropText(
236             "{\"global\":[{\"name\":\"service\",\"value\":[\"" + blueprintArtifact.getDcaeBlueprint() + "\"]}]}");
237         template
238             .setImageText(IOUtils.toString(appContext.getResource(configFiles.getSvgXmlFilePath()).getInputStream()));
239         template.setName(TEMPLATE_NAME_PREFIX
240             + buildModelName(csar, blueprintArtifact.getResourceAttached().getResourceInstanceName()));
241         template.save(cldsDao, null);
242         logger.info("Fake Clds Template created for blueprint " + blueprintArtifact.getBlueprintArtifactName()
243             + " with name " + template.getName());
244         return template;
245     }
246
247     private CldsModel createFakeCldsModel(CsarHandler csar, BlueprintArtifact blueprintArtifact,
248         CldsTemplate cldsTemplate, DcaeInventoryResponse dcaeInventoryResponse) throws SdcArtifactInstallerException {
249         try {
250             CldsModel cldsModel = new CldsModel();
251             cldsModel.setName(buildModelName(csar, blueprintArtifact.getResourceAttached().getResourceInstanceName()));
252             cldsModel.setBlueprintText(blueprintArtifact.getDcaeBlueprint());
253             cldsModel.setTemplateName(cldsTemplate.getName());
254             cldsModel.setTemplateId(cldsTemplate.getId());
255             cldsModel.setBpmnText(cldsTemplate.getBpmnText());
256             cldsModel.setTypeId(dcaeInventoryResponse.getTypeId());
257             cldsModel.setTypeName(dcaeInventoryResponse.getTypeName());
258             cldsModel.setControlNamePrefix(CONTROL_NAME_PREFIX);
259             // We must save it otherwise object won't be created in db
260             // and proptext will always be null
261             cldsModel.setPropText("{\"global\":[]}");
262             // Must save first to have the generated id available to generate
263             // the policyId
264             cldsModel = cldsModel.save(cldsDao, null);
265             cldsModel = setModelPropText(cldsModel, blueprintArtifact, cldsTemplate);
266             logger.info("Fake Clds Model created for blueprint " + blueprintArtifact.getBlueprintArtifactName()
267                 + " with name " + cldsModel.getName());
268             return cldsModel;
269         } catch (TransformerException e) {
270             throw new SdcArtifactInstallerException("TransformerException when decoding the BpmnText", e);
271         }
272     }
273
274     private CldsModel setModelPropText(CldsModel cldsModel, BlueprintArtifact blueprintArtifact,
275         CldsTemplate cldsTemplate) throws TransformerException {
276         // Do a test to validate the BPMN
277         new ModelProperties(cldsModel.getName(), cldsModel.getControlName(), "PUT", false,
278             cldsBpmnTransformer.doXslTransformToString(cldsTemplate.getBpmnText()), "{}");
279         String inputParams = "{\"name\":\"deployParameters\",\"value\":"
280             + getAllBlueprintParametersInJson(blueprintArtifact) + "}";
281         cldsModel.setPropText("{\"global\":[{\"name\":\"service\",\"value\":[\""
282             + blueprintArtifact.getBlueprintInvariantServiceUuid() + "\"]},{\"name\":\"vf\",\"value\":[\""
283             + blueprintArtifact.getResourceAttached().getResourceInvariantUUID()
284             + "\"]},{\"name\":\"actionSet\",\"value\":[\"vnfRecipe\"]},{\"name\":\"location\",\"value\":[\"DC1\"]},"
285             + inputParams + "]}");
286         return cldsModel.save(cldsDao, null);
287     }
288
289     private void addPropertyToNode(JsonObject node, String key, Object value) {
290         if (value instanceof String) {
291             node.addProperty(key, (String) value);
292         } else if (value instanceof Number) {
293             node.addProperty(key, (Number) value);
294         } else if (value instanceof Boolean) {
295             node.addProperty(key, (Boolean) value);
296         } else if (value instanceof Character) {
297             node.addProperty(key, (Character) value);
298         } else {
299             node.addProperty(key, JsonUtils.GSON.toJson(value));
300         }
301     }
302 }