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