Add Prefix to ModelName
[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  * ECOMP is a trademark and service mark of AT&T Intellectual Property.
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
39 import org.json.simple.parser.ParseException;
40 import org.onap.clamp.clds.client.DcaeInventoryServices;
41 import org.onap.clamp.clds.config.sdc.BlueprintParserFilesConfiguration;
42 import org.onap.clamp.clds.config.sdc.BlueprintParserMappingConfiguration;
43 import org.onap.clamp.clds.dao.CldsDao;
44 import org.onap.clamp.clds.exception.sdc.controller.SdcArtifactInstallerException;
45 import org.onap.clamp.clds.model.CldsModel;
46 import org.onap.clamp.clds.model.CldsTemplate;
47 import org.onap.clamp.clds.service.CldsService;
48 import org.onap.clamp.clds.service.CldsTemplateService;
49 import org.springframework.beans.factory.annotation.Autowired;
50 import org.springframework.beans.factory.annotation.Value;
51 import org.springframework.context.ApplicationContext;
52 import org.springframework.transaction.annotation.Transactional;
53 import org.yaml.snakeyaml.Yaml;
54
55 /**
56  * This class will be instantiated by spring config, and used by Sdc Controller.
57  * There is no state kept by the bean. It's used to deploy the csar/notification
58  * received from SDC in DB.
59  */
60 public class CsarInstallerImpl implements CsarInstaller {
61
62     private static final EELFLogger logger = EELFManager.getInstance().getLogger(CsarInstallerImpl.class);
63     private Map<String, BlueprintParserFilesConfiguration> bpmnMapping = new HashMap<>();
64     public static final String TEMPLATE_NAME_PREFIX = "DCAE-Designer-ClosedLoopTemplate-";
65     public static final String CONTROL_NAME_PREFIX = "ClosedLoop-";
66     public static final String GET_INPUT_BLUEPRINT_PARAM = "get_input";
67     // This will be used later as the policy scope
68     public static final String MODEL_NAME_PREFIX = "CLAMP";
69     /**
70      * The file name that will be loaded by Spring.
71      */
72     @Value("${clamp.config.sdc.blueprint.parser.mapping:'classpath:/clds/blueprint-parser-mapping.json'}")
73     protected String blueprintMappingFile;
74     @Autowired
75     protected ApplicationContext appContext;
76     @Autowired
77     private CldsDao cldsDao;
78     @Autowired
79     CldsTemplateService cldsTemplateService;
80     @Autowired
81     CldsService cldsService;
82     @Autowired
83     DcaeInventoryServices dcaeInventoryService;
84
85     @PostConstruct
86     public void loadConfiguration() throws IOException {
87         BlueprintParserMappingConfiguration
88                 .createFromJson(appContext.getResource(blueprintMappingFile).getInputStream()).stream()
89                 .forEach(e -> bpmnMapping.put(e.getBlueprintKey(), e.getFiles()));
90     }
91
92     @Override
93     public boolean isCsarAlreadyDeployed(CsarHandler csar) throws SdcArtifactInstallerException {
94         return (CldsModel.retrieve(cldsDao, buildModelName(csar), true).getId() != null) ? true : false;
95     }
96
97     public static String buildModelName(CsarHandler csar) {
98         return MODEL_NAME_PREFIX + csar.getSdcCsarHelper().getServiceMetadata().getValue("name") + "_v"
99                 + csar.getSdcNotification().getServiceVersion().replace('.', '_');
100     }
101
102     @Override
103     @Transactional
104     public void installTheCsar(CsarHandler csar) throws SdcArtifactInstallerException {
105         try {
106             logger.info("Installing the CSAR " + csar.getFilePath());
107             for (Entry<String, BlueprintArtifact> blueprint : csar.getMapOfBlueprints().entrySet()) {
108                 logger.info("Processing blueprint " + blueprint.getValue().getBlueprintArtifactName());
109                 String serviceTypeId = queryDcaeToGetServiceTypeId(blueprint.getValue());
110                 createFakeCldsModel(csar, blueprint.getValue(), createFakeCldsTemplate(csar, blueprint.getValue(),
111                         this.searchForRightMapping(blueprint.getValue())), serviceTypeId);
112             }
113             logger.info("Successfully installed the CSAR " + csar.getFilePath());
114         } catch (IOException e) {
115             throw new SdcArtifactInstallerException("Exception caught during the Csar installation in database", e);
116         } catch (ParseException | InterruptedException e) {
117             throw new SdcArtifactInstallerException("Exception caught during the Dcae query to get ServiceTypeId", e);
118         }
119     }
120
121     private BlueprintParserFilesConfiguration searchForRightMapping(BlueprintArtifact blueprintArtifact)
122             throws SdcArtifactInstallerException {
123         List<BlueprintParserFilesConfiguration> listConfig = new ArrayList<>();
124         Yaml yaml = new Yaml();
125         Map<String, Object> templateNodes = ((Map<String, Object>) ((Map<String, Object>) yaml
126                 .load(blueprintArtifact.getDcaeBlueprint())).get("node_templates"));
127         bpmnMapping.entrySet().forEach(e -> {
128             if (templateNodes.keySet().stream().anyMatch(t -> t.contains(e.getKey()))) {
129                 listConfig.add(e.getValue());
130             }
131         });
132         if (listConfig.size() > 1) {
133             throw new SdcArtifactInstallerException(
134                     "The code does not currently support multiple MicroServices in the blueprint");
135         } else if (listConfig.isEmpty()) {
136             throw new SdcArtifactInstallerException("There is no recognized MicroService found in the blueprint");
137         }
138         logger.info("Mapping found for blueprint " + blueprintArtifact.getBlueprintArtifactName() + " is "
139                 + listConfig.get(0).getBpmnXmlFilePath());
140         return listConfig.get(0);
141     }
142
143     private String searchForPolicyName(BlueprintArtifact blueprintArtifact) throws SdcArtifactInstallerException {
144         String policyName = null;
145         Yaml yaml = new Yaml();
146         List<String> policyNameList = new ArrayList<>();
147         Map<String, Object> templateNodes = ((Map<String, Object>) ((Map<String, Object>) yaml
148                 .load(blueprintArtifact.getDcaeBlueprint())).get("node_templates"));
149         templateNodes.entrySet().stream().filter(e -> e.getKey().contains("policy_")).forEach(ef -> {
150             String filteredPolicyName = (String) ((Map<String, Object>) ((Map<String, Object>) ef.getValue())
151                     .get("properties")).get("policy_filter");
152             if (policyName != null) {
153                 policyNameList.add(filteredPolicyName);
154             } else {
155                 String inputPolicyName = (String) ((Map<String, Object>) ((Map<String, Object>) ((Map<String, Object>) ef
156                         .getValue()).get("properties")).get("policy_id")).get(GET_INPUT_BLUEPRINT_PARAM);
157                 if (inputPolicyName != null) {
158                     policyNameList.add(GET_INPUT_BLUEPRINT_PARAM);
159                 }
160             }
161         });
162         if (policyNameList.size() > 1) {
163             throw new SdcArtifactInstallerException(
164                     "The code does not currently support multiple Policy MicroServices in the blueprint");
165         } else if (policyNameList.isEmpty()) {
166             throw new SdcArtifactInstallerException(
167                     "There is no recognized Policy MicroService found in the blueprint");
168         }
169         logger.info("policyName found in blueprint " + blueprintArtifact.getBlueprintArtifactName() + " is "
170                 + policyNameList.get(0));
171         return policyNameList.get(0);
172     }
173
174     private String queryDcaeToGetServiceTypeId(BlueprintArtifact blueprintArtifact)
175             throws IOException, ParseException, InterruptedException {
176         return dcaeInventoryService.getDcaeInformation(blueprintArtifact.getBlueprintArtifactName(),
177                 blueprintArtifact.getBlueprintInvariantServiceUuid(),
178                 blueprintArtifact.getResourceAttached().getResourceInvariantUUID()).getTypeId();
179     }
180
181     private CldsTemplate createFakeCldsTemplate(CsarHandler csar, BlueprintArtifact blueprintArtifact,
182             BlueprintParserFilesConfiguration configFiles) throws IOException {
183         CldsTemplate template = new CldsTemplate();
184         template.setBpmnId("Sdc-Generated");
185         template.setBpmnText(
186                 IOUtils.toString(appContext.getResource(configFiles.getBpmnXmlFilePath()).getInputStream()));
187         template.setPropText(
188                 "{\"global\":[{\"name\":\"service\",\"value\":[\"" + blueprintArtifact.getDcaeBlueprint() + "\"]}]}");
189         template.setImageText(
190                 IOUtils.toString(appContext.getResource(configFiles.getSvgXmlFilePath()).getInputStream()));
191         template.setName(TEMPLATE_NAME_PREFIX + buildModelName(csar));
192         template.save(cldsDao, null);
193         logger.info("Fake Clds Template created for blueprint " + blueprintArtifact.getBlueprintArtifactName()
194                 + " with name " + template.getName());
195         return template;
196     }
197
198     private CldsModel createFakeCldsModel(CsarHandler csar, BlueprintArtifact blueprintArtifact,
199             CldsTemplate cldsTemplate, String serviceTypeId) throws SdcArtifactInstallerException {
200         CldsModel cldsModel = new CldsModel();
201         String policyName = searchForPolicyName(blueprintArtifact);
202         if (policyName.contains("*")) {
203             // It's a filter must add a specific prefix
204             cldsModel.setControlNamePrefix(policyName);
205         } else {
206             cldsModel.setControlNamePrefix(CONTROL_NAME_PREFIX);
207         }
208         cldsModel.setName(buildModelName(csar));
209         cldsModel.setBlueprintText(blueprintArtifact.getDcaeBlueprint());
210         cldsModel.setTemplateName(cldsTemplate.getName());
211         cldsModel.setTemplateId(cldsTemplate.getId());
212         cldsModel.setPropText("{\"global\":[{\"name\":\"service\",\"value\":[\""
213                 + blueprintArtifact.getBlueprintInvariantServiceUuid() + "\"]},{\"name\":\"vf\",\"value\":[\""
214                 + blueprintArtifact.getResourceAttached().getResourceInvariantUUID()
215                 + "\"]},{\"name\":\"actionSet\",\"value\":[\"vnfRecipe\"]},{\"name\":\"location\",\"value\":[\"DC1\"]},{\"name\":\"deployParameters\",\"value\":{\n"
216                 + "        \"policy_id\": \"" + "test" + "\"" + "      }}]}");
217         cldsModel.setBpmnText(cldsTemplate.getBpmnText());
218         cldsModel.setTypeId(serviceTypeId);
219         cldsModel.save(cldsDao, null);
220         logger.info("Fake Clds Model created for blueprint " + blueprintArtifact.getBlueprintArtifactName()
221                 + " with name " + cldsModel.getName());
222         return cldsModel;
223     }
224 }