e28e8ab7058c384af41a716924b5e528ce3f0d3a
[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.aft.dme2.internal.apache.commons.io.IOUtils;
27 import com.att.eelf.configuration.EELFLogger;
28 import com.att.eelf.configuration.EELFManager;
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.json.simple.parser.ParseException;
41 import org.onap.clamp.clds.client.DcaeInventoryServices;
42 import org.onap.clamp.clds.config.ClampProperties;
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.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;
58
59 /**
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.
63  */
64 public class CsarInstallerImpl implements CsarInstaller {
65
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-ClosedLoopTemplate-";
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";
73     /**
74      * The file name that will be loaded by Spring.
75      */
76     @Value("${clamp.config.sdc.blueprint.parser.mapping:'classpath:/clds/blueprint-parser-mapping.json'}")
77     protected String blueprintMappingFile;
78     @Autowired
79     protected ApplicationContext appContext;
80     @Autowired
81     private CldsDao cldsDao;
82     @Autowired
83     CldsTemplateService cldsTemplateService;
84     @Autowired
85     CldsService cldsService;
86     @Autowired
87     DcaeInventoryServices dcaeInventoryService;
88     @Autowired
89     private XslTransformer cldsBpmnTransformer;
90     @Autowired
91     private ClampProperties refProp;
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         return (CldsModel.retrieve(cldsDao, buildModelName(csar), true).getId() != null) ? true : false;
103     }
104
105     public static String buildModelName(CsarHandler csar) {
106         return MODEL_NAME_PREFIX + csar.getSdcCsarHelper().getServiceMetadata().getValue("name") + "_v"
107                 + csar.getSdcNotification().getServiceVersion().replace('.', '_');
108     }
109
110     @Override
111     @Transactional
112     public void installTheCsar(CsarHandler csar) throws SdcArtifactInstallerException {
113         try {
114             logger.info("Installing the CSAR " + csar.getFilePath());
115             for (Entry<String, BlueprintArtifact> blueprint : csar.getMapOfBlueprints().entrySet()) {
116                 logger.info("Processing blueprint " + blueprint.getValue().getBlueprintArtifactName());
117                 String serviceTypeId = queryDcaeToGetServiceTypeId(blueprint.getValue());
118                 createFakeCldsModel(csar, blueprint.getValue(), createFakeCldsTemplate(csar, blueprint.getValue(),
119                         this.searchForRightMapping(blueprint.getValue())), serviceTypeId);
120             }
121             logger.info("Successfully installed the CSAR " + csar.getFilePath());
122         } catch (IOException e) {
123             throw new SdcArtifactInstallerException("Exception caught during the Csar installation in database", e);
124         } catch (ParseException | InterruptedException e) {
125             throw new SdcArtifactInstallerException("Exception caught during the Dcae query to get ServiceTypeId", e);
126         }
127     }
128
129     private BlueprintParserFilesConfiguration searchForRightMapping(BlueprintArtifact blueprintArtifact)
130             throws SdcArtifactInstallerException {
131         List<BlueprintParserFilesConfiguration> listConfig = new ArrayList<>();
132         Yaml yaml = new Yaml();
133         Map<String, Object> templateNodes = ((Map<String, Object>) ((Map<String, Object>) yaml
134                 .load(blueprintArtifact.getDcaeBlueprint())).get("node_templates"));
135         bpmnMapping.entrySet().forEach(e -> {
136             if (templateNodes.keySet().stream().anyMatch(t -> t.contains(e.getKey()))) {
137                 listConfig.add(e.getValue());
138             }
139         });
140         if (listConfig.size() > 1) {
141             throw new SdcArtifactInstallerException(
142                     "The code does not currently support multiple MicroServices in the blueprint");
143         } else if (listConfig.isEmpty()) {
144             throw new SdcArtifactInstallerException("There is no recognized MicroService found in the blueprint");
145         }
146         logger.info("Mapping found for blueprint " + blueprintArtifact.getBlueprintArtifactName() + " is "
147                 + listConfig.get(0).getBpmnXmlFilePath());
148         return listConfig.get(0);
149     }
150
151     private String searchForPolicyName(BlueprintArtifact blueprintArtifact) throws SdcArtifactInstallerException {
152         String policyName = null;
153         Yaml yaml = new Yaml();
154         List<String> policyNameList = new ArrayList<>();
155         Map<String, Object> templateNodes = ((Map<String, Object>) ((Map<String, Object>) yaml
156                 .load(blueprintArtifact.getDcaeBlueprint())).get("node_templates"));
157         templateNodes.entrySet().stream().filter(e -> e.getKey().contains("policy")).forEach(ef -> {
158             String filteredPolicyName = (String) ((Map<String, Object>) ((Map<String, Object>) ef.getValue())
159                     .get("properties")).get("policy_filter");
160             if (policyName != null) {
161                 policyNameList.add(filteredPolicyName);
162             } else {
163                 String inputPolicyName = (String) ((Map<String, Object>) ((Map<String, Object>) ((Map<String, Object>) ef
164                         .getValue()).get("properties")).get("policy_id")).get(GET_INPUT_BLUEPRINT_PARAM);
165                 if (inputPolicyName != null) {
166                     policyNameList.add(GET_INPUT_BLUEPRINT_PARAM);
167                 }
168             }
169         });
170         if (policyNameList.size() > 1) {
171             throw new SdcArtifactInstallerException(
172                     "The code does not currently support multiple Policy MicroServices in the blueprint");
173         } else if (policyNameList.isEmpty()) {
174             throw new SdcArtifactInstallerException(
175                     "There is no recognized Policy MicroService found in the blueprint");
176         }
177         logger.info("policyName found in blueprint " + blueprintArtifact.getBlueprintArtifactName() + " is "
178                 + policyNameList.get(0));
179         return policyNameList.get(0);
180     }
181
182     private String queryDcaeToGetServiceTypeId(BlueprintArtifact blueprintArtifact)
183             throws IOException, ParseException, InterruptedException {
184         return dcaeInventoryService.getDcaeInformation(blueprintArtifact.getBlueprintArtifactName(),
185                 blueprintArtifact.getBlueprintInvariantServiceUuid(),
186                 blueprintArtifact.getResourceAttached().getResourceInvariantUUID()).getTypeId();
187     }
188
189     private CldsTemplate createFakeCldsTemplate(CsarHandler csar, BlueprintArtifact blueprintArtifact,
190             BlueprintParserFilesConfiguration configFiles) throws IOException {
191         CldsTemplate template = new CldsTemplate();
192         template.setBpmnId("Sdc-Generated");
193         template.setBpmnText(
194                 IOUtils.toString(appContext.getResource(configFiles.getBpmnXmlFilePath()).getInputStream()));
195         template.setPropText(
196                 "{\"global\":[{\"name\":\"service\",\"value\":[\"" + blueprintArtifact.getDcaeBlueprint() + "\"]}]}");
197         template.setImageText(
198                 IOUtils.toString(appContext.getResource(configFiles.getSvgXmlFilePath()).getInputStream()));
199         template.setName(TEMPLATE_NAME_PREFIX + buildModelName(csar));
200         template.save(cldsDao, null);
201         logger.info("Fake Clds Template created for blueprint " + blueprintArtifact.getBlueprintArtifactName()
202                 + " with name " + template.getName());
203         return template;
204     }
205
206     private CldsModel createFakeCldsModel(CsarHandler csar, BlueprintArtifact blueprintArtifact,
207             CldsTemplate cldsTemplate, String serviceTypeId) throws SdcArtifactInstallerException {
208         try {
209             CldsModel cldsModel = new CldsModel();
210             cldsModel.setName(buildModelName(csar));
211             cldsModel.setBlueprintText(blueprintArtifact.getDcaeBlueprint());
212             cldsModel.setTemplateName(cldsTemplate.getName());
213             cldsModel.setTemplateId(cldsTemplate.getId());
214             cldsModel.setBpmnText(cldsTemplate.getBpmnText());
215             cldsModel.setTypeId(serviceTypeId);
216             ModelProperties modelProp = new ModelProperties(cldsModel.getName(), "test", "PUT", false,
217                     cldsBpmnTransformer.doXslTransformToString(cldsTemplate.getBpmnText()), "{}");
218             String policyName = searchForPolicyName(blueprintArtifact);
219             String inputParams = "";
220             if (policyName.contains("*")) {
221                 // It's a filter must add a specific prefix
222                 cldsModel.setControlNamePrefix(policyName);
223             } else {
224                 cldsModel.setControlNamePrefix(CONTROL_NAME_PREFIX);
225                 inputParams = "{\"name\":\"deployParameters\",\"value\":{\n" + "\"policy_id\": \""
226                         + modelProp.getPolicyNameForDcaeDeploy(refProp) + "\"" + "}}";
227             }
228             cldsModel.setPropText("{\"global\":[{\"name\":\"service\",\"value\":[\""
229                     + blueprintArtifact.getBlueprintInvariantServiceUuid() + "\"]},{\"name\":\"vf\",\"value\":[\""
230                     + blueprintArtifact.getResourceAttached().getResourceInvariantUUID()
231                     + "\"]},{\"name\":\"actionSet\",\"value\":[\"vnfRecipe\"]},{\"name\":\"location\",\"value\":[\"DC1\"]},"
232                     + inputParams + "]}");
233             cldsModel = cldsModel.save(cldsDao, null);
234             logger.info("Fake Clds Model created for blueprint " + blueprintArtifact.getBlueprintArtifactName()
235                     + " with name " + cldsModel.getName());
236             return cldsModel;
237         } catch (TransformerException e) {
238             throw new SdcArtifactInstallerException("TransformerException when decoding the BpmnText", e);
239         }
240     }
241 }