Merge ssl password
[clamp.git] / src / main / java / org / onap / clamp / loop / LoopCsarInstaller.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.JsonObject;
29
30 import java.io.IOException;
31 import java.util.Arrays;
32 import java.util.HashSet;
33 import java.util.List;
34 import java.util.Map;
35 import java.util.Map.Entry;
36
37 import org.json.simple.parser.ParseException;
38 import org.onap.clamp.clds.client.DcaeInventoryServices;
39 import org.onap.clamp.clds.exception.sdc.controller.SdcArtifactInstallerException;
40 import org.onap.clamp.clds.model.dcae.DcaeInventoryResponse;
41 import org.onap.clamp.clds.sdc.controller.installer.BlueprintArtifact;
42 import org.onap.clamp.clds.sdc.controller.installer.BlueprintParser;
43 import org.onap.clamp.clds.sdc.controller.installer.ChainGenerator;
44 import org.onap.clamp.clds.sdc.controller.installer.CsarHandler;
45 import org.onap.clamp.clds.sdc.controller.installer.CsarInstaller;
46 import org.onap.clamp.clds.sdc.controller.installer.MicroService;
47 import org.onap.clamp.clds.util.JsonUtils;
48 import org.onap.clamp.clds.util.drawing.SvgFacade;
49 import org.onap.clamp.loop.service.Service;
50 import org.onap.clamp.policy.Policy;
51 import org.onap.clamp.policy.microservice.MicroServicePolicy;
52 import org.onap.clamp.policy.operational.OperationalPolicy;
53 import org.onap.sdc.tosca.parser.api.IEntityDetails;
54 import org.onap.sdc.tosca.parser.elements.queries.EntityQuery;
55 import org.onap.sdc.tosca.parser.elements.queries.TopologyTemplateQuery;
56 import org.onap.sdc.tosca.parser.enums.EntityTemplateType;
57 import org.onap.sdc.tosca.parser.enums.SdcTypes;
58 import org.onap.sdc.toscaparser.api.NodeTemplate;
59 import org.onap.sdc.toscaparser.api.Property;
60 import org.springframework.beans.factory.annotation.Autowired;
61 import org.springframework.beans.factory.annotation.Qualifier;
62 import org.springframework.stereotype.Component;
63 import org.springframework.transaction.annotation.Propagation;
64 import org.springframework.transaction.annotation.Transactional;
65 import org.yaml.snakeyaml.Yaml;
66
67 /**
68  * This class will be instantiated by spring config, and used by Sdc Controller.
69  * There is no state kept by the bean. It's used to deploy the csar/notification
70  * received from SDC in DB.
71  */
72 @Component
73 @Qualifier("loopInstaller")
74 public class LoopCsarInstaller implements CsarInstaller {
75
76     private static final EELFLogger logger = EELFManager.getInstance().getLogger(LoopCsarInstaller.class);
77     public static final String CONTROL_NAME_PREFIX = "ClosedLoop-";
78     public static final String GET_INPUT_BLUEPRINT_PARAM = "get_input";
79     // This will be used later as the policy scope
80     public static final String MODEL_NAME_PREFIX = "Loop_";
81
82     @Autowired
83     LoopsRepository loopRepository;
84
85     @Autowired
86     BlueprintParser blueprintParser;
87
88     @Autowired
89     ChainGenerator chainGenerator;
90
91     @Autowired
92     DcaeInventoryServices dcaeInventoryService;
93
94     @Autowired
95     private SvgFacade svgFacade;
96
97     @Override
98     public boolean isCsarAlreadyDeployed(CsarHandler csar) throws SdcArtifactInstallerException {
99         boolean alreadyInstalled = true;
100         for (Entry<String, BlueprintArtifact> blueprint : csar.getMapOfBlueprints().entrySet()) {
101             alreadyInstalled = alreadyInstalled
102                     && loopRepository.existsById(Loop.generateLoopName(csar.getSdcNotification().getServiceName(),
103                             csar.getSdcNotification().getServiceVersion(),
104                             blueprint.getValue().getResourceAttached().getResourceInstanceName(),
105                             blueprint.getValue().getBlueprintArtifactName()));
106         }
107         return alreadyInstalled;
108     }
109
110     @Override
111     @Transactional(propagation = Propagation.REQUIRED)
112     public void installTheCsar(CsarHandler csar) throws SdcArtifactInstallerException, InterruptedException {
113         try {
114             logger.info("Installing the CSAR " + csar.getFilePath());
115             for (Entry<String, BlueprintArtifact> blueprint : csar.getMapOfBlueprints().entrySet()) {
116                 logger.info("Processing blueprint " + blueprint.getValue().getBlueprintArtifactName());
117                 loopRepository.save(createLoopFromBlueprint(csar, blueprint.getValue()));
118             }
119             logger.info("Successfully installed the CSAR " + csar.getFilePath());
120         } catch (IOException e) {
121             throw new SdcArtifactInstallerException("Exception caught during the Csar installation in database", e);
122         } catch (ParseException e) {
123             throw new SdcArtifactInstallerException("Exception caught during the Dcae query to get ServiceTypeId", e);
124         }
125     }
126
127     private Loop createLoopFromBlueprint(CsarHandler csar, BlueprintArtifact blueprintArtifact)
128             throws IOException, ParseException, InterruptedException {
129         Loop newLoop = new Loop();
130         newLoop.setBlueprint(blueprintArtifact.getDcaeBlueprint());
131         newLoop.setName(Loop.generateLoopName(csar.getSdcNotification().getServiceName(),
132                 csar.getSdcNotification().getServiceVersion(),
133                 blueprintArtifact.getResourceAttached().getResourceInstanceName(),
134                 blueprintArtifact.getBlueprintArtifactName()));
135         newLoop.setLastComputedState(LoopState.DESIGN);
136
137         List<MicroService> microServicesChain = chainGenerator
138                 .getChainOfMicroServices(blueprintParser.getMicroServices(blueprintArtifact.getDcaeBlueprint()));
139         if (microServicesChain.isEmpty()) {
140             microServicesChain = blueprintParser.fallbackToOneMicroService(blueprintArtifact.getDcaeBlueprint());
141         }
142         newLoop.setModelService(createServiceModel(csar));
143         newLoop.setMicroServicePolicies(
144                 createMicroServicePolicies(microServicesChain, csar, blueprintArtifact, newLoop));
145         newLoop.setOperationalPolicies(createOperationalPolicies(csar, blueprintArtifact, newLoop));
146
147         newLoop.setSvgRepresentation(svgFacade.getSvgImage(microServicesChain));
148         newLoop.setGlobalPropertiesJson(createGlobalPropertiesJson(blueprintArtifact, newLoop));
149
150         DcaeInventoryResponse dcaeResponse = queryDcaeToGetServiceTypeId(blueprintArtifact);
151         newLoop.setDcaeBlueprintId(dcaeResponse.getTypeId());
152         return newLoop;
153     }
154
155     private HashSet<OperationalPolicy> createOperationalPolicies(CsarHandler csar, BlueprintArtifact blueprintArtifact,
156             Loop newLoop) {
157         return new HashSet<>(Arrays.asList(new OperationalPolicy(Policy.generatePolicyName("OPERATIONAL",
158                 csar.getSdcNotification().getServiceName(), csar.getSdcNotification().getServiceVersion(),
159                 blueprintArtifact.getResourceAttached().getResourceInstanceName(),
160                 blueprintArtifact.getBlueprintArtifactName()), newLoop, new JsonObject())));
161     }
162
163     private HashSet<MicroServicePolicy> createMicroServicePolicies(List<MicroService> microServicesChain,
164             CsarHandler csar, BlueprintArtifact blueprintArtifact, Loop newLoop) throws IOException {
165         HashSet<MicroServicePolicy> newSet = new HashSet<>();
166
167         for (MicroService microService : microServicesChain) {
168             MicroServicePolicy microServicePolicy = new MicroServicePolicy(
169                     Policy.generatePolicyName(microService.getName(), csar.getSdcNotification().getServiceName(),
170                             csar.getSdcNotification().getServiceVersion(),
171                             blueprintArtifact.getResourceAttached().getResourceInstanceName(),
172                             blueprintArtifact.getBlueprintArtifactName()),
173                     microService.getModelType(), csar.getPolicyModelYaml().orElse(""), false,
174                     new HashSet<>(Arrays.asList(newLoop)));
175
176             newSet.add(microServicePolicy);
177             microService.setMappedNameJpa(microServicePolicy.getName());
178         }
179         return newSet;
180     }
181
182     private JsonObject createGlobalPropertiesJson(BlueprintArtifact blueprintArtifact, Loop newLoop) {
183         JsonObject globalProperties = new JsonObject();
184         globalProperties.add("dcaeDeployParameters", getAllBlueprintParametersInJson(blueprintArtifact, newLoop));
185         return globalProperties;
186     }
187
188     private static JsonObject createVfModuleProperties(CsarHandler csar) {
189         JsonObject vfModuleProps = new JsonObject();
190         // Loop on all Groups defined in the service (VFModule entries type:
191         // org.openecomp.groups.VfModule)
192         for (IEntityDetails entity : csar.getSdcCsarHelper().getEntity(
193                 EntityQuery.newBuilder(EntityTemplateType.GROUP).build(),
194                 TopologyTemplateQuery.newBuilder(SdcTypes.SERVICE).build(), false)) {
195             // Get all metadata info
196             JsonObject allVfProps = (JsonObject) JsonUtils.GSON.toJsonTree(entity.getMetadata().getAllProperties());
197             vfModuleProps.add(entity.getMetadata().getAllProperties().get("vfModuleModelName"), allVfProps);
198             // now append the properties section so that we can also have isBase,
199             // volume_group, etc ... fields under the VFmodule name
200             for (Entry<String, Property> additionalProp : entity.getProperties().entrySet()) {
201                 allVfProps.add(additionalProp.getValue().getName(),
202                         JsonUtils.GSON.toJsonTree(additionalProp.getValue().getValue()));
203             }
204         }
205         return vfModuleProps;
206     }
207
208     private static JsonObject createServicePropertiesByType(CsarHandler csar) {
209         JsonObject resourcesProp = new JsonObject();
210         // Iterate on all types defined in the tosca lib
211         for (SdcTypes type : SdcTypes.values()) {
212             JsonObject resourcesPropByType = new JsonObject();
213             // For each type, get the metadata of each nodetemplate
214             for (NodeTemplate nodeTemplate : csar.getSdcCsarHelper().getServiceNodeTemplateBySdcType(type)) {
215                 resourcesPropByType.add(nodeTemplate.getName(),
216                         JsonUtils.GSON.toJsonTree(nodeTemplate.getMetaData().getAllProperties()));
217             }
218             resourcesProp.add(type.getValue(), resourcesPropByType);
219         }
220         return resourcesProp;
221     }
222
223     private Service createServiceModel(CsarHandler csar) {
224         JsonObject serviceDetails = JsonUtils.GSON.fromJson(
225                 JsonUtils.GSON.toJson(csar.getSdcCsarHelper().getServiceMetadataAllProperties()), JsonObject.class);
226
227         // Add properties details for each type, VfModule, VF, VFC, ....
228         JsonObject resourcesProp = createServicePropertiesByType(csar);
229         resourcesProp.add("VFModule", createVfModuleProperties(csar));
230
231         Service modelService = new Service(serviceDetails, resourcesProp);
232
233         return modelService;
234     }
235
236     private JsonObject getAllBlueprintParametersInJson(BlueprintArtifact blueprintArtifact, Loop newLoop) {
237         JsonObject node = new JsonObject();
238         Yaml yaml = new Yaml();
239         Map<String, Object> inputsNodes = ((Map<String, Object>) ((Map<String, Object>) yaml
240                 .load(blueprintArtifact.getDcaeBlueprint())).get("inputs"));
241         inputsNodes.entrySet().stream().filter(e -> !e.getKey().contains("policy_id")).forEach(elem -> {
242             Object defaultValue = ((Map<String, Object>) elem.getValue()).get("default");
243             if (defaultValue != null) {
244                 addPropertyToNode(node, elem.getKey(), defaultValue);
245             } else {
246                 node.addProperty(elem.getKey(), "");
247             }
248         });
249         // For Dublin only one micro service is expected
250         node.addProperty("policy_id", ((MicroServicePolicy) newLoop.getMicroServicePolicies().toArray()[0]).getName());
251         return node;
252     }
253
254     /**
255      * ll get the latest version of the artifact (version can be specified to DCAE
256      * call).
257      *
258      * @return The DcaeInventoryResponse object containing the dcae values
259      */
260     private DcaeInventoryResponse queryDcaeToGetServiceTypeId(BlueprintArtifact blueprintArtifact)
261             throws IOException, ParseException, InterruptedException {
262         return dcaeInventoryService.getDcaeInformation(blueprintArtifact.getBlueprintArtifactName(),
263                 blueprintArtifact.getBlueprintInvariantServiceUuid(),
264                 blueprintArtifact.getResourceAttached().getResourceInvariantUUID());
265     }
266
267     private void addPropertyToNode(JsonObject node, String key, Object value) {
268         if (value instanceof String) {
269             node.addProperty(key, (String) value);
270         } else if (value instanceof Number) {
271             node.addProperty(key, (Number) value);
272         } else if (value instanceof Boolean) {
273             node.addProperty(key, (Boolean) value);
274         } else if (value instanceof Character) {
275             node.addProperty(key, (Character) value);
276         } else {
277             node.addProperty(key, JsonUtils.GSON.toJson(value));
278         }
279     }
280 }