Merge "Create a camel route that would retrieve all the DCAE blueprints"
[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 com.google.gson.JsonObject;
29
30 import java.io.IOException;
31 import java.util.Arrays;
32 import java.util.HashSet;
33 import java.util.List;
34 import java.util.Map.Entry;
35
36 import org.json.simple.parser.ParseException;
37 import org.onap.clamp.clds.client.DcaeInventoryServices;
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.BlueprintParser;
42 import org.onap.clamp.clds.sdc.controller.installer.ChainGenerator;
43 import org.onap.clamp.clds.sdc.controller.installer.CsarHandler;
44 import org.onap.clamp.clds.sdc.controller.installer.MicroService;
45 import org.onap.clamp.clds.util.drawing.SvgFacade;
46 import org.onap.clamp.loop.deploy.DcaeDeployParameters;
47 import org.onap.clamp.loop.service.CsarServiceInstaller;
48 import org.onap.clamp.loop.service.Service;
49 import org.onap.clamp.policy.Policy;
50 import org.onap.clamp.policy.microservice.MicroServicePolicy;
51 import org.onap.clamp.policy.operational.OperationalPolicy;
52 import org.springframework.beans.factory.annotation.Autowired;
53 import org.springframework.beans.factory.annotation.Qualifier;
54 import org.springframework.stereotype.Component;
55
56 /**
57  * This class will be instantiated by spring config, and used by Sdc Controller.
58  * There is no state kept by the bean. It's used to deploy the csar/notification
59  * received from SDC in DB.
60  */
61 @Component
62 @Qualifier("csarInstaller")
63 public class CsarInstaller {
64
65     private static final EELFLogger logger = EELFManager.getInstance().getLogger(CsarInstaller.class);
66     public static final String CONTROL_NAME_PREFIX = "ClosedLoop-";
67     public static final String GET_INPUT_BLUEPRINT_PARAM = "get_input";
68     // This will be used later as the policy scope
69     public static final String MODEL_NAME_PREFIX = "Loop_";
70
71     @Autowired
72     LoopsRepository loopRepository;
73
74     @Autowired
75     BlueprintParser blueprintParser;
76
77     @Autowired
78     ChainGenerator chainGenerator;
79
80     @Autowired
81     DcaeInventoryServices dcaeInventoryService;
82
83     @Autowired
84     private SvgFacade svgFacade;
85
86     @Autowired
87     CsarServiceInstaller csarServiceInstaller;
88
89     /**
90      * Verify whether Csar is deployed.
91      * 
92      * @param csar The Csar Handler
93      * @return The flag indicating whether Csar is deployed
94      * @throws SdcArtifactInstallerException The SdcArtifactInstallerException
95      */
96     public boolean isCsarAlreadyDeployed(CsarHandler csar) throws SdcArtifactInstallerException {
97         boolean alreadyInstalled = csarServiceInstaller.isServiceAlreadyDeployed(csar);
98
99         for (Entry<String, BlueprintArtifact> blueprint : csar.getMapOfBlueprints().entrySet()) {
100             alreadyInstalled = alreadyInstalled
101                     && loopRepository.existsById(Loop.generateLoopName(csar.getSdcNotification().getServiceName(),
102                             csar.getSdcNotification().getServiceVersion(),
103                             blueprint.getValue().getResourceAttached().getResourceInstanceName(),
104                             blueprint.getValue().getBlueprintArtifactName()));
105         }
106         return alreadyInstalled;
107     }
108
109     /**
110      * Install the service and loops from the csar.
111      * 
112      * @param csar The Csar Handler
113      * @throws SdcArtifactInstallerException The SdcArtifactInstallerException
114      * @throws InterruptedException          The InterruptedException
115      */
116     public void installTheCsar(CsarHandler csar) throws SdcArtifactInstallerException, InterruptedException {
117         logger.info("Installing the CSAR " + csar.getFilePath());
118         installTheLoop(csar, csarServiceInstaller.installTheService(csar));
119         logger.info("Successfully installed the CSAR " + csar.getFilePath());
120     }
121
122     /**
123      * Install the Loop from the csar.
124      * 
125      * @param csar    The Csar Handler
126      * @param service The service object that is related to the loop
127      * @throws SdcArtifactInstallerException The SdcArtifactInstallerException
128      * @throws InterruptedException          The InterruptedException
129      */
130     public void installTheLoop(CsarHandler csar, Service service)
131             throws SdcArtifactInstallerException, InterruptedException {
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                 loopRepository.save(createLoopFromBlueprint(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 Loop createLoopFromBlueprint(CsarHandler csar, BlueprintArtifact blueprintArtifact, Service service)
147             throws IOException, ParseException, InterruptedException {
148         Loop newLoop = new Loop();
149         newLoop.setBlueprint(blueprintArtifact.getDcaeBlueprint());
150         newLoop.setName(Loop.generateLoopName(csar.getSdcNotification().getServiceName(),
151                 csar.getSdcNotification().getServiceVersion(),
152                 blueprintArtifact.getResourceAttached().getResourceInstanceName(),
153                 blueprintArtifact.getBlueprintArtifactName()));
154         newLoop.setLastComputedState(LoopState.DESIGN);
155
156         List<MicroService> microServicesChain = chainGenerator
157                 .getChainOfMicroServices(blueprintParser.getMicroServices(blueprintArtifact.getDcaeBlueprint()));
158         if (microServicesChain.isEmpty()) {
159             microServicesChain = blueprintParser.fallbackToOneMicroService(blueprintArtifact.getDcaeBlueprint());
160         }
161         newLoop.setModelService(service);
162         newLoop.setMicroServicePolicies(
163                 createMicroServicePolicies(microServicesChain, csar, blueprintArtifact, newLoop));
164         newLoop.setOperationalPolicies(createOperationalPolicies(csar, blueprintArtifact, newLoop));
165
166         newLoop.setSvgRepresentation(svgFacade.getSvgImage(microServicesChain));
167         newLoop.setGlobalPropertiesJson(createGlobalPropertiesJson(blueprintArtifact, newLoop));
168
169         DcaeInventoryResponse dcaeResponse = queryDcaeToGetServiceTypeId(blueprintArtifact);
170         newLoop.setDcaeBlueprintId(dcaeResponse.getTypeId());
171         return newLoop;
172     }
173
174     private HashSet<OperationalPolicy> createOperationalPolicies(CsarHandler csar, BlueprintArtifact blueprintArtifact,
175             Loop newLoop) {
176         return new HashSet<>(Arrays.asList(new OperationalPolicy(Policy.generatePolicyName("OPERATIONAL",
177                 csar.getSdcNotification().getServiceName(), csar.getSdcNotification().getServiceVersion(),
178                 blueprintArtifact.getResourceAttached().getResourceInstanceName(),
179                 blueprintArtifact.getBlueprintArtifactName()), newLoop, new JsonObject())));
180     }
181
182     private HashSet<MicroServicePolicy> createMicroServicePolicies(List<MicroService> microServicesChain,
183             CsarHandler csar, BlueprintArtifact blueprintArtifact, Loop newLoop) throws IOException {
184         HashSet<MicroServicePolicy> newSet = new HashSet<>();
185
186         for (MicroService microService : microServicesChain) {
187             MicroServicePolicy microServicePolicy = new MicroServicePolicy(
188                     Policy.generatePolicyName(microService.getName(), csar.getSdcNotification().getServiceName(),
189                             csar.getSdcNotification().getServiceVersion(),
190                             blueprintArtifact.getResourceAttached().getResourceInstanceName(),
191                             blueprintArtifact.getBlueprintArtifactName()),
192                     microService.getModelType(), csar.getPolicyModelYaml().orElse(""), false,
193                     new HashSet<>(Arrays.asList(newLoop)));
194
195             newSet.add(microServicePolicy);
196             microService.setMappedNameJpa(microServicePolicy.getName());
197         }
198         return newSet;
199     }
200
201     private JsonObject createGlobalPropertiesJson(BlueprintArtifact blueprintArtifact, Loop newLoop) {
202         return DcaeDeployParameters.getDcaeDeploymentParametersInJson(blueprintArtifact, newLoop);
203     }
204
205     /**
206      * ll get the latest version of the artifact (version can be specified to DCAE
207      * call).
208      *
209      * @return The DcaeInventoryResponse object containing the dcae values
210      */
211     private DcaeInventoryResponse queryDcaeToGetServiceTypeId(BlueprintArtifact blueprintArtifact)
212             throws IOException, ParseException, InterruptedException {
213         return dcaeInventoryService.getDcaeInformation(blueprintArtifact.getBlueprintArtifactName(),
214                 blueprintArtifact.getBlueprintInvariantServiceUuid(),
215                 blueprintArtifact.getResourceAttached().getResourceInvariantUUID());
216     }
217
218 }