Merge changes from topic 'bugfix/sdc-controller'
[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
28 import java.io.IOException;
29 import java.util.ArrayList;
30 import java.util.HashMap;
31 import java.util.List;
32 import java.util.Map;
33
34 import javax.annotation.PostConstruct;
35
36 import org.json.simple.parser.ParseException;
37 import org.onap.clamp.clds.client.DcaeInventoryServices;
38 import org.onap.clamp.clds.config.sdc.BlueprintParserFilesConfiguration;
39 import org.onap.clamp.clds.config.sdc.BlueprintParserMappingConfiguration;
40 import org.onap.clamp.clds.dao.CldsDao;
41 import org.onap.clamp.clds.exception.sdc.controller.SdcArtifactInstallerException;
42 import org.onap.clamp.clds.model.CldsModel;
43 import org.onap.clamp.clds.model.CldsTemplate;
44 import org.onap.clamp.clds.service.CldsService;
45 import org.onap.clamp.clds.service.CldsTemplateService;
46 import org.springframework.beans.factory.annotation.Autowired;
47 import org.springframework.beans.factory.annotation.Value;
48 import org.springframework.context.ApplicationContext;
49 import org.yaml.snakeyaml.Yaml;
50
51 /**
52  * This class will be instantiated by spring config, and used by Sdc Controller.
53  * There is no state kept by the bean. It's used to deploy the csar/notification
54  * received from SDC in DB.
55  */
56 public class CsarInstallerImpl implements CsarInstaller {
57
58     private Map<String, BlueprintParserFilesConfiguration> bpmnMapping = new HashMap<>();
59     public static final String TEMPLATE_NAME_PREFIX = "DCAE-Designer-ClosedLoopTemplate-";
60     public static final String MODEL_NAME_PREFIX = "ClosedLoop-";
61     /**
62      * The file name that will be loaded by Spring.
63      */
64     @Value("${clamp.config.sdc.blueprint.parser.mapping:'classpath:/clds/blueprint-parser-mapping.json'}")
65     protected String blueprintMappingFile;
66     @Autowired
67     protected ApplicationContext appContext;
68     @Autowired
69     private CldsDao cldsDao;
70     @Autowired
71     CldsTemplateService cldsTemplateService;
72     @Autowired
73     CldsService cldsService;
74     @Autowired
75     DcaeInventoryServices dcaeInventoryService;
76
77     @PostConstruct
78     public void loadConfiguration() throws IOException {
79         BlueprintParserMappingConfiguration
80                 .createFromJson(appContext.getResource(blueprintMappingFile).getInputStream()).stream()
81                 .forEach(e -> bpmnMapping.put(e.getBlueprintKey(), e.getFiles()));
82     }
83
84     @Override
85     public boolean isCsarAlreadyDeployed(CsarHandler csar) throws SdcArtifactInstallerException {
86         return (CldsModel.retrieve(cldsDao, csar.getSdcCsarHelper().getServiceMetadata().getValue("name"),
87                 false) != null) ? true : false;
88     }
89
90     @Override
91     public void installTheCsar(CsarHandler csar) throws SdcArtifactInstallerException {
92         try {
93             String serviceTypeId = queryDcaeToGetServiceTypeId(csar);
94             createFakeCldsModel(csar, createFakeCldsTemplate(csar, this.searchForRightMapping(csar)), serviceTypeId);
95         } catch (IOException e) {
96             throw new SdcArtifactInstallerException("Exception caught during the Csar installation in database", e);
97         } catch (ParseException e) {
98             throw new SdcArtifactInstallerException("Exception caught during the Dcae query to get ServiceTypeId", e);
99         }
100     }
101
102     private BlueprintParserFilesConfiguration searchForRightMapping(CsarHandler csar)
103             throws SdcArtifactInstallerException {
104         List<BlueprintParserFilesConfiguration> listConfig = new ArrayList<>();
105         Yaml yaml = new Yaml();
106         Map<String, Object> templateNodes = ((Map<String, Object>) ((Map<String, Object>) yaml
107                 .load(csar.getDcaeBlueprint())).get("node_templates"));
108         bpmnMapping.entrySet().forEach(e -> {
109             if (templateNodes.keySet().stream().anyMatch(t -> t.contains(e.getKey()))) {
110                 listConfig.add(e.getValue());
111             }
112         });
113         if (listConfig.size() > 1) {
114             throw new SdcArtifactInstallerException(
115                     "The code does not currently support multiple MicroServices in the blueprint");
116         } else if (listConfig.isEmpty()) {
117             throw new SdcArtifactInstallerException("There is no recognized MicroService found in the blueprint");
118         }
119         return listConfig.get(0);
120     }
121
122     private String searchForPolicyName(CsarHandler csar) throws SdcArtifactInstallerException {
123         String policyName = null;
124         Yaml yaml = new Yaml();
125         List<String> policyNameList = new ArrayList<>();
126         Map<String, Object> templateNodes = ((Map<String, Object>) ((Map<String, Object>) yaml
127                 .load(csar.getDcaeBlueprint())).get("node_templates"));
128         templateNodes.entrySet().stream().filter(e -> e.getKey().contains("policy_")).forEach(ef -> {
129             String filteredPolicyName = (String) ((Map<String, Object>) ((Map<String, Object>) ef.getValue())
130                     .get("properties")).get("policy_filter");
131             if (policyName != null) {
132                 policyNameList.add(filteredPolicyName);
133             } else {
134                 String inputPolicyName = (String) ((Map<String, Object>) ((Map<String, Object>) ((Map<String, Object>) ef
135                         .getValue()).get("properties")).get("policy_id")).get("get_input");
136                 if (inputPolicyName != null) {
137                     policyNameList.add("get_input");
138                 }
139             }
140         });
141         if (policyNameList.size() > 1) {
142             throw new SdcArtifactInstallerException(
143                     "The code does not currently support multiple Policy MicroServices in the blueprint");
144         } else if (policyNameList.isEmpty()) {
145             throw new SdcArtifactInstallerException(
146                     "There is no recognized Policy MicroService found in the blueprint");
147         }
148         return policyNameList.get(0);
149     }
150
151     private String queryDcaeToGetServiceTypeId(CsarHandler csar) throws IOException, ParseException {
152         return dcaeInventoryService.getDcaeInformation(csar.getBlueprintArtifactName(),
153                 csar.getBlueprintInvariantServiceUuid(), csar.getBlueprintInvariantResourceUuid()).getTypeId();
154     }
155
156     private CldsTemplate createFakeCldsTemplate(CsarHandler csar, BlueprintParserFilesConfiguration configFiles)
157             throws IOException {
158         CldsTemplate template = new CldsTemplate();
159         template.setBpmnId("Sdc-Generated");
160         template.setBpmnText(
161                 IOUtils.toString(appContext.getResource(configFiles.getBpmnXmlFilePath()).getInputStream()));
162         template.setPropText("{\"global\":[{\"name\":\"service\",\"value\":[\"" + csar.getDcaeBlueprint() + "\"]}]}");
163         template.setImageText(
164                 IOUtils.toString(appContext.getResource(configFiles.getSvgXmlFilePath()).getInputStream()));
165         template.setName(TEMPLATE_NAME_PREFIX + csar.getSdcCsarHelper().getServiceMetadata().getValue("name"));
166         template.save(cldsDao, null);
167         return template;
168     }
169
170     private CldsModel createFakeCldsModel(CsarHandler csar, CldsTemplate cldsTemplate, String serviceTypeId)
171             throws SdcArtifactInstallerException {
172         CldsModel cldsModel = new CldsModel();
173         String policyName = searchForPolicyName(csar);
174         if (policyName.contains("*")) {
175             // It's a filter must add a specific prefix
176             cldsModel.setControlNamePrefix(policyName);
177         } else {
178             cldsModel.setControlNamePrefix(MODEL_NAME_PREFIX);
179         }
180         cldsModel.setName(csar.getSdcCsarHelper().getServiceMetadata().getValue("name"));
181         cldsModel.setBlueprintText(csar.getDcaeBlueprint());
182         cldsModel.setTemplateName(cldsTemplate.getName());
183         cldsModel.setTemplateId(cldsTemplate.getId());
184         cldsModel.setPropText("{\"global\":[{\"name\":\"service\",\"value\":[\""
185                 + csar.getBlueprintInvariantServiceUuid() + "\"]},{\"name\":\"vf\",\"value\":[\""
186                 + csar.getBlueprintInvariantResourceUuid()
187                 + "\"]},{\"name\":\"actionSet\",\"value\":[\"vnfRecipe\"]},{\"name\":\"location\",\"value\":[\"DC1\"]}]}");
188         cldsModel.setBpmnText(cldsTemplate.getBpmnText());
189         cldsModel.setTypeId(serviceTypeId);
190         cldsModel.save(cldsDao, null);
191         return cldsModel;
192     }
193 }