Add properties to model
[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.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 static final EELFLogger logger = EELFManager.getInstance().getLogger(CsarInstallerImpl.class);
61     private Map<String, BlueprintParserFilesConfiguration> bpmnMapping = new HashMap<>();
62     public static final String TEMPLATE_NAME_PREFIX = "DCAE-Designer-ClosedLoopTemplate-";
63     public static final String MODEL_NAME_PREFIX = "ClosedLoop-";
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, csar.getSdcCsarHelper().getServiceMetadata().getValue("name"),
90                 false) != null) ? true : false;
91     }
92
93     @Override
94     public void installTheCsar(CsarHandler csar) throws SdcArtifactInstallerException {
95         try {
96             String serviceTypeId = queryDcaeToGetServiceTypeId(csar);
97             createFakeCldsModel(csar, createFakeCldsTemplate(csar, this.searchForRightMapping(csar)), serviceTypeId);
98         } catch (IOException e) {
99             throw new SdcArtifactInstallerException("Exception caught during the Csar installation in database", e);
100         } catch (ParseException e) {
101             throw new SdcArtifactInstallerException("Exception caught during the Dcae query to get ServiceTypeId", e);
102         }
103     }
104
105     private BlueprintParserFilesConfiguration searchForRightMapping(CsarHandler csar)
106             throws SdcArtifactInstallerException {
107         List<BlueprintParserFilesConfiguration> listConfig = new ArrayList<>();
108         Yaml yaml = new Yaml();
109         Map<String, Object> templateNodes = ((Map<String, Object>) ((Map<String, Object>) yaml
110                 .load(csar.getDcaeBlueprint())).get("node_templates"));
111         bpmnMapping.entrySet().forEach(e -> {
112             if (templateNodes.keySet().stream().anyMatch(t -> t.contains(e.getKey()))) {
113                 listConfig.add(e.getValue());
114             }
115         });
116         if (listConfig.size() > 1) {
117             throw new SdcArtifactInstallerException(
118                     "The code does not currently support multiple MicroServices in the blueprint");
119         } else if (listConfig.isEmpty()) {
120             throw new SdcArtifactInstallerException("There is no recognized MicroService found in the blueprint");
121         }
122         return listConfig.get(0);
123     }
124
125     private String searchForPolicyName(CsarHandler csar) throws SdcArtifactInstallerException {
126         String policyName = null;
127         Yaml yaml = new Yaml();
128         List<String> policyNameList = new ArrayList<>();
129         Map<String, Object> templateNodes = ((Map<String, Object>) ((Map<String, Object>) yaml
130                 .load(csar.getDcaeBlueprint())).get("node_templates"));
131         templateNodes.entrySet().stream().filter(e -> e.getKey().contains("policy_")).forEach(ef -> {
132             String filteredPolicyName = (String) ((Map<String, Object>) ((Map<String, Object>) ef.getValue())
133                     .get("properties")).get("policy_filter");
134             if (policyName != null) {
135                 policyNameList.add(filteredPolicyName);
136             } else {
137                 String inputPolicyName = (String) ((Map<String, Object>) ((Map<String, Object>) ((Map<String, Object>) ef
138                         .getValue()).get("properties")).get("policy_id")).get("get_input");
139                 if (inputPolicyName != null) {
140                     policyNameList.add("get_input");
141                 }
142             }
143         });
144         if (policyNameList.size() > 1) {
145             throw new SdcArtifactInstallerException(
146                     "The code does not currently support multiple Policy MicroServices in the blueprint");
147         } else if (policyNameList.isEmpty()) {
148             throw new SdcArtifactInstallerException(
149                     "There is no recognized Policy MicroService found in the blueprint");
150         }
151         return policyNameList.get(0);
152     }
153
154     private String queryDcaeToGetServiceTypeId(CsarHandler csar) throws IOException, ParseException {
155         return dcaeInventoryService.getDcaeInformation(csar.getBlueprintArtifactName(),
156                 csar.getBlueprintInvariantServiceUuid(), csar.getBlueprintInvariantResourceUuid());
157     }
158
159     private CldsTemplate createFakeCldsTemplate(CsarHandler csar, BlueprintParserFilesConfiguration configFiles)
160             throws IOException, SdcArtifactInstallerException {
161         CldsTemplate template = new CldsTemplate();
162         template.setBpmnId("Sdc-Generated");
163         template.setBpmnText(
164                 IOUtils.toString(appContext.getResource(configFiles.getBpmnXmlFilePath()).getInputStream()));
165         template.setPropText("{\"global\":[{\"name\":\"service\",\"value\":[\"" + csar.getDcaeBlueprint() + "\"]}]}");
166         template.setImageText(
167                 IOUtils.toString(appContext.getResource(configFiles.getSvgXmlFilePath()).getInputStream()));
168         template.setName(TEMPLATE_NAME_PREFIX + csar.getSdcCsarHelper().getServiceMetadata().getValue("name"));
169         template.save(cldsDao, null);
170         return template;
171     }
172
173     private CldsModel createFakeCldsModel(CsarHandler csar, CldsTemplate cldsTemplate, String serviceTypeId)
174             throws SdcArtifactInstallerException {
175         CldsModel cldsModel = new CldsModel();
176         String policyName = searchForPolicyName(csar);
177         if (policyName.contains("*")) {
178             // It's a filter must add a specific prefix
179             cldsModel.setControlNamePrefix(policyName);
180         } else {
181             cldsModel.setControlNamePrefix(MODEL_NAME_PREFIX);
182         }
183         cldsModel.setName(csar.getSdcCsarHelper().getServiceMetadata().getValue("name"));
184         cldsModel.setBlueprintText(csar.getDcaeBlueprint());
185         cldsModel.setTemplateName(cldsTemplate.getName());
186         cldsModel.setTemplateId(cldsTemplate.getId());
187         // cldsModel.setDocText(cldsTemplate.getPropText());
188         cldsModel.setPropText("{\"global\":[{\"name\":\"service\",\"value\":[\""
189                 + csar.getSdcNotification().getServiceInvariantUUID() + "\"]},{\"name\":\"vf\",\"value\":[\""
190                 + csar.getBlueprintInvariantResourceUuid()
191                 + "\"]},{\"name\":\"actionSet\",\"value\":[\"vnfRecipe\"]},{\"name\":\"location\",\"value\":[\"DC1\"]}]}");
192         cldsModel.setBpmnText(cldsTemplate.getBpmnText());
193         cldsModel.setTypeId(serviceTypeId);
194         cldsModel.save(cldsDao, null);
195         return cldsModel;
196     }
197 }