aboutsummaryrefslogtreecommitdiffstats
path: root/tosca-controlloop/runtime/src/main/java/org/onap/policy/clamp/controlloop/runtime/instantiation/ControlLoopInstantiationProvider.java
blob: eb72d921900e720e4005027227c22b9ebd7bbc27 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
/*-
 * ============LICENSE_START=======================================================
 * Copyright (C) 2021 Nordix Foundation.
 * ================================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * SPDX-License-Identifier: Apache-2.0
 * ============LICENSE_END=========================================================
 */

package org.onap.policy.clamp.controlloop.runtime.instantiation;

import java.io.Closeable;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.function.UnaryOperator;
import java.util.stream.Collectors;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import org.onap.policy.clamp.controlloop.common.exception.ControlLoopException;
import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ControlLoop;
import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ControlLoopElement;
import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ControlLoopState;
import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ControlLoops;
import org.onap.policy.clamp.controlloop.models.controlloop.persistence.provider.ControlLoopProvider;
import org.onap.policy.clamp.controlloop.models.messages.rest.instantiation.InstantiationCommand;
import org.onap.policy.clamp.controlloop.models.messages.rest.instantiation.InstantiationResponse;
import org.onap.policy.clamp.controlloop.runtime.commissioning.CommissioningProvider;
import org.onap.policy.clamp.controlloop.runtime.supervision.SupervisionHandler;
import org.onap.policy.common.parameters.BeanValidationResult;
import org.onap.policy.common.parameters.ObjectValidationResult;
import org.onap.policy.common.parameters.ValidationResult;
import org.onap.policy.common.parameters.ValidationStatus;
import org.onap.policy.models.base.PfModelException;
import org.onap.policy.models.base.PfModelRuntimeException;
import org.onap.policy.models.provider.PolicyModelsProviderParameters;
import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier;
import org.onap.policy.models.tosca.authorative.concepts.ToscaNodeTemplate;

/**
 * This class is dedicated to the Instantiation of Commissioned control loop.
 */
public class ControlLoopInstantiationProvider implements Closeable {
    private final ControlLoopProvider controlLoopProvider;
    private final CommissioningProvider commissioningProvider;

    private static final Object lockit = new Object();

    /**
     * Create a instantiation provider.
     *
     * @param databaseProviderParameters the parameters for database access
     */
    public ControlLoopInstantiationProvider(PolicyModelsProviderParameters databaseProviderParameters) {
        try {
            controlLoopProvider = new ControlLoopProvider(databaseProviderParameters);
            commissioningProvider = new CommissioningProvider(databaseProviderParameters);
        } catch (PfModelException e) {
            throw new PfModelRuntimeException(e);
        }
    }

    @Override
    public void close() throws IOException {
        controlLoopProvider.close();
    }

    /**
     * Create control loops.
     *
     * @param controlLoops the control loop
     * @return the result of the instantiation operation
     * @throws PfModelException on creation errors
     */
    public InstantiationResponse createControlLoops(ControlLoops controlLoops) throws PfModelException {

        synchronized (lockit) {
            for (ControlLoop controlLoop : controlLoops.getControlLoopList()) {
                ControlLoop checkControlLoop = controlLoopProvider.getControlLoop(controlLoop.getKey().asIdentifier());
                if (checkControlLoop != null) {
                    throw new PfModelException(Response.Status.BAD_REQUEST,
                            controlLoop.getKey().asIdentifier() + " already defined");
                }
            }
            BeanValidationResult validationResult = validateControlLoops(controlLoops);
            if (!validationResult.isValid()) {
                throw new PfModelException(Response.Status.BAD_REQUEST, validationResult.getResult());
            }
            controlLoopProvider.createControlLoops(controlLoops.getControlLoopList());
        }

        InstantiationResponse response = new InstantiationResponse();
        response.setAffectedControlLoops(controlLoops.getControlLoopList().stream()
                .map(cl -> cl.getKey().asIdentifier()).collect(Collectors.toList()));

        return response;
    }

    /**
     * Update control loops.
     *
     * @param controlLoops the control loop
     * @return the result of the instantiation operation
     * @throws PfModelException on update errors
     */
    public InstantiationResponse updateControlLoops(ControlLoops controlLoops) throws PfModelException {
        synchronized (lockit) {
            BeanValidationResult validationResult = validateControlLoops(controlLoops);
            if (!validationResult.isValid()) {
                throw new PfModelException(Response.Status.BAD_REQUEST, validationResult.getResult());
            }
            controlLoopProvider.updateControlLoops(controlLoops.getControlLoopList());
        }

        InstantiationResponse response = new InstantiationResponse();
        response.setAffectedControlLoops(controlLoops.getControlLoopList().stream()
                .map(cl -> cl.getKey().asIdentifier()).collect(Collectors.toList()));

        return response;
    }

    /**
     * Validate ControlLoops.
     *
     * @param controlLoops ControlLoops to validate
     * @result the result of validation
     * @throws PfModelException if controlLoops is not valid
     */
    private BeanValidationResult validateControlLoops(ControlLoops controlLoops) throws PfModelException {

        BeanValidationResult result = new BeanValidationResult("ControlLoops", controlLoops);

        for (ControlLoop controlLoop : controlLoops.getControlLoopList()) {
            BeanValidationResult subResult = new BeanValidationResult(
                    "entry " + controlLoop.getDefinition().getName(), controlLoop);

            List<ToscaNodeTemplate> toscaNodeTemplates = commissioningProvider.getControlLoopDefinitions(
                    controlLoop.getDefinition().getName(), controlLoop.getDefinition().getVersion());

            if (toscaNodeTemplates.isEmpty()) {
                subResult
                        .addResult(new ObjectValidationResult("ControlLoop", controlLoop.getDefinition().getName(),
                                ValidationStatus.INVALID, "Commissioned control loop definition not FOUND"));
            } else if (toscaNodeTemplates.size() > 1) {
                subResult
                        .addResult(new ObjectValidationResult("ControlLoop", controlLoop.getDefinition().getName(),
                                ValidationStatus.INVALID, "Commissioned control loop definition not VALID"));
            } else {

                List<ToscaNodeTemplate> clElementDefinitions =
                        commissioningProvider.getControlLoopElementDefinitions(toscaNodeTemplates.get(0));

                // @formatter:off
                Map<String, ToscaConceptIdentifier> definitions = clElementDefinitions
                        .stream()
                        .map(nodeTemplate -> nodeTemplate.getKey().asIdentifier())
                        .collect(Collectors.toMap(ToscaConceptIdentifier::getName, UnaryOperator.identity()));
                // @formatter:on

                for (ControlLoopElement element : controlLoop.getElements().values()) {
                    subResult.addResult(validateDefinition(definitions, element.getDefinition()));
                }
            }
            result.addResult(subResult);
        }
        return result;
    }

    /**
     * Validate ToscaConceptIdentifier, checking if exist in ToscaConceptIdentifiers map.
     *
     * @param definitions map of all ToscaConceptIdentifiers
     * @param definition ToscaConceptIdentifier to validate
     * @result result the validation result
     */
    private ValidationResult validateDefinition(Map<String, ToscaConceptIdentifier> definitions,
                                                ToscaConceptIdentifier definition) {
        BeanValidationResult result = new BeanValidationResult("entry " + definition.getName(), definition);
        ToscaConceptIdentifier identifier = definitions.get(definition.getName());
        if (identifier == null) {
            result.setResult(ValidationStatus.INVALID, "Not FOUND");
        } else if (!identifier.equals(definition)) {
            result.setResult(ValidationStatus.INVALID, "Version not matching");
        }
        return (result.isClean() ? null : result);
    }

    /**
     * Delete the control loop with the given name and version.
     *
     * @param name the name of the control loop to delete
     * @param version the version of the control loop to delete
     * @return the result of the deletion
     * @throws PfModelException on deletion errors
     */
    public InstantiationResponse deleteControlLoop(String name, String version) throws PfModelException {
        InstantiationResponse response = new InstantiationResponse();
        synchronized (lockit) {
            List<ControlLoop> controlLoops = controlLoopProvider.getControlLoops(name, version);
            if (controlLoops.isEmpty()) {
                throw new PfModelException(Response.Status.NOT_FOUND, "Control Loop not found");
            }
            for (ControlLoop controlLoop : controlLoops) {
                if (!ControlLoopState.UNINITIALISED.equals(controlLoop.getState())) {
                    throw new PfModelException(Response.Status.BAD_REQUEST,
                            "Control Loop State is still " + controlLoop.getState());
                }
            }

            response.setAffectedControlLoops(Collections
                    .singletonList(controlLoopProvider.deleteControlLoop(name, version).getKey().asIdentifier()));
        }
        return response;
    }

    /**
     * Get the requested control loops.
     *
     * @param name the name of the control loop to get, null for all control loops
     * @param version the version of the control loop to get, null for all control loops
     * @return the control loops
     * @throws PfModelException on errors getting control loops
     */
    public ControlLoops getControlLoops(String name, String version) throws PfModelException {
        ControlLoops controlLoops = new ControlLoops();
        controlLoops.setControlLoopList(controlLoopProvider.getControlLoops(name, version));

        return controlLoops;
    }

    /**
     * Issue a command to control loops, setting their ordered state.
     *
     * @param command the command to issue to control loops
     * @return the result of the initiation command
     * @throws PfModelException on errors setting the ordered state on the control loops
     * @throws ControlLoopException on ordered state invalid
     */
    public InstantiationResponse issueControlLoopCommand(InstantiationCommand command)
            throws ControlLoopException, PfModelException {

        if (command.getOrderedState() == null) {
            throw new ControlLoopException(Status.BAD_REQUEST, "ordered state invalid or not specified on command");
        }

        synchronized (lockit) {
            List<ControlLoop> controlLoops = new ArrayList<>(command.getControlLoopIdentifierList().size());
            for (ToscaConceptIdentifier id : command.getControlLoopIdentifierList()) {
                ControlLoop controlLoop = controlLoopProvider.getControlLoop(id);
                controlLoop.setCascadedOrderedState(command.getOrderedState());
                controlLoops.add(controlLoop);
            }
            controlLoopProvider.updateControlLoops(controlLoops);
        }

        SupervisionHandler supervisionHandler = SupervisionHandler.getInstance();
        supervisionHandler.triggerControlLoopSupervision(command.getControlLoopIdentifierList());
        InstantiationResponse response = new InstantiationResponse();
        response.setAffectedControlLoops(command.getControlLoopIdentifierList());

        return response;
    }
}