Fix 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  * 
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 import javax.xml.transform.TransformerException;
39
40 import org.json.simple.parser.ParseException;
41 import org.onap.clamp.clds.client.DcaeInventoryServices;
42 import org.onap.clamp.clds.config.ClampProperties;
43 import org.onap.clamp.clds.config.sdc.BlueprintParserFilesConfiguration;
44 import org.onap.clamp.clds.config.sdc.BlueprintParserMappingConfiguration;
45 import org.onap.clamp.clds.dao.CldsDao;
46 import org.onap.clamp.clds.exception.sdc.controller.SdcArtifactInstallerException;
47 import org.onap.clamp.clds.model.CldsModel;
48 import org.onap.clamp.clds.model.CldsTemplate;
49 import org.onap.clamp.clds.model.properties.ModelProperties;
50 import org.onap.clamp.clds.service.CldsService;
51 import org.onap.clamp.clds.service.CldsTemplateService;
52 import org.onap.clamp.clds.transform.XslTransformer;
53 import org.springframework.beans.factory.annotation.Autowired;
54 import org.springframework.beans.factory.annotation.Value;
55 import org.springframework.context.ApplicationContext;
56 import org.springframework.transaction.annotation.Transactional;
57 import org.yaml.snakeyaml.Yaml;
58
59 /**
60  * This class will be instantiated by spring config, and used by Sdc Controller.
61  * There is no state kept by the bean. It's used to deploy the csar/notification
62  * received from SDC in DB.
63  */
64 public class CsarInstallerImpl implements CsarInstaller {
65
66     private static final EELFLogger logger = EELFManager.getInstance().getLogger(CsarInstallerImpl.class);
67     private Map<String, BlueprintParserFilesConfiguration> bpmnMapping = new HashMap<>();
68     public static final String TEMPLATE_NAME_PREFIX = "DCAE-Designer-Template-";
69     public static final String CONTROL_NAME_PREFIX = "ClosedLoop-";
70     public static final String GET_INPUT_BLUEPRINT_PARAM = "get_input";
71     // This will be used later as the policy scope
72     public static final String MODEL_NAME_PREFIX = "CLAMP";
73     /**
74      * The file name that will be loaded by Spring.
75      */
76     @Value("${clamp.config.sdc.blueprint.parser.mapping:'classpath:/clds/blueprint-parser-mapping.json'}")
77     protected String blueprintMappingFile;
78     @Autowired
79     protected ApplicationContext appContext;
80     @Autowired
81     private CldsDao cldsDao;
82     @Autowired
83     CldsTemplateService cldsTemplateService;
84     @Autowired
85     CldsService cldsService;
86     @Autowired
87     DcaeInventoryServices dcaeInventoryService;
88     @Autowired
89     private XslTransformer cldsBpmnTransformer;
90     @Autowired
91     private ClampProperties refProp;
92
93     @PostConstruct
94     public void loadConfiguration() throws IOException {
95         BlueprintParserMappingConfiguration
96                 .createFromJson(appContext.getResource(blueprintMappingFile).getInputStream()).stream()
97                 .forEach(e -> bpmnMapping.put(e.getBlueprintKey(), e.getFiles()));
98     }
99
100     @Override
101     public boolean isCsarAlreadyDeployed(CsarHandler csar) throws SdcArtifactInstallerException {
102         boolean alreadyInstalled = true;
103         for (Entry<String, BlueprintArtifact> blueprint : csar.getMapOfBlueprints().entrySet()) {
104             alreadyInstalled = alreadyInstalled
105                     && (CldsModel.retrieve(cldsDao, buildModelName(csar, blueprint.getKey()), true).getId() != null)
106                             ? true
107                             : false;
108         }
109         return alreadyInstalled;
110     }
111
112     public static String buildModelName(CsarHandler csar, String resourceInstanceName)
113             throws SdcArtifactInstallerException {
114         String policyScopePrefix = searchForPolicyScopePrefix(csar.getMapOfBlueprints().get(resourceInstanceName));
115         if (policyScopePrefix.contains("*")) {
116             // This is policy_filter type
117             policyScopePrefix = policyScopePrefix.replaceAll("\\*", "");
118         } else {
119             // This is normally the get_input case
120             policyScopePrefix = MODEL_NAME_PREFIX;
121         }
122         return policyScopePrefix + csar.getSdcCsarHelper().getServiceMetadata().getValue("name") + "_v"
123                 + csar.getSdcNotification().getServiceVersion().replace('.', '_') + "_" + resourceInstanceName;
124     }
125
126     @Override
127     @Transactional
128     public void installTheCsar(CsarHandler csar) throws SdcArtifactInstallerException {
129         try {
130             logger.info("Installing the CSAR " + csar.getFilePath());
131             for (Entry<String, BlueprintArtifact> blueprint : csar.getMapOfBlueprints().entrySet()) {
132                 logger.info("Processing blueprint " + blueprint.getValue().getBlueprintArtifactName());
133                 String serviceTypeId = queryDcaeToGetServiceTypeId(blueprint.getValue());
134                 createFakeCldsModel(csar, blueprint.getValue(), createFakeCldsTemplate(csar, blueprint.getValue(),
135                         this.searchForRightMapping(blueprint.getValue())), serviceTypeId);
136             }
137             logger.info("Successfully installed the CSAR " + csar.getFilePath());
138         } catch (IOException e) {
139             throw new SdcArtifactInstallerException("Exception caught during the Csar installation in database", e);
140         } catch (ParseException | InterruptedException e) {
141             throw new SdcArtifactInstallerException("Exception caught during the Dcae query to get ServiceTypeId", e);
142         }
143     }
144
145     private BlueprintParserFilesConfiguration searchForRightMapping(BlueprintArtifact blueprintArtifact)
146             throws SdcArtifactInstallerException {
147         List<BlueprintParserFilesConfiguration> listConfig = new ArrayList<>();
148         Yaml yaml = new Yaml();
149         Map<String, Object> templateNodes = ((Map<String, Object>) ((Map<String, Object>) yaml
150                 .load(blueprintArtifact.getDcaeBlueprint())).get("node_templates"));
151         bpmnMapping.entrySet().forEach(e -> {
152             if (templateNodes.keySet().stream().anyMatch(t -> t.contains(e.getKey()))) {
153                 listConfig.add(e.getValue());
154             }
155         });
156         if (listConfig.size() > 1) {
157             throw new SdcArtifactInstallerException(
158                     "The code does not currently support multiple MicroServices in the blueprint");
159         } else if (listConfig.isEmpty()) {
160             throw new SdcArtifactInstallerException("There is no recognized MicroService found in the blueprint");
161         }
162         logger.info("Mapping found for blueprint " + blueprintArtifact.getBlueprintArtifactName() + " is "
163                 + listConfig.get(0).getBpmnXmlFilePath());
164         return listConfig.get(0);
165     }
166
167     private static String searchForPolicyScopePrefix(BlueprintArtifact blueprintArtifact)
168             throws SdcArtifactInstallerException {
169         String policyName = null;
170         Yaml yaml = new Yaml();
171         List<String> policyNameList = new ArrayList<>();
172         Map<String, Object> templateNodes = ((Map<String, Object>) ((Map<String, Object>) yaml
173                 .load(blueprintArtifact.getDcaeBlueprint())).get("node_templates"));
174         templateNodes.entrySet().stream().filter(e -> e.getKey().contains("policy")).forEach(ef -> {
175             String filteredPolicyName = (String) ((Map<String, Object>) ((Map<String, Object>) ef.getValue())
176                     .get("properties")).get("policy_filter");
177             if (policyName != null) {
178                 policyNameList.add(filteredPolicyName);
179             } else {
180                 String inputPolicyName = (String) ((Map<String, Object>) ((Map<String, Object>) ((Map<String, Object>) ef
181                         .getValue()).get("properties")).get("policy_id")).get(GET_INPUT_BLUEPRINT_PARAM);
182                 if (inputPolicyName != null) {
183                     policyNameList.add(GET_INPUT_BLUEPRINT_PARAM);
184                 }
185             }
186         });
187         if (policyNameList.size() > 1) {
188             throw new SdcArtifactInstallerException(
189                     "The code does not currently support multiple Policy MicroServices in the blueprint");
190         } else if (policyNameList.isEmpty()) {
191             throw new SdcArtifactInstallerException(
192                     "There is no recognized Policy MicroService found in the blueprint");
193         }
194         logger.info("policyName found in blueprint " + blueprintArtifact.getBlueprintArtifactName() + " is "
195                 + policyNameList.get(0));
196         return policyNameList.get(0);
197     }
198
199     /**
200      * This call must be done when deploying the SDC notification as this call
201      * get the latest version of the artifact (version can be specified to DCAE
202      * call)
203      * 
204      * @param blueprintArtifact
205      * @return
206      * @throws IOException
207      * @throws ParseException
208      * @throws InterruptedException
209      */
210     private String queryDcaeToGetServiceTypeId(BlueprintArtifact blueprintArtifact)
211             throws IOException, ParseException, InterruptedException {
212         return dcaeInventoryService.getDcaeInformation(blueprintArtifact.getBlueprintArtifactName(),
213                 blueprintArtifact.getBlueprintInvariantServiceUuid(),
214                 blueprintArtifact.getResourceAttached().getResourceInvariantUUID()).getTypeId();
215     }
216
217     private CldsTemplate createFakeCldsTemplate(CsarHandler csar, BlueprintArtifact blueprintArtifact,
218             BlueprintParserFilesConfiguration configFiles) throws IOException, SdcArtifactInstallerException {
219         CldsTemplate template = new CldsTemplate();
220         template.setBpmnId("Sdc-Generated");
221         template.setBpmnText(
222                 IOUtils.toString(appContext.getResource(configFiles.getBpmnXmlFilePath()).getInputStream()));
223         template.setPropText(
224                 "{\"global\":[{\"name\":\"service\",\"value\":[\"" + blueprintArtifact.getDcaeBlueprint() + "\"]}]}");
225         template.setImageText(
226                 IOUtils.toString(appContext.getResource(configFiles.getSvgXmlFilePath()).getInputStream()));
227         template.setName(TEMPLATE_NAME_PREFIX
228                 + buildModelName(csar, blueprintArtifact.getResourceAttached().getResourceInstanceName()));
229         template.save(cldsDao, null);
230         logger.info("Fake Clds Template created for blueprint " + blueprintArtifact.getBlueprintArtifactName()
231                 + " with name " + template.getName());
232         return template;
233     }
234
235     private CldsModel createFakeCldsModel(CsarHandler csar, BlueprintArtifact blueprintArtifact,
236             CldsTemplate cldsTemplate, String serviceTypeId) throws SdcArtifactInstallerException {
237         try {
238             CldsModel cldsModel = new CldsModel();
239             cldsModel.setName(buildModelName(csar, blueprintArtifact.getResourceAttached().getResourceInstanceName()));
240             cldsModel.setBlueprintText(blueprintArtifact.getDcaeBlueprint());
241             cldsModel.setTemplateName(cldsTemplate.getName());
242             cldsModel.setTemplateId(cldsTemplate.getId());
243             cldsModel.setBpmnText(cldsTemplate.getBpmnText());
244             cldsModel.setTypeId(serviceTypeId);
245             cldsModel.setControlNamePrefix(CONTROL_NAME_PREFIX);
246             // We must save it otherwise object won't be created in db
247             // and proptext will always be null
248             cldsModel.setPropText("{\"global\":[]}");
249             // Must save first to have the generated id available to generate
250             // the policyId
251             cldsModel = cldsModel.save(cldsDao, null);
252             cldsModel = setModelPropText(cldsModel, blueprintArtifact, cldsTemplate);
253             logger.info("Fake Clds Model created for blueprint " + blueprintArtifact.getBlueprintArtifactName()
254                     + " with name " + cldsModel.getName());
255             return cldsModel;
256         } catch (TransformerException e) {
257             throw new SdcArtifactInstallerException("TransformerException when decoding the BpmnText", e);
258         }
259     }
260
261     private CldsModel setModelPropText(CldsModel cldsModel, BlueprintArtifact blueprintArtifact,
262             CldsTemplate cldsTemplate) throws TransformerException {
263         ModelProperties modelProp = new ModelProperties(cldsModel.getName(), cldsModel.getControlName(), "PUT", false,
264                 cldsBpmnTransformer.doXslTransformToString(cldsTemplate.getBpmnText()), "{}");
265         String inputParams = "{\"name\":\"deployParameters\",\"value\":{\n" + "\"policy_id\": \""
266                 + "AUTO_GENERATED_POLICY_ID_AT_SUBMIT" + "\"" + "}}";
267         cldsModel.setPropText("{\"global\":[{\"name\":\"service\",\"value\":[\""
268                 + blueprintArtifact.getBlueprintInvariantServiceUuid() + "\"]},{\"name\":\"vf\",\"value\":[\""
269                 + blueprintArtifact.getResourceAttached().getResourceInvariantUUID()
270                 + "\"]},{\"name\":\"actionSet\",\"value\":[\"vnfRecipe\"]},{\"name\":\"location\",\"value\":[\"DC1\"]},"
271                 + inputParams + "]}");
272         return cldsModel.save(cldsDao, null);
273     }
274 }