cb22132b4ecbb1bb436ea30f2db47c0c7719ead4
[policy/clamp.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  * Copyright (C) 2021 Nordix Foundation.
4  * ================================================================================
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  * SPDX-License-Identifier: Apache-2.0
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.policy.clamp.controlloop.runtime.instantiation;
22
23 import java.util.ArrayList;
24 import java.util.Collections;
25 import java.util.List;
26 import java.util.Map;
27 import java.util.function.UnaryOperator;
28 import java.util.stream.Collectors;
29 import javax.ws.rs.core.Response;
30 import javax.ws.rs.core.Response.Status;
31 import lombok.AllArgsConstructor;
32 import org.onap.policy.clamp.controlloop.common.exception.ControlLoopException;
33 import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ControlLoop;
34 import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ControlLoopElement;
35 import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ControlLoopState;
36 import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ControlLoops;
37 import org.onap.policy.clamp.controlloop.models.controlloop.persistence.provider.ControlLoopProvider;
38 import org.onap.policy.clamp.controlloop.models.messages.rest.GenericNameVersion;
39 import org.onap.policy.clamp.controlloop.models.messages.rest.instantiation.ControlLoopOrderStateResponse;
40 import org.onap.policy.clamp.controlloop.models.messages.rest.instantiation.InstantiationCommand;
41 import org.onap.policy.clamp.controlloop.models.messages.rest.instantiation.InstantiationResponse;
42 import org.onap.policy.clamp.controlloop.runtime.commissioning.CommissioningProvider;
43 import org.onap.policy.clamp.controlloop.runtime.supervision.SupervisionHandler;
44 import org.onap.policy.common.parameters.BeanValidationResult;
45 import org.onap.policy.common.parameters.ObjectValidationResult;
46 import org.onap.policy.common.parameters.ValidationResult;
47 import org.onap.policy.common.parameters.ValidationStatus;
48 import org.onap.policy.models.base.PfModelException;
49 import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier;
50 import org.onap.policy.models.tosca.authorative.concepts.ToscaNodeTemplate;
51 import org.springframework.stereotype.Component;
52
53 /**
54  * This class is dedicated to the Instantiation of Commissioned control loop.
55  */
56 @Component
57 @AllArgsConstructor
58 public class ControlLoopInstantiationProvider {
59     private final ControlLoopProvider controlLoopProvider;
60     private final CommissioningProvider commissioningProvider;
61     private final SupervisionHandler supervisionHandler;
62
63     private static final Object lockit = new Object();
64
65     /**
66      * Create control loops.
67      *
68      * @param controlLoops the control loop
69      * @return the result of the instantiation operation
70      * @throws PfModelException on creation errors
71      */
72     public InstantiationResponse createControlLoops(ControlLoops controlLoops) throws PfModelException {
73
74         synchronized (lockit) {
75             for (ControlLoop controlLoop : controlLoops.getControlLoopList()) {
76                 var checkControlLoop = controlLoopProvider.getControlLoop(controlLoop.getKey().asIdentifier());
77                 if (checkControlLoop != null) {
78                     throw new PfModelException(Response.Status.BAD_REQUEST,
79                             controlLoop.getKey().asIdentifier() + " already defined");
80                 }
81             }
82             BeanValidationResult validationResult = validateControlLoops(controlLoops);
83             if (!validationResult.isValid()) {
84                 throw new PfModelException(Response.Status.BAD_REQUEST, validationResult.getResult());
85             }
86             controlLoopProvider.createControlLoops(controlLoops.getControlLoopList());
87         }
88
89         var response = new InstantiationResponse();
90         response.setAffectedControlLoops(controlLoops.getControlLoopList().stream()
91                 .map(cl -> cl.getKey().asIdentifier()).collect(Collectors.toList()));
92
93         return response;
94     }
95
96     /**
97      * Update control loops.
98      *
99      * @param controlLoops the control loop
100      * @return the result of the instantiation operation
101      * @throws PfModelException on update errors
102      */
103     public InstantiationResponse updateControlLoops(ControlLoops controlLoops) throws PfModelException {
104         synchronized (lockit) {
105             BeanValidationResult validationResult = validateControlLoops(controlLoops);
106             if (!validationResult.isValid()) {
107                 throw new PfModelException(Response.Status.BAD_REQUEST, validationResult.getResult());
108             }
109             controlLoopProvider.updateControlLoops(controlLoops.getControlLoopList());
110         }
111
112         var response = new InstantiationResponse();
113         response.setAffectedControlLoops(controlLoops.getControlLoopList().stream()
114                 .map(cl -> cl.getKey().asIdentifier()).collect(Collectors.toList()));
115
116         return response;
117     }
118
119     /**
120      * Validate ControlLoops.
121      *
122      * @param controlLoops ControlLoops to validate
123      * @return the result of validation
124      * @throws PfModelException if controlLoops is not valid
125      */
126     private BeanValidationResult validateControlLoops(ControlLoops controlLoops) throws PfModelException {
127
128         var result = new BeanValidationResult("ControlLoops", controlLoops);
129
130         for (ControlLoop controlLoop : controlLoops.getControlLoopList()) {
131             var subResult = new BeanValidationResult("entry " + controlLoop.getDefinition().getName(), controlLoop);
132
133             List<ToscaNodeTemplate> toscaNodeTemplates = commissioningProvider.getControlLoopDefinitions(
134                     controlLoop.getDefinition().getName(), controlLoop.getDefinition().getVersion());
135
136             if (toscaNodeTemplates.isEmpty()) {
137                 subResult.addResult(new ObjectValidationResult("ControlLoop", controlLoop.getDefinition().getName(),
138                         ValidationStatus.INVALID, "Commissioned control loop definition not FOUND"));
139             } else if (toscaNodeTemplates.size() > 1) {
140                 subResult.addResult(new ObjectValidationResult("ControlLoop", controlLoop.getDefinition().getName(),
141                         ValidationStatus.INVALID, "Commissioned control loop definition not VALID"));
142             } else {
143
144                 List<ToscaNodeTemplate> clElementDefinitions =
145                         commissioningProvider.getControlLoopElementDefinitions(toscaNodeTemplates.get(0));
146
147                 // @formatter:off
148                 Map<String, ToscaConceptIdentifier> definitions = clElementDefinitions
149                         .stream()
150                         .map(nodeTemplate -> nodeTemplate.getKey().asIdentifier())
151                         .collect(Collectors.toMap(ToscaConceptIdentifier::getName, UnaryOperator.identity()));
152                 // @formatter:on
153
154                 for (ControlLoopElement element : controlLoop.getElements().values()) {
155                     subResult.addResult(validateDefinition(definitions, element.getDefinition()));
156                 }
157             }
158             result.addResult(subResult);
159         }
160         return result;
161     }
162
163     /**
164      * Validate ToscaConceptIdentifier, checking if exist in ToscaConceptIdentifiers map.
165      *
166      * @param definitions map of all ToscaConceptIdentifiers
167      * @param definition ToscaConceptIdentifier to validate
168      * @return the validation result
169      */
170     private ValidationResult validateDefinition(Map<String, ToscaConceptIdentifier> definitions,
171             ToscaConceptIdentifier definition) {
172         var result = new BeanValidationResult("entry " + definition.getName(), definition);
173         ToscaConceptIdentifier identifier = definitions.get(definition.getName());
174         if (identifier == null) {
175             result.setResult(ValidationStatus.INVALID, "Not FOUND");
176         } else if (!identifier.equals(definition)) {
177             result.setResult(ValidationStatus.INVALID, "Version not matching");
178         }
179         return (result.isClean() ? null : result);
180     }
181
182     /**
183      * Delete the control loop with the given name and version.
184      *
185      * @param name the name of the control loop to delete
186      * @param version the version of the control loop to delete
187      * @return the result of the deletion
188      * @throws PfModelException on deletion errors
189      */
190     public InstantiationResponse deleteControlLoop(String name, String version) throws PfModelException {
191         var response = new InstantiationResponse();
192         synchronized (lockit) {
193             List<ControlLoop> controlLoops = controlLoopProvider.getControlLoops(name, version);
194             if (controlLoops.isEmpty()) {
195                 throw new PfModelException(Response.Status.NOT_FOUND, "Control Loop not found");
196             }
197             for (ControlLoop controlLoop : controlLoops) {
198                 if (!ControlLoopState.UNINITIALISED.equals(controlLoop.getState())) {
199                     throw new PfModelException(Response.Status.BAD_REQUEST,
200                             "Control Loop State is still " + controlLoop.getState());
201                 }
202             }
203
204             response.setAffectedControlLoops(Collections
205                     .singletonList(controlLoopProvider.deleteControlLoop(name, version).getKey().asIdentifier()));
206         }
207         return response;
208     }
209
210     /**
211      * Get the requested control loops.
212      *
213      * @param name the name of the control loop to get, null for all control loops
214      * @param version the version of the control loop to get, null for all control loops
215      * @return the control loops
216      * @throws PfModelException on errors getting control loops
217      */
218     public ControlLoops getControlLoops(String name, String version) throws PfModelException {
219         var controlLoops = new ControlLoops();
220         controlLoops.setControlLoopList(controlLoopProvider.getControlLoops(name, version));
221
222         return controlLoops;
223     }
224
225     /**
226      * Issue a command to control loops, setting their ordered state.
227      *
228      * @param command the command to issue to control loops
229      * @return the result of the initiation command
230      * @throws PfModelException on errors setting the ordered state on the control loops
231      * @throws ControlLoopException on ordered state invalid
232      */
233     public InstantiationResponse issueControlLoopCommand(InstantiationCommand command)
234             throws ControlLoopException, PfModelException {
235
236         if (command.getOrderedState() == null) {
237             throw new ControlLoopException(Status.BAD_REQUEST, "ordered state invalid or not specified on command");
238         }
239
240         synchronized (lockit) {
241             List<ControlLoop> controlLoops = new ArrayList<>(command.getControlLoopIdentifierList().size());
242             for (ToscaConceptIdentifier id : command.getControlLoopIdentifierList()) {
243                 var controlLoop = controlLoopProvider.getControlLoop(id);
244                 controlLoop.setCascadedOrderedState(command.getOrderedState());
245                 controlLoops.add(controlLoop);
246             }
247             controlLoopProvider.updateControlLoops(controlLoops);
248         }
249
250         supervisionHandler.triggerControlLoopSupervision(command.getControlLoopIdentifierList());
251         var response = new InstantiationResponse();
252         response.setAffectedControlLoops(command.getControlLoopIdentifierList());
253
254         return response;
255     }
256
257     /**
258      * Gets a list of control loops with it's ordered state.
259      *
260      * @param name the name of the control loop to get, null for all control loops
261      * @param version the version of the control loop to get, null for all control loops
262      * @return a list of Instantiation Command
263      * @throws PfModelException on errors getting control loops
264      */
265     public ControlLoopOrderStateResponse getInstantiationOrderState(String name, String version)
266         throws PfModelException {
267
268         List<ControlLoop> controlLoops = controlLoopProvider.getControlLoops(name, version);
269
270         ControlLoopOrderStateResponse response = new ControlLoopOrderStateResponse();
271
272         controlLoops.forEach(controlLoop -> {
273             GenericNameVersion genericNameVersion = new GenericNameVersion();
274             genericNameVersion.setName(controlLoop.getName());
275             genericNameVersion.setVersion(controlLoop.getVersion());
276             response.getControlLoopIdentifierList().add(genericNameVersion);
277         });
278
279         return response;
280     }
281 }