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