Operational policy modification
[clamp.git] / src / main / java / org / onap / clamp / loop / CsarInstaller.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 java.io.IOException;
29 import java.util.HashSet;
30 import java.util.List;
31 import java.util.Map.Entry;
32 import org.json.simple.parser.ParseException;
33 import org.onap.clamp.clds.client.DcaeInventoryServices;
34 import org.onap.clamp.clds.client.PolicyEngineServices;
35 import org.onap.clamp.clds.exception.sdc.controller.BlueprintParserException;
36 import org.onap.clamp.clds.exception.sdc.controller.SdcArtifactInstallerException;
37 import org.onap.clamp.clds.model.dcae.DcaeInventoryResponse;
38 import org.onap.clamp.clds.sdc.controller.installer.BlueprintArtifact;
39 import org.onap.clamp.clds.sdc.controller.installer.BlueprintMicroService;
40 import org.onap.clamp.clds.sdc.controller.installer.BlueprintParser;
41 import org.onap.clamp.clds.sdc.controller.installer.ChainGenerator;
42 import org.onap.clamp.clds.sdc.controller.installer.CsarHandler;
43 import org.onap.clamp.loop.service.CsarServiceInstaller;
44 import org.onap.clamp.loop.service.Service;
45 import org.onap.clamp.loop.template.LoopElementModel;
46 import org.onap.clamp.loop.template.LoopTemplate;
47 import org.onap.clamp.loop.template.LoopTemplatesRepository;
48 import org.onap.clamp.loop.template.PolicyModel;
49 import org.onap.clamp.loop.template.PolicyModelId;
50 import org.onap.clamp.loop.template.PolicyModelsRepository;
51 import org.springframework.beans.factory.annotation.Autowired;
52 import org.springframework.beans.factory.annotation.Qualifier;
53 import org.springframework.stereotype.Component;
54
55 /**
56  * This class will be instantiated by spring config, and used by Sdc Controller.
57  * There is no state kept by the bean. It's used to deploy the csar/notification
58  * received from SDC in DB.
59  */
60 @Component
61 @Qualifier("csarInstaller")
62 public class CsarInstaller {
63
64     private static final EELFLogger logger = EELFManager.getInstance().getLogger(CsarInstaller.class);
65
66     @Autowired
67     private PolicyModelsRepository policyModelsRepository;
68
69     @Autowired
70     private LoopTemplatesRepository loopTemplatesRepository;
71
72     @Autowired
73     private ChainGenerator chainGenerator;
74
75     @Autowired
76     private DcaeInventoryServices dcaeInventoryService;
77
78     @Autowired
79     private CsarServiceInstaller csarServiceInstaller;
80
81     @Autowired
82     private PolicyEngineServices policyEngineServices;
83
84     /**
85      * Verify whether Csar is deployed.
86      *
87      * @param csar The Csar Handler
88      * @return The flag indicating whether Csar is deployed
89      * @throws SdcArtifactInstallerException The SdcArtifactInstallerException
90      */
91     public boolean isCsarAlreadyDeployed(CsarHandler csar) throws SdcArtifactInstallerException {
92         boolean alreadyInstalled = csarServiceInstaller.isServiceAlreadyDeployed(csar);
93
94         for (Entry<String, BlueprintArtifact> blueprint : csar.getMapOfBlueprints().entrySet()) {
95             alreadyInstalled = alreadyInstalled
96                     && loopTemplatesRepository.existsById(LoopTemplate.generateLoopTemplateName(
97                     csar.getSdcNotification().getServiceName(), csar.getSdcNotification().getServiceVersion(),
98                     blueprint.getValue().getResourceAttached().getResourceInstanceName(),
99                     blueprint.getValue().getBlueprintArtifactName()));
100         }
101         return alreadyInstalled;
102     }
103
104     /**
105      * Install the service and loop templates from the csar.
106      *
107      * @param csar The Csar Handler
108      * @throws SdcArtifactInstallerException The SdcArtifactInstallerException
109      * @throws InterruptedException          The InterruptedException
110      * @throws BlueprintParserException      In case of issues with the blueprint
111      *                                       parsing
112      */
113     public void installTheCsar(CsarHandler csar)
114             throws SdcArtifactInstallerException, InterruptedException, BlueprintParserException {
115         logger.info("Installing the CSAR " + csar.getFilePath());
116         installTheLoopTemplates(csar, csarServiceInstaller.installTheService(csar));
117         logger.info("Successfully installed the CSAR " + csar.getFilePath());
118     }
119
120     /**
121      * Install the loop templates from the csar.
122      *
123      * @param csar    The Csar Handler
124      * @param service The service object that is related to the loop
125      * @throws SdcArtifactInstallerException The SdcArtifactInstallerException
126      * @throws InterruptedException          The InterruptedException
127      * @throws BlueprintParserException      In case of issues with the blueprint
128      *                                       parsing
129      */
130     public void installTheLoopTemplates(CsarHandler csar, Service service)
131             throws SdcArtifactInstallerException, InterruptedException, BlueprintParserException {
132         try {
133             logger.info("Installing the Loops");
134             for (Entry<String, BlueprintArtifact> blueprint : csar.getMapOfBlueprints().entrySet()) {
135                 logger.info("Processing blueprint " + blueprint.getValue().getBlueprintArtifactName());
136                 loopTemplatesRepository.save(createLoopTemplateFromBlueprint(csar, blueprint.getValue(), service));
137             }
138             logger.info("Successfully installed the Loops ");
139         } catch (IOException e) {
140             throw new SdcArtifactInstallerException("Exception caught during the Loop installation in database", e);
141         } catch (ParseException e) {
142             throw new SdcArtifactInstallerException("Exception caught during the Dcae query to get ServiceTypeId", e);
143         }
144     }
145
146     private LoopTemplate createLoopTemplateFromBlueprint(CsarHandler csar, BlueprintArtifact blueprintArtifact,
147                                                          Service service)
148             throws IOException, ParseException, InterruptedException, BlueprintParserException {
149         LoopTemplate newLoopTemplate = new LoopTemplate();
150         newLoopTemplate.setBlueprint(blueprintArtifact.getDcaeBlueprint());
151         newLoopTemplate.setName(LoopTemplate.generateLoopTemplateName(csar.getSdcNotification().getServiceName(),
152                 csar.getSdcNotification().getServiceVersion(),
153                 blueprintArtifact.getResourceAttached().getResourceInstanceName(),
154                 blueprintArtifact.getBlueprintArtifactName()));
155         List<BlueprintMicroService> microServicesChain = chainGenerator
156                 .getChainOfMicroServices(BlueprintParser.getMicroServices(blueprintArtifact.getDcaeBlueprint()));
157         if (microServicesChain.isEmpty()) {
158             microServicesChain = BlueprintParser.fallbackToOneMicroService();
159         }
160         newLoopTemplate.setModelService(service);
161         newLoopTemplate.addLoopElementModels(createMicroServiceModels(microServicesChain));
162         newLoopTemplate.setMaximumInstancesAllowed(0);
163         DcaeInventoryResponse dcaeResponse = queryDcaeToGetServiceTypeId(blueprintArtifact);
164         newLoopTemplate.setDcaeBlueprintId(dcaeResponse.getTypeId());
165         return newLoopTemplate;
166     }
167
168     private HashSet<LoopElementModel> createMicroServiceModels(List<BlueprintMicroService> microServicesChain)
169             throws InterruptedException {
170         HashSet<LoopElementModel> newSet = new HashSet<>();
171         for (BlueprintMicroService microService : microServicesChain) {
172             LoopElementModel loopElementModel =
173                     new LoopElementModel(microService.getModelType(), LoopElementModel.MICRO_SERVICE_TYPE,
174                             null);
175             newSet.add(loopElementModel);
176             loopElementModel.addPolicyModel(getPolicyModel(microService));
177         }
178         return newSet;
179     }
180
181     private PolicyModel getPolicyModel(BlueprintMicroService microService) throws InterruptedException {
182         return policyModelsRepository
183                 .findById(new PolicyModelId(microService.getModelType(), microService.getModelVersion()))
184                 .orElse(policyEngineServices.createPolicyModelFromPolicyEngine(microService));
185     }
186
187     /**
188      * Get the service blueprint Id in the Dcae inventory using the SDC UUID.
189      *
190      * @return The DcaeInventoryResponse object containing the dcae values
191      */
192     private DcaeInventoryResponse queryDcaeToGetServiceTypeId(BlueprintArtifact blueprintArtifact)
193             throws IOException, ParseException, InterruptedException {
194         return dcaeInventoryService.getDcaeInformation(blueprintArtifact.getBlueprintArtifactName(),
195                 blueprintArtifact.getBlueprintInvariantServiceUuid(),
196                 blueprintArtifact.getResourceAttached().getResourceInvariantUUID());
197     }
198
199 }