f407aa9449bfbc618d3a610be4e57fcc6e03c628
[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, newLoop));
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                 microService.getModelType(), csar.getPolicyModelYaml().orElse(""), false,
168                 new HashSet<>(Arrays.asList(newLoop)));
169
170             newSet.add(microServicePolicy);
171             microService.setMappedNameJpa(microServicePolicy.getName());
172         }
173         return newSet;
174     }
175
176     private JsonObject createGlobalPropertiesJson(BlueprintArtifact blueprintArtifact, Loop newLoop) {
177         JsonObject globalProperties = new JsonObject();
178         globalProperties.add("dcaeDeployParameters", getAllBlueprintParametersInJson(blueprintArtifact, newLoop));
179         return globalProperties;
180     }
181
182     private JsonObject createModelPropertiesJson(CsarHandler csar) {
183         JsonObject modelProperties = new JsonObject();
184         Gson gson = new Gson();
185         modelProperties.add("serviceDetails",
186             gson.fromJson(gson.toJson(csar.getSdcCsarHelper().getServiceMetadataAllProperties()), JsonObject.class));
187
188         JsonObject resourcesProp = new JsonObject();
189         for (SdcTypes type : SdcTypes.values()) {
190             JsonObject resourcesPropByType = new JsonObject();
191             for (NodeTemplate nodeTemplate : csar.getSdcCsarHelper().getServiceNodeTemplateBySdcType(type)) {
192                 resourcesPropByType.add(nodeTemplate.getName(), JsonUtils.GSON_JPA_MODEL
193                     .fromJson(new Gson().toJson(nodeTemplate.getMetaData().getAllProperties()), JsonObject.class));
194             }
195             resourcesProp.add(type.getValue(), resourcesPropByType);
196         }
197         modelProperties.add("resourceDetails", resourcesProp);
198         return modelProperties;
199     }
200
201     private JsonObject getAllBlueprintParametersInJson(BlueprintArtifact blueprintArtifact, Loop newLoop) {
202         JsonObject node = new JsonObject();
203         Yaml yaml = new Yaml();
204         Map<String, Object> inputsNodes = ((Map<String, Object>) ((Map<String, Object>) yaml
205             .load(blueprintArtifact.getDcaeBlueprint())).get("inputs"));
206         inputsNodes.entrySet().stream().filter(e -> !e.getKey().contains("policy_id")).forEach(elem -> {
207             Object defaultValue = ((Map<String, Object>) elem.getValue()).get("default");
208             if (defaultValue != null) {
209                 addPropertyToNode(node, elem.getKey(), defaultValue);
210             } else {
211                 node.addProperty(elem.getKey(), "");
212             }
213         });
214         // For Dublin only one micro service is expected
215         node.addProperty("policy_id", ((MicroServicePolicy) newLoop.getMicroServicePolicies().toArray()[0]).getName());
216         return node;
217     }
218
219     /**
220      * ll get the latest version of the artifact (version can be specified to DCAE
221      * call).
222      *
223      * @return The DcaeInventoryResponse object containing the dcae values
224      */
225     private DcaeInventoryResponse queryDcaeToGetServiceTypeId(BlueprintArtifact blueprintArtifact)
226         throws IOException, ParseException, InterruptedException {
227         return dcaeInventoryService.getDcaeInformation(blueprintArtifact.getBlueprintArtifactName(),
228             blueprintArtifact.getBlueprintInvariantServiceUuid(),
229             blueprintArtifact.getResourceAttached().getResourceInvariantUUID());
230     }
231
232     private void addPropertyToNode(JsonObject node, String key, Object value) {
233         if (value instanceof String) {
234             node.addProperty(key, (String) value);
235         } else if (value instanceof Number) {
236             node.addProperty(key, (Number) value);
237         } else if (value instanceof Boolean) {
238             node.addProperty(key, (Boolean) value);
239         } else if (value instanceof Character) {
240             node.addProperty(key, (Character) value);
241         } else {
242             node.addProperty(key, JsonUtils.GSON.toJson(value));
243         }
244     }
245 }