Rework of the csarinstaller
[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
36 import javax.annotation.PostConstruct;
37
38 import org.json.simple.parser.ParseException;
39 import org.onap.clamp.clds.client.DcaeInventoryServices;
40 import org.onap.clamp.clds.config.sdc.BlueprintParserFilesConfiguration;
41 import org.onap.clamp.clds.config.sdc.BlueprintParserMappingConfiguration;
42 import org.onap.clamp.clds.dao.CldsDao;
43 import org.onap.clamp.clds.exception.sdc.controller.SdcArtifactInstallerException;
44 import org.onap.clamp.clds.model.CldsModel;
45 import org.onap.clamp.clds.model.CldsTemplate;
46 import org.onap.clamp.clds.service.CldsService;
47 import org.onap.clamp.clds.service.CldsTemplateService;
48 import org.springframework.beans.factory.annotation.Autowired;
49 import org.springframework.beans.factory.annotation.Value;
50 import org.springframework.context.ApplicationContext;
51 import org.springframework.stereotype.Component;
52 import org.yaml.snakeyaml.Yaml;
53
54 @Component
55 public class CsarInstallerImpl implements CsarInstaller {
56
57     private static final EELFLogger logger = EELFManager.getInstance().getLogger(CsarInstallerImpl.class);
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 = "DCAE-Designer-ClosedLoopInstance-";
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 false;
87     }
88
89     @Override
90     public void installTheCsar(CsarHandler csar) throws SdcArtifactInstallerException {
91         try {
92             String serviceTypeId = queryDcaeToGetServiceTypeId(csar);
93             String policyName = searchForPolicyName(csar);
94             if (policyName.contains("*")) {
95             }
96             createFakeCldsModel(csar, createFakeCldsTemplate(csar, this.searchForRightMapping(csar)), serviceTypeId);
97         } catch (IOException e) {
98             throw new SdcArtifactInstallerException("Exception caught during the Csar installation in database", e);
99         } catch (ParseException e) {
100             throw new SdcArtifactInstallerException("Exception caught during the Dcae query to get ServiceTypeId", e);
101         }
102     }
103
104     private BlueprintParserFilesConfiguration searchForRightMapping(CsarHandler csar)
105             throws SdcArtifactInstallerException {
106         List<BlueprintParserFilesConfiguration> listConfig = new ArrayList<>();
107         Yaml yaml = new Yaml();
108         Map<String, Object> templateNodes = ((Map<String, Object>) ((Map<String, Object>) yaml
109                 .load(csar.getDcaeBlueprint())).get("node_templates"));
110         bpmnMapping.entrySet().forEach(e -> {
111             if (templateNodes.keySet().stream().anyMatch(t -> t.contains(e.getKey()))) {
112                 listConfig.add(e.getValue());
113             }
114         });
115         if (listConfig.size() > 1) {
116             throw new SdcArtifactInstallerException(
117                     "The code does not currently support multiple MicroServices in the blueprint");
118         } else if (listConfig.isEmpty()) {
119             throw new SdcArtifactInstallerException("There is no recognized MicroService found in the blueprint");
120         }
121         return listConfig.get(0);
122     }
123
124     private String searchForPolicyName(CsarHandler csar) throws SdcArtifactInstallerException {
125         String policyName = null;
126         Yaml yaml = new Yaml();
127         List<String> policyNameList = new ArrayList<>();
128         Map<String, Object> templateNodes = ((Map<String, Object>) ((Map<String, Object>) yaml
129                 .load(csar.getDcaeBlueprint())).get("node_templates"));
130         templateNodes.entrySet().stream().filter(e -> e.getKey().contains("policy_")).forEach(ef -> {
131             String filteredPolicyName = (String) ((Map<String, Object>) ((Map<String, Object>) ef.getValue())
132                     .get("properties")).get("policy_filter");
133             if (policyName != null) {
134                 policyNameList.add(filteredPolicyName);
135             } else {
136                 String inputPolicyName = (String) ((Map<String, Object>) ((Map<String, Object>) ((Map<String, Object>) ef
137                         .getValue()).get("properties")).get("policy_id")).get("get_input");
138                 if (inputPolicyName != null) {
139                     policyNameList.add("get_input");
140                 }
141             }
142         });
143         if (policyNameList.size() > 1) {
144             throw new SdcArtifactInstallerException(
145                     "The code does not currently support multiple Policy MicroServices in the blueprint");
146         } else if (policyNameList.isEmpty()) {
147             throw new SdcArtifactInstallerException(
148                     "There is no recognized Policy MicroService found in the blueprint");
149         }
150         return policyNameList.get(0);
151     }
152
153     private String queryDcaeToGetServiceTypeId(CsarHandler csar) throws IOException, ParseException {
154         return dcaeInventoryService.getDcaeInformation(csar.getBlueprintArtifactName(),
155                 csar.getBlueprintInvariantServiceUuid(), csar.getBlueprintInvariantResourceUuid());
156     }
157
158     private CldsTemplate createFakeCldsTemplate(CsarHandler csar, BlueprintParserFilesConfiguration configFiles)
159             throws IOException, SdcArtifactInstallerException {
160         CldsTemplate template = new CldsTemplate();
161         template.setBpmnId("Sdc-Generated");
162         template.setBpmnText(
163                 IOUtils.toString(appContext.getResource(configFiles.getBpmnXmlFilePath()).getInputStream()));
164         template.setPropText(csar.getDcaeBlueprint());
165         template.setImageText(
166                 IOUtils.toString(appContext.getResource(configFiles.getSvgXmlFilePath()).getInputStream()));
167         template.setName(TEMPLATE_NAME_PREFIX + csar.getSdcCsarHelper().getServiceMetadata().getValue("name"));
168         template.save(cldsDao, null);
169         return template;
170     }
171
172     private CldsModel createFakeCldsModel(CsarHandler csar, CldsTemplate cldsTemplate, String serviceTypeId) {
173         CldsModel cldsModel = new CldsModel();
174         cldsModel.setControlNamePrefix(MODEL_NAME_PREFIX);
175         cldsModel.setName(csar.getSdcCsarHelper().getServiceMetadata().getValue("name"));
176         cldsModel.setBlueprintText(csar.getDcaeBlueprint());
177         cldsModel.setTemplateName(cldsTemplate.getName());
178         cldsModel.setTemplateId(cldsTemplate.getId());
179         cldsModel.setDocText(cldsTemplate.getPropText());
180         cldsModel.setPropText("{}");
181         cldsModel.setBpmnText(cldsTemplate.getBpmnText());
182         cldsModel.setTypeId(serviceTypeId);
183         cldsModel.save(cldsDao, null);
184         return cldsModel;
185     }
186 }