57fe7cd472c33f73687f1ca6198bb866b84e73cf
[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.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.springframework.beans.factory.annotation.Autowired;
55 import org.springframework.beans.factory.annotation.Value;
56 import org.springframework.context.ApplicationContext;
57 import org.springframework.transaction.annotation.Transactional;
58 import org.yaml.snakeyaml.Yaml;
59
60 /**
61  * This class will be instantiated by spring config, and used by Sdc Controller.
62  * There is no state kept by the bean. It's used to deploy the csar/notification
63  * 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     @Autowired
92     private ClampProperties refProp;
93
94     @PostConstruct
95     public void loadConfiguration() throws IOException {
96         BlueprintParserMappingConfiguration
97                 .createFromJson(appContext.getResource(blueprintMappingFile).getInputStream()).stream()
98                 .forEach(e -> bpmnMapping.put(e.getBlueprintKey(), e.getFiles()));
99     }
100
101     @Override
102     public boolean isCsarAlreadyDeployed(CsarHandler csar) throws SdcArtifactInstallerException {
103         boolean alreadyInstalled = true;
104         for (Entry<String, BlueprintArtifact> blueprint : csar.getMapOfBlueprints().entrySet()) {
105             alreadyInstalled = alreadyInstalled
106                     && (CldsModel.retrieve(cldsDao, buildModelName(csar, blueprint.getKey()), true).getId() != null)
107                             ? true
108                             : false;
109         }
110         return alreadyInstalled;
111     }
112
113     public static String buildModelName(CsarHandler csar, String resourceInstanceName)
114             throws SdcArtifactInstallerException {
115         String policyScopePrefix = searchForPolicyScopePrefix(csar.getMapOfBlueprints().get(resourceInstanceName));
116         if (policyScopePrefix.contains("*")) {
117             // This is policy_filter type
118             policyScopePrefix = policyScopePrefix.replaceAll("\\*", "");
119         } else {
120             // This is normally the get_input case
121             policyScopePrefix = MODEL_NAME_PREFIX;
122         }
123         return policyScopePrefix + csar.getSdcCsarHelper().getServiceMetadata().getValue("name") + "_v"
124                 + csar.getSdcNotification().getServiceVersion().replace('.', '_') + "_"
125                 + resourceInstanceName.replaceAll(" ", "");
126     }
127
128     @Override
129     @Transactional
130     public void installTheCsar(CsarHandler csar) throws SdcArtifactInstallerException {
131         try {
132             logger.info("Installing the CSAR " + csar.getFilePath());
133             for (Entry<String, BlueprintArtifact> blueprint : csar.getMapOfBlueprints().entrySet()) {
134                 logger.info("Processing blueprint " + blueprint.getValue().getBlueprintArtifactName());
135                 createFakeCldsModel(csar, blueprint.getValue(),
136                         createFakeCldsTemplate(csar, blueprint.getValue(),
137                                 this.searchForRightMapping(blueprint.getValue())),
138                         queryDcaeToGetServiceTypeId(blueprint.getValue()));
139             }
140             logger.info("Successfully installed the CSAR " + csar.getFilePath());
141         } catch (IOException e) {
142             throw new SdcArtifactInstallerException("Exception caught during the Csar installation in database", e);
143         } catch (ParseException | InterruptedException e) {
144             throw new SdcArtifactInstallerException("Exception caught during the Dcae query to get ServiceTypeId", e);
145         }
146     }
147
148     private BlueprintParserFilesConfiguration searchForRightMapping(BlueprintArtifact blueprintArtifact)
149             throws SdcArtifactInstallerException {
150         List<BlueprintParserFilesConfiguration> listConfig = new ArrayList<>();
151         Yaml yaml = new Yaml();
152         Map<String, Object> templateNodes = ((Map<String, Object>) ((Map<String, Object>) yaml
153                 .load(blueprintArtifact.getDcaeBlueprint())).get("node_templates"));
154         bpmnMapping.entrySet().forEach(e -> {
155             if (templateNodes.keySet().stream().anyMatch(t -> t.contains(e.getKey()))) {
156                 listConfig.add(e.getValue());
157             }
158         });
159         if (listConfig.size() > 1) {
160             throw new SdcArtifactInstallerException(
161                     "The code does not currently support multiple MicroServices in the blueprint");
162         } else if (listConfig.isEmpty()) {
163             throw new SdcArtifactInstallerException("There is no recognized MicroService found in the blueprint");
164         }
165         logger.info("Mapping found for blueprint " + blueprintArtifact.getBlueprintArtifactName() + " is "
166                 + listConfig.get(0).getBpmnXmlFilePath());
167         return listConfig.get(0);
168     }
169
170     private static String searchForPolicyScopePrefix(BlueprintArtifact blueprintArtifact)
171             throws SdcArtifactInstallerException {
172         String policyName = null;
173         Yaml yaml = new Yaml();
174         List<String> policyNameList = new ArrayList<>();
175         Map<String, Object> templateNodes = ((Map<String, Object>) ((Map<String, Object>) yaml
176                 .load(blueprintArtifact.getDcaeBlueprint())).get("node_templates"));
177         templateNodes.entrySet().stream().filter(e -> e.getKey().contains("policy")).forEach(ef -> {
178             String filteredPolicyName = (String) ((Map<String, Object>) ((Map<String, Object>) ef.getValue())
179                     .get("properties")).get("policy_filter");
180             if (policyName != null) {
181                 policyNameList.add(filteredPolicyName);
182             } else {
183                 String inputPolicyName = (String) ((Map<String, Object>) ((Map<String, Object>) ((Map<String, Object>) ef
184                         .getValue()).get("properties")).get("policy_id")).get(GET_INPUT_BLUEPRINT_PARAM);
185                 if (inputPolicyName != null) {
186                     policyNameList.add(GET_INPUT_BLUEPRINT_PARAM);
187                 }
188             }
189         });
190         if (policyNameList.size() > 1) {
191             throw new SdcArtifactInstallerException(
192                     "The code does not currently support multiple Policy MicroServices in the blueprint");
193         } else if (policyNameList.isEmpty()) {
194             throw new SdcArtifactInstallerException(
195                     "There is no recognized Policy MicroService found in the blueprint");
196         }
197         logger.info("policyName found in blueprint " + blueprintArtifact.getBlueprintArtifactName() + " is "
198                 + policyNameList.get(0));
199         return policyNameList.get(0);
200     }
201
202     /**
203      * This call must be done when deploying the SDC notification as this call
204      * get the latest version of the artifact (version can be specified to DCAE
205      * call)
206      * 
207      * @param blueprintArtifact
208      * @return The DcaeInventoryResponse object containing the dcae values
209      * @throws IOException
210      * @throws ParseException
211      * @throws InterruptedException
212      */
213     private DcaeInventoryResponse queryDcaeToGetServiceTypeId(BlueprintArtifact blueprintArtifact)
214             throws IOException, ParseException, InterruptedException {
215         return dcaeInventoryService.getDcaeInformation(blueprintArtifact.getBlueprintArtifactName(),
216                 blueprintArtifact.getBlueprintInvariantServiceUuid(),
217                 blueprintArtifact.getResourceAttached().getResourceInvariantUUID());
218     }
219
220     private CldsTemplate createFakeCldsTemplate(CsarHandler csar, BlueprintArtifact blueprintArtifact,
221             BlueprintParserFilesConfiguration configFiles) throws IOException, SdcArtifactInstallerException {
222         CldsTemplate template = new CldsTemplate();
223         template.setBpmnId("Sdc-Generated");
224         template.setBpmnText(
225                 IOUtils.toString(appContext.getResource(configFiles.getBpmnXmlFilePath()).getInputStream()));
226         template.setPropText(
227                 "{\"global\":[{\"name\":\"service\",\"value\":[\"" + blueprintArtifact.getDcaeBlueprint() + "\"]}]}");
228         template.setImageText(
229                 IOUtils.toString(appContext.getResource(configFiles.getSvgXmlFilePath()).getInputStream()));
230         template.setName(TEMPLATE_NAME_PREFIX
231                 + buildModelName(csar, blueprintArtifact.getResourceAttached().getResourceInstanceName()));
232         template.save(cldsDao, null);
233         logger.info("Fake Clds Template created for blueprint " + blueprintArtifact.getBlueprintArtifactName()
234                 + " with name " + template.getName());
235         return template;
236     }
237
238     private CldsModel createFakeCldsModel(CsarHandler csar, BlueprintArtifact blueprintArtifact,
239             CldsTemplate cldsTemplate, DcaeInventoryResponse dcaeInventoryResponse)
240             throws SdcArtifactInstallerException {
241         try {
242             CldsModel cldsModel = new CldsModel();
243             cldsModel.setName(buildModelName(csar, blueprintArtifact.getResourceAttached().getResourceInstanceName()));
244             cldsModel.setBlueprintText(blueprintArtifact.getDcaeBlueprint());
245             cldsModel.setTemplateName(cldsTemplate.getName());
246             cldsModel.setTemplateId(cldsTemplate.getId());
247             cldsModel.setBpmnText(cldsTemplate.getBpmnText());
248             cldsModel.setTypeId(dcaeInventoryResponse.getTypeId());
249             cldsModel.setTypeName(dcaeInventoryResponse.getTypeName());
250             cldsModel.setControlNamePrefix(CONTROL_NAME_PREFIX);
251             // We must save it otherwise object won't be created in db
252             // and proptext will always be null
253             cldsModel.setPropText("{\"global\":[]}");
254             // Must save first to have the generated id available to generate
255             // the policyId
256             cldsModel = cldsModel.save(cldsDao, null);
257             cldsModel = setModelPropText(cldsModel, blueprintArtifact, cldsTemplate);
258             logger.info("Fake Clds Model created for blueprint " + blueprintArtifact.getBlueprintArtifactName()
259                     + " with name " + cldsModel.getName());
260             return cldsModel;
261         } catch (TransformerException e) {
262             throw new SdcArtifactInstallerException("TransformerException when decoding the BpmnText", e);
263         }
264     }
265
266     private CldsModel setModelPropText(CldsModel cldsModel, BlueprintArtifact blueprintArtifact,
267             CldsTemplate cldsTemplate) throws TransformerException {
268         ModelProperties modelProp = new ModelProperties(cldsModel.getName(), cldsModel.getControlName(), "PUT", false,
269                 cldsBpmnTransformer.doXslTransformToString(cldsTemplate.getBpmnText()), "{}");
270         String inputParams = "{\"name\":\"deployParameters\",\"value\":{\n" + "\"policy_id\": \""
271                 + "AUTO_GENERATED_POLICY_ID_AT_SUBMIT" + "\"" + "}}";
272         cldsModel.setPropText("{\"global\":[{\"name\":\"service\",\"value\":[\""
273                 + blueprintArtifact.getBlueprintInvariantServiceUuid() + "\"]},{\"name\":\"vf\",\"value\":[\""
274                 + blueprintArtifact.getResourceAttached().getResourceInvariantUUID()
275                 + "\"]},{\"name\":\"actionSet\",\"value\":[\"vnfRecipe\"]},{\"name\":\"location\",\"value\":[\"DC1\"]},"
276                 + inputParams + "]}");
277         return cldsModel.save(cldsDao, null);
278     }
279 }