Draft of op policy
[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.policy.PolicyModelException;
40 import org.onap.clamp.clds.exception.sdc.controller.SdcArtifactInstallerException;
41 import org.onap.clamp.clds.model.dcae.DcaeInventoryResponse;
42 import org.onap.clamp.clds.sdc.controller.installer.BlueprintArtifact;
43 import org.onap.clamp.clds.sdc.controller.installer.BlueprintParser;
44 import org.onap.clamp.clds.sdc.controller.installer.ChainGenerator;
45 import org.onap.clamp.clds.sdc.controller.installer.CsarHandler;
46 import org.onap.clamp.clds.sdc.controller.installer.CsarInstaller;
47 import org.onap.clamp.clds.sdc.controller.installer.MicroService;
48 import org.onap.clamp.clds.util.JsonUtils;
49 import org.onap.clamp.clds.util.drawing.SvgFacade;
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)
113             throws SdcArtifactInstallerException, InterruptedException, PolicyModelException {
114         try {
115             logger.info("Installing the CSAR " + csar.getFilePath());
116             for (Entry<String, BlueprintArtifact> blueprint : csar.getMapOfBlueprints().entrySet()) {
117                 logger.info("Processing blueprint " + blueprint.getValue().getBlueprintArtifactName());
118                 loopRepository.save(createLoopFromBlueprint(csar, blueprint.getValue()));
119             }
120             logger.info("Successfully installed the CSAR " + csar.getFilePath());
121         } catch (IOException e) {
122             throw new SdcArtifactInstallerException("Exception caught during the Csar installation in database", e);
123         } catch (ParseException e) {
124             throw new SdcArtifactInstallerException("Exception caught during the Dcae query to get ServiceTypeId", e);
125         }
126     }
127
128     private Loop createLoopFromBlueprint(CsarHandler csar, BlueprintArtifact blueprintArtifact)
129             throws IOException, ParseException, InterruptedException {
130         Loop newLoop = new Loop();
131         newLoop.setBlueprint(blueprintArtifact.getDcaeBlueprint());
132         newLoop.setName(Loop.generateLoopName(csar.getSdcNotification().getServiceName(),
133                 csar.getSdcNotification().getServiceVersion(),
134                 blueprintArtifact.getResourceAttached().getResourceInstanceName(),
135                 blueprintArtifact.getBlueprintArtifactName()));
136         newLoop.setLastComputedState(LoopState.DESIGN);
137
138         List<MicroService> microServicesChain = chainGenerator
139                 .getChainOfMicroServices(blueprintParser.getMicroServices(blueprintArtifact.getDcaeBlueprint()));
140         if (microServicesChain.isEmpty()) {
141             microServicesChain = blueprintParser.fallbackToOneMicroService(blueprintArtifact.getDcaeBlueprint());
142         }
143         newLoop.setModelPropertiesJson(createModelPropertiesJson(csar));
144         newLoop.setMicroServicePolicies(
145                 createMicroServicePolicies(microServicesChain, csar, blueprintArtifact, newLoop));
146         newLoop.setOperationalPolicies(createOperationalPolicies(csar, blueprintArtifact, newLoop));
147
148         newLoop.setSvgRepresentation(svgFacade.getSvgImage(microServicesChain));
149         newLoop.setGlobalPropertiesJson(createGlobalPropertiesJson(blueprintArtifact, newLoop));
150
151         DcaeInventoryResponse dcaeResponse = queryDcaeToGetServiceTypeId(blueprintArtifact);
152         newLoop.setDcaeBlueprintId(dcaeResponse.getTypeId());
153         return newLoop;
154     }
155
156     private HashSet<OperationalPolicy> createOperationalPolicies(CsarHandler csar, BlueprintArtifact blueprintArtifact,
157             Loop newLoop) {
158         return new HashSet<>(Arrays.asList(new OperationalPolicy(Policy.generatePolicyName("OPERATIONAL",
159                 csar.getSdcNotification().getServiceName(), csar.getSdcNotification().getServiceVersion(),
160                 blueprintArtifact.getResourceAttached().getResourceInstanceName(),
161                 blueprintArtifact.getBlueprintArtifactName()), newLoop, new JsonObject())));
162     }
163
164     private HashSet<MicroServicePolicy> createMicroServicePolicies(List<MicroService> microServicesChain,
165             CsarHandler csar, BlueprintArtifact blueprintArtifact, Loop newLoop) throws IOException {
166         HashSet<MicroServicePolicy> newSet = new HashSet<>();
167
168         for (MicroService microService : microServicesChain) {
169             MicroServicePolicy microServicePolicy = new MicroServicePolicy(
170                     Policy.generatePolicyName(microService.getName(), csar.getSdcNotification().getServiceName(),
171                             csar.getSdcNotification().getServiceVersion(),
172                             blueprintArtifact.getResourceAttached().getResourceInstanceName(),
173                             blueprintArtifact.getBlueprintArtifactName()),
174                     microService.getModelType(), csar.getPolicyModelYaml().orElse(""), false,
175                     new HashSet<>(Arrays.asList(newLoop)));
176
177             newSet.add(microServicePolicy);
178             microService.setMappedNameJpa(microServicePolicy.getName());
179         }
180         return newSet;
181     }
182
183     private JsonObject createGlobalPropertiesJson(BlueprintArtifact blueprintArtifact, Loop newLoop) {
184         JsonObject globalProperties = new JsonObject();
185         globalProperties.add("dcaeDeployParameters", getAllBlueprintParametersInJson(blueprintArtifact, newLoop));
186         return globalProperties;
187     }
188
189     private static JsonObject createVfModuleProperties(CsarHandler csar) {
190         JsonObject vfModuleProps = new JsonObject();
191         // Loop on all Groups defined in the service (VFModule entries type:
192         // org.openecomp.groups.VfModule)
193         for (IEntityDetails entity : csar.getSdcCsarHelper().getEntity(
194                 EntityQuery.newBuilder(EntityTemplateType.GROUP).build(),
195                 TopologyTemplateQuery.newBuilder(SdcTypes.SERVICE).build(), false)) {
196             // Get all metadata info
197             JsonObject allVfProps = (JsonObject) JsonUtils.GSON.toJsonTree(entity.getMetadata().getAllProperties());
198             vfModuleProps.add(entity.getMetadata().getAllProperties().get("vfModuleModelName"), allVfProps);
199             // now append the properties section so that we can also have isBase,
200             // volume_group, etc ... fields under the VFmodule name
201             for (Entry<String, Property> additionalProp : entity.getProperties().entrySet()) {
202                 allVfProps.add(additionalProp.getValue().getName(),
203                         JsonUtils.GSON.toJsonTree(additionalProp.getValue().getValue()));
204             }
205         }
206         return vfModuleProps;
207     }
208
209     private static JsonObject createServicePropertiesByType(CsarHandler csar) {
210         JsonObject resourcesProp = new JsonObject();
211         // Iterate on all types defined in the tosca lib
212         for (SdcTypes type : SdcTypes.values()) {
213             JsonObject resourcesPropByType = new JsonObject();
214             // For each type, get the metadata of each nodetemplate
215             for (NodeTemplate nodeTemplate : csar.getSdcCsarHelper().getServiceNodeTemplateBySdcType(type)) {
216                 resourcesPropByType.add(nodeTemplate.getName(),
217                         JsonUtils.GSON.toJsonTree(nodeTemplate.getMetaData().getAllProperties()));
218             }
219             resourcesProp.add(type.getValue(), resourcesPropByType);
220         }
221         return resourcesProp;
222     }
223
224     private static JsonObject createModelPropertiesJson(CsarHandler csar) {
225         JsonObject modelProperties = new JsonObject();
226         // Add service details
227         modelProperties.add("serviceDetails", JsonUtils.GSON.fromJson(
228                 JsonUtils.GSON.toJson(csar.getSdcCsarHelper().getServiceMetadataAllProperties()), JsonObject.class));
229         // Add properties details for each type, VfModule, VF, VFC, ....
230         JsonObject resourcesProp = createServicePropertiesByType(csar);
231         resourcesProp.add("VFModule", createVfModuleProperties(csar));
232         modelProperties.add("resourceDetails", resourcesProp);
233         return modelProperties;
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 }