fed2c65b7b7631b4305e18d73b7d8ec778fde027
[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 Loop createLoopFromBlueprint(CsarHandler csar, BlueprintArtifact blueprintArtifact)
122         throws IOException, ParseException, InterruptedException {
123         Loop newLoop = new Loop();
124         newLoop.setBlueprint(blueprintArtifact.getDcaeBlueprint());
125         newLoop.setName(Loop.generateLoopName(csar.getSdcNotification().getServiceName(),
126             csar.getSdcNotification().getServiceVersion(),
127             blueprintArtifact.getResourceAttached().getResourceInstanceName(),
128             blueprintArtifact.getBlueprintArtifactName()));
129         newLoop.setLastComputedState(LoopState.DESIGN);
130
131         List<MicroService> microServicesChain = chainGenerator
132             .getChainOfMicroServices(blueprintParser.getMicroServices(blueprintArtifact.getDcaeBlueprint()));
133         if (microServicesChain.isEmpty()) {
134             microServicesChain = blueprintParser.fallbackToOneMicroService(blueprintArtifact.getDcaeBlueprint());
135         }
136
137         newLoop
138             .setMicroServicePolicies(createMicroServicePolicies(microServicesChain, csar, blueprintArtifact, newLoop));
139         newLoop.setOperationalPolicies(createOperationalPolicies(csar, blueprintArtifact, newLoop));
140
141         newLoop.setSvgRepresentation(svgFacade.getSvgImage(microServicesChain));
142         newLoop.setGlobalPropertiesJson(createGlobalPropertiesJson(blueprintArtifact));
143         newLoop.setModelPropertiesJson(createModelPropertiesJson(csar));
144         DcaeInventoryResponse dcaeResponse = queryDcaeToGetServiceTypeId(blueprintArtifact);
145         newLoop.setDcaeBlueprintId(dcaeResponse.getTypeId());
146         return newLoop;
147     }
148
149     private HashSet<OperationalPolicy> createOperationalPolicies(CsarHandler csar, BlueprintArtifact blueprintArtifact,
150         Loop newLoop) {
151         return new HashSet<>(Arrays.asList(new OperationalPolicy(Policy.generatePolicyName("OPERATIONAL",
152             csar.getSdcNotification().getServiceName(), csar.getSdcNotification().getServiceVersion(),
153             blueprintArtifact.getResourceAttached().getResourceInstanceName(),
154             blueprintArtifact.getBlueprintArtifactName()), newLoop, new JsonObject())));
155     }
156
157     private HashSet<MicroServicePolicy> createMicroServicePolicies(List<MicroService> microServicesChain,
158         CsarHandler csar, BlueprintArtifact blueprintArtifact, Loop newLoop) throws IOException {
159         HashSet<MicroServicePolicy> newSet = new HashSet<>();
160
161         for (MicroService microService : microServicesChain) {
162             MicroServicePolicy microServicePolicy = new MicroServicePolicy(
163                 Policy.generatePolicyName(microService.getName(), csar.getSdcNotification().getServiceName(),
164                     csar.getSdcNotification().getServiceVersion(),
165                     blueprintArtifact.getResourceAttached().getResourceInstanceName(),
166                     blueprintArtifact.getBlueprintArtifactName()),
167                 csar.getPolicyModelYaml().orElse(""), false, new HashSet<>(Arrays.asList(newLoop)));
168
169             newSet.add(microServicePolicy);
170             microService.setMappedNameJpa(microServicePolicy.getName());
171         }
172         return newSet;
173     }
174
175     private JsonObject createGlobalPropertiesJson(BlueprintArtifact blueprintArtifact) {
176         JsonObject globalProperties = new JsonObject();
177         globalProperties.add("dcaeDeployParameters", getAllBlueprintParametersInJson(blueprintArtifact));
178         return globalProperties;
179     }
180
181     private JsonObject createModelPropertiesJson(CsarHandler csar) {
182         JsonObject modelProperties = new JsonObject();
183         Gson gson = new Gson();
184         modelProperties.add("serviceDetails",
185             gson.fromJson(gson.toJson(csar.getSdcCsarHelper().getServiceMetadataAllProperties()), JsonObject.class));
186
187         JsonObject resourcesProp = new JsonObject();
188         for (SdcTypes type : SdcTypes.values()) {
189             JsonObject resourcesPropByType = new JsonObject();
190             for (NodeTemplate nodeTemplate : csar.getSdcCsarHelper().getServiceNodeTemplateBySdcType(type)) {
191                 resourcesPropByType.add(nodeTemplate.getName(), JsonUtils.GSON_JPA_MODEL
192                     .fromJson(new Gson().toJson(nodeTemplate.getMetaData().getAllProperties()), JsonObject.class));
193             }
194             resourcesProp.add(type.getValue(), resourcesPropByType);
195         }
196         modelProperties.add("resourceDetails", resourcesProp);
197         return modelProperties;
198     }
199
200     private JsonObject getAllBlueprintParametersInJson(BlueprintArtifact blueprintArtifact) {
201         JsonObject node = new JsonObject();
202         Yaml yaml = new Yaml();
203         Map<String, Object> inputsNodes = ((Map<String, Object>) ((Map<String, Object>) yaml
204             .load(blueprintArtifact.getDcaeBlueprint())).get("inputs"));
205         inputsNodes.entrySet().stream().filter(e -> !e.getKey().contains("policy_id")).forEach(elem -> {
206             Object defaultValue = ((Map<String, Object>) elem.getValue()).get("default");
207             if (defaultValue != null) {
208                 addPropertyToNode(node, elem.getKey(), defaultValue);
209             } else {
210                 node.addProperty(elem.getKey(), "");
211             }
212         });
213         node.addProperty("policy_id", "AUTO_GENERATED_POLICY_ID_AT_SUBMIT");
214         return node;
215     }
216
217     /**
218      * ll get the latest version of the artifact (version can be specified to DCAE
219      * call).
220      *
221      * @return The DcaeInventoryResponse object containing the dcae values
222      */
223     private DcaeInventoryResponse queryDcaeToGetServiceTypeId(BlueprintArtifact blueprintArtifact)
224         throws IOException, ParseException, InterruptedException {
225         return dcaeInventoryService.getDcaeInformation(blueprintArtifact.getBlueprintArtifactName(),
226             blueprintArtifact.getBlueprintInvariantServiceUuid(),
227             blueprintArtifact.getResourceAttached().getResourceInvariantUUID());
228     }
229
230     private void addPropertyToNode(JsonObject node, String key, Object value) {
231         if (value instanceof String) {
232             node.addProperty(key, (String) value);
233         } else if (value instanceof Number) {
234             node.addProperty(key, (Number) value);
235         } else if (value instanceof Boolean) {
236             node.addProperty(key, (Boolean) value);
237         } else if (value instanceof Character) {
238             node.addProperty(key, (Character) value);
239         } else {
240             node.addProperty(key, JsonUtils.GSON.toJson(value));
241         }
242     }
243 }