Change the Csar installer
[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.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.BlueprintParser;
40 import org.onap.clamp.clds.sdc.controller.installer.ChainGenerator;
41 import org.onap.clamp.clds.sdc.controller.installer.CsarHandler;
42 import org.onap.clamp.clds.sdc.controller.installer.MicroService;
43 import org.onap.clamp.clds.util.drawing.SvgFacade;
44 import org.onap.clamp.loop.service.CsarServiceInstaller;
45 import org.onap.clamp.loop.service.Service;
46 import org.onap.clamp.loop.template.LoopElementModel;
47 import org.onap.clamp.loop.template.LoopTemplate;
48 import org.onap.clamp.loop.template.LoopTemplatesRepository;
49 import org.onap.clamp.loop.template.PolicyModel;
50 import org.springframework.beans.factory.annotation.Autowired;
51 import org.springframework.beans.factory.annotation.Qualifier;
52 import org.springframework.stereotype.Component;
53
54 /**
55  * This class will be instantiated by spring config, and used by Sdc Controller.
56  * There is no state kept by the bean. It's used to deploy the csar/notification
57  * received from SDC in DB.
58  */
59 @Component
60 @Qualifier("csarInstaller")
61 public class CsarInstaller {
62
63     private static final EELFLogger logger = EELFManager.getInstance().getLogger(CsarInstaller.class);
64     public static final String CONTROL_NAME_PREFIX = "ClosedLoop-";
65     public static final String GET_INPUT_BLUEPRINT_PARAM = "get_input";
66     // This will be used later as the policy scope
67     public static final String MODEL_NAME_PREFIX = "Loop_";
68
69     @Autowired
70     LoopsRepository loopRepository;
71
72     @Autowired
73     LoopTemplatesRepository loopTemplatesRepository;
74
75     @Autowired
76     BlueprintParser blueprintParser;
77
78     @Autowired
79     ChainGenerator chainGenerator;
80
81     @Autowired
82     DcaeInventoryServices dcaeInventoryService;
83
84     @Autowired
85     private SvgFacade svgFacade;
86
87     @Autowired
88     CsarServiceInstaller csarServiceInstaller;
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      */
117     public void installTheCsar(CsarHandler csar) throws SdcArtifactInstallerException, InterruptedException {
118         logger.info("Installing the CSAR " + csar.getFilePath());
119         installTheLoopTemplates(csar, csarServiceInstaller.installTheService(csar));
120         logger.info("Successfully installed the CSAR " + csar.getFilePath());
121     }
122
123     /**
124      * Install the loop templates from the csar.
125      * 
126      * @param csar    The Csar Handler
127      * @param service The service object that is related to the loop
128      * @throws SdcArtifactInstallerException The SdcArtifactInstallerException
129      * @throws InterruptedException          The InterruptedException
130      */
131     public void installTheLoopTemplates(CsarHandler csar, Service service)
132             throws SdcArtifactInstallerException, InterruptedException {
133         try {
134             logger.info("Installing the Loops");
135             for (Entry<String, BlueprintArtifact> blueprint : csar.getMapOfBlueprints().entrySet()) {
136                 logger.info("Processing blueprint " + blueprint.getValue().getBlueprintArtifactName());
137                 loopTemplatesRepository.save(createLoopTemplateFromBlueprint(csar, blueprint.getValue(), service));
138             }
139             logger.info("Successfully installed the Loops ");
140         } catch (IOException e) {
141             throw new SdcArtifactInstallerException("Exception caught during the Loop installation in database", e);
142         } catch (ParseException e) {
143             throw new SdcArtifactInstallerException("Exception caught during the Dcae query to get ServiceTypeId", e);
144         }
145     }
146
147     private LoopTemplate createLoopTemplateFromBlueprint(CsarHandler csar, BlueprintArtifact blueprintArtifact,
148             Service service) throws IOException, ParseException, InterruptedException {
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<MicroService> microServicesChain = chainGenerator
156                 .getChainOfMicroServices(blueprintParser.getMicroServices(blueprintArtifact.getDcaeBlueprint()));
157         if (microServicesChain.isEmpty()) {
158             microServicesChain = blueprintParser.fallbackToOneMicroService(blueprintArtifact.getDcaeBlueprint());
159         }
160         newLoopTemplate.setModelService(service);
161         newLoopTemplate.addLoopElementModels(createMicroServiceModels(microServicesChain, csar, blueprintArtifact));
162         newLoopTemplate.setMaximumInstancesAllowed(0);
163         newLoopTemplate.setSvgRepresentation(svgFacade.getSvgImage(microServicesChain));
164         DcaeInventoryResponse dcaeResponse = queryDcaeToGetServiceTypeId(blueprintArtifact);
165         newLoopTemplate.setDcaeBlueprintId(dcaeResponse.getTypeId());
166         return newLoopTemplate;
167     }
168
169     private HashSet<LoopElementModel> createMicroServiceModels(List<MicroService> microServicesChain, CsarHandler csar,
170             BlueprintArtifact blueprintArtifact) throws IOException {
171         HashSet<LoopElementModel> newSet = new HashSet<>();
172         for (MicroService microService : microServicesChain) {
173             LoopElementModel loopElementModel = new LoopElementModel(microService.getModelType(), "CONFIG_POLICY",
174                     blueprintArtifact.getDcaeBlueprint());
175             newSet.add(loopElementModel);
176             loopElementModel.addPolicyModel(createPolicyModel(microService, csar));
177         }
178         return newSet;
179     }
180
181     private static String createPolicyAcronym(String policyType) {
182         String[] policyNameArray = policyType.split("\\.");
183         return policyNameArray[policyNameArray.length - 1];
184     }
185
186     private PolicyModel createPolicyModel(MicroService microService, CsarHandler csar) throws IOException {
187         return new PolicyModel(microService.getModelType(), csar.getPolicyModelYaml().orElse(""), "1.0",
188                 createPolicyAcronym(microService.getModelType()));
189     }
190
191     /**
192      * ll get the latest version of the artifact (version can be specified to DCAE
193      * call).
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 }