Add svg support
[clamp.git] / src / main / java / org / onap / clamp / loop / CsarInstallerImpl.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP CLAMP
4  * ================================================================================
5  * Copyright (C) 2019 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.loop;
25
26 import com.att.eelf.configuration.EELFLogger;
27 import com.att.eelf.configuration.EELFManager;
28 import com.google.gson.Gson;
29 import com.google.gson.JsonObject;
30
31 import java.io.IOException;
32 import java.util.Arrays;
33 import java.util.HashSet;
34 import java.util.List;
35 import java.util.Map;
36 import java.util.Map.Entry;
37
38 import org.json.simple.parser.ParseException;
39 import org.onap.clamp.clds.client.DcaeInventoryServices;
40 import org.onap.clamp.clds.exception.policy.PolicyModelException;
41 import org.onap.clamp.clds.exception.sdc.controller.SdcArtifactInstallerException;
42 import org.onap.clamp.clds.model.dcae.DcaeInventoryResponse;
43 import org.onap.clamp.clds.sdc.controller.installer.BlueprintArtifact;
44 import org.onap.clamp.clds.sdc.controller.installer.BlueprintParser;
45 import org.onap.clamp.clds.sdc.controller.installer.ChainGenerator;
46 import org.onap.clamp.clds.sdc.controller.installer.CsarHandler;
47 import org.onap.clamp.clds.sdc.controller.installer.CsarInstaller;
48 import org.onap.clamp.clds.sdc.controller.installer.MicroService;
49 import org.onap.clamp.clds.util.JsonUtils;
50 import org.onap.clamp.clds.util.drawing.SvgFacade;
51 import org.onap.clamp.policy.Policy;
52 import org.onap.clamp.policy.microservice.MicroServicePolicy;
53 import org.onap.clamp.policy.operational.OperationalPolicy;
54 import org.onap.sdc.tosca.parser.enums.SdcTypes;
55 import org.onap.sdc.toscaparser.api.NodeTemplate;
56 import org.springframework.beans.factory.annotation.Autowired;
57 import org.springframework.transaction.annotation.Propagation;
58 import org.springframework.transaction.annotation.Transactional;
59 import org.yaml.snakeyaml.Yaml;
60
61 /**
62  * This class will be instantiated by spring config, and used by Sdc Controller.
63  * There is no state kept by the bean. It's used to deploy the csar/notification
64  * received from SDC in DB.
65  */
66 public class CsarInstallerImpl implements CsarInstaller {
67
68     private static final EELFLogger logger = EELFManager.getInstance().getLogger(CsarInstallerImpl.class);
69     public static final String TEMPLATE_NAME_PREFIX = "DCAE-Designer-Template-";
70     public static final String CONTROL_NAME_PREFIX = "ClosedLoop-";
71     public static final String GET_INPUT_BLUEPRINT_PARAM = "get_input";
72     // This will be used later as the policy scope
73     public static final String MODEL_NAME_PREFIX = "Loop_";
74
75     @Autowired
76     LoopsRepository loopRepository;
77
78     @Autowired
79     BlueprintParser blueprintParser;
80
81     @Autowired
82     ChainGenerator chainGenerator;
83
84     @Autowired
85     DcaeInventoryServices dcaeInventoryService;
86
87     @Autowired
88     private SvgFacade svgFacade;
89
90     @Override
91     public boolean isCsarAlreadyDeployed(CsarHandler csar) throws SdcArtifactInstallerException {
92         boolean alreadyInstalled = true;
93         for (Entry<String, BlueprintArtifact> blueprint : csar.getMapOfBlueprints().entrySet()) {
94             alreadyInstalled = alreadyInstalled
95                 && loopRepository.existsById(Loop.generateLoopName(csar.getSdcNotification().getServiceName(),
96                     csar.getSdcNotification().getServiceVersion(),
97                     blueprint.getValue().getResourceAttached().getResourceInstanceName(),
98                     blueprint.getValue().getBlueprintArtifactName()));
99         }
100         return alreadyInstalled;
101     }
102
103     @Override
104     @Transactional(propagation = Propagation.REQUIRED)
105     public void installTheCsar(CsarHandler csar)
106         throws SdcArtifactInstallerException, InterruptedException, PolicyModelException {
107         try {
108             logger.info("Installing the CSAR " + csar.getFilePath());
109             for (Entry<String, BlueprintArtifact> blueprint : csar.getMapOfBlueprints().entrySet()) {
110                 logger.info("Processing blueprint " + blueprint.getValue().getBlueprintArtifactName());
111                 loopRepository.save(createLoopFromBlueprint(csar, blueprint.getValue()));
112             }
113             logger.info("Successfully installed the CSAR " + csar.getFilePath());
114         } catch (IOException e) {
115             throw new SdcArtifactInstallerException("Exception caught during the Csar installation in database", e);
116         } catch (ParseException e) {
117             throw new SdcArtifactInstallerException("Exception caught during the Dcae query to get ServiceTypeId", e);
118         }
119     }
120
121     private String getSvgInLoop(BlueprintArtifact blueprintArtifact) {
122         List<MicroService> microServicesChain = chainGenerator
123             .getChainOfMicroServices(blueprintParser.getMicroServices(blueprintArtifact.getDcaeBlueprint()));
124         if (microServicesChain.isEmpty()) {
125             microServicesChain = blueprintParser.fallbackToOneMicroService(blueprintArtifact.getDcaeBlueprint());
126         }
127         return svgFacade.getSvgImage(microServicesChain);
128
129     }
130
131     private Loop createLoopFromBlueprint(CsarHandler csar, BlueprintArtifact blueprintArtifact)
132         throws IOException, ParseException, InterruptedException {
133         Loop newLoop = new Loop();
134         newLoop.setBlueprint(blueprintArtifact.getDcaeBlueprint());
135         newLoop.setName(Loop.generateLoopName(csar.getSdcNotification().getServiceName(),
136             csar.getSdcNotification().getServiceVersion(),
137             blueprintArtifact.getResourceAttached().getResourceInstanceName(),
138             blueprintArtifact.getBlueprintArtifactName()));
139         newLoop.setLastComputedState(LoopState.DESIGN);
140         newLoop.setMicroServicePolicies(createMicroServicePolicies(csar, blueprintArtifact, newLoop));
141         newLoop.setOperationalPolicies(createOperationalPolicies(csar, blueprintArtifact, newLoop));
142
143         newLoop.setSvgRepresentation(getSvgInLoop(blueprintArtifact));
144         newLoop.setGlobalPropertiesJson(createGlobalPropertiesJson(blueprintArtifact));
145         newLoop.setModelPropertiesJson(createModelPropertiesJson(csar));
146         DcaeInventoryResponse dcaeResponse = queryDcaeToGetServiceTypeId(blueprintArtifact);
147         newLoop.setDcaeBlueprintId(dcaeResponse.getTypeId());
148         return newLoop;
149     }
150
151     private HashSet<OperationalPolicy> createOperationalPolicies(CsarHandler csar, BlueprintArtifact blueprintArtifact,
152         Loop newLoop) {
153         return new HashSet<>(Arrays.asList(new OperationalPolicy(Policy.generatePolicyName("OPERATIONAL",
154             csar.getSdcNotification().getServiceName(), csar.getSdcNotification().getServiceVersion(),
155             blueprintArtifact.getResourceAttached().getResourceInstanceName(),
156             blueprintArtifact.getBlueprintArtifactName()), newLoop, new JsonObject())));
157     }
158
159     private HashSet<MicroServicePolicy> createMicroServicePolicies(CsarHandler csar,
160         BlueprintArtifact blueprintArtifact, Loop newLoop) throws IOException {
161         HashSet<MicroServicePolicy> newSet = new HashSet<>();
162         List<MicroService> microServicesChain = chainGenerator
163             .getChainOfMicroServices(blueprintParser.getMicroServices(blueprintArtifact.getDcaeBlueprint()));
164         if (microServicesChain.isEmpty()) {
165             microServicesChain = blueprintParser.fallbackToOneMicroService(blueprintArtifact.getDcaeBlueprint());
166         }
167         for (MicroService microService : microServicesChain) {
168             newSet.add(new MicroServicePolicy(
169                 Policy.generatePolicyName(microService.getName(), csar.getSdcNotification().getServiceName(),
170                     csar.getSdcNotification().getServiceVersion(),
171                     blueprintArtifact.getResourceAttached().getResourceInstanceName(),
172                     blueprintArtifact.getBlueprintArtifactName()),
173                 csar.getPolicyModelYaml().orElse(""), false, new HashSet<>(Arrays.asList(newLoop))));
174         }
175         return newSet;
176     }
177
178     private JsonObject createGlobalPropertiesJson(BlueprintArtifact blueprintArtifact) {
179         JsonObject globalProperties = new JsonObject();
180         globalProperties.add("dcaeDeployParameters", getAllBlueprintParametersInJson(blueprintArtifact));
181         return globalProperties;
182
183     }
184
185     private JsonObject createModelPropertiesJson(CsarHandler csar) {
186         JsonObject modelProperties = new JsonObject();
187         Gson gson = new Gson();
188         modelProperties.add("serviceDetails",
189             gson.fromJson(gson.toJson(csar.getSdcCsarHelper().getServiceMetadataAllProperties()), JsonObject.class));
190
191         JsonObject resourcesProp = new JsonObject();
192         for (SdcTypes type : SdcTypes.values()) {
193             JsonObject resourcesPropByType = new JsonObject();
194             for (NodeTemplate nodeTemplate : csar.getSdcCsarHelper().getServiceNodeTemplateBySdcType(type)) {
195                 resourcesPropByType.add(nodeTemplate.getName(), JsonUtils.GSON_JPA_MODEL
196                     .fromJson(new Gson().toJson(nodeTemplate.getMetaData().getAllProperties()), JsonObject.class));
197             }
198             resourcesProp.add(type.getValue(), resourcesPropByType);
199         }
200         modelProperties.add("resourceDetails", resourcesProp);
201         return modelProperties;
202     }
203
204     private JsonObject getAllBlueprintParametersInJson(BlueprintArtifact blueprintArtifact) {
205         JsonObject node = new JsonObject();
206         Yaml yaml = new Yaml();
207         Map<String, Object> inputsNodes = ((Map<String, Object>) ((Map<String, Object>) yaml
208             .load(blueprintArtifact.getDcaeBlueprint())).get("inputs"));
209         inputsNodes.entrySet().stream().filter(e -> !e.getKey().contains("policy_id")).forEach(elem -> {
210             Object defaultValue = ((Map<String, Object>) elem.getValue()).get("default");
211             if (defaultValue != null) {
212                 addPropertyToNode(node, elem.getKey(), defaultValue);
213             } else {
214                 node.addProperty(elem.getKey(), "");
215             }
216         });
217         node.addProperty("policy_id", "AUTO_GENERATED_POLICY_ID_AT_SUBMIT");
218         return node;
219     }
220
221     /**
222      * ll get the latest version of the artifact (version can be specified to DCAE
223      * call)
224      *
225      * @return The DcaeInventoryResponse object containing the dcae values
226      */
227     private DcaeInventoryResponse queryDcaeToGetServiceTypeId(BlueprintArtifact blueprintArtifact)
228         throws IOException, ParseException, InterruptedException {
229         return dcaeInventoryService.getDcaeInformation(blueprintArtifact.getBlueprintArtifactName(),
230             blueprintArtifact.getBlueprintInvariantServiceUuid(),
231             blueprintArtifact.getResourceAttached().getResourceInvariantUUID());
232     }
233
234     private void addPropertyToNode(JsonObject node, String key, Object value) {
235         if (value instanceof String) {
236             node.addProperty(key, (String) value);
237         } else if (value instanceof Number) {
238             node.addProperty(key, (Number) value);
239         } else if (value instanceof Boolean) {
240             node.addProperty(key, (Boolean) value);
241         } else if (value instanceof Character) {
242             node.addProperty(key, (Character) value);
243         } else {
244             node.addProperty(key, JsonUtils.GSON.toJson(value));
245         }
246     }
247 }