d517ef61e20a64796d8bcf8dadc30c0c211d3d12
[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.participant.policy.main.utils;
22
23 import static org.junit.Assert.assertTrue;
24
25 import java.io.File;
26 import java.io.FileNotFoundException;
27 import java.time.Instant;
28 import java.util.ArrayList;
29 import java.util.LinkedHashMap;
30 import java.util.List;
31 import java.util.Map;
32 import java.util.Set;
33 import java.util.UUID;
34 import lombok.AccessLevel;
35 import lombok.NoArgsConstructor;
36 import org.onap.policy.clamp.controlloop.common.utils.CommonUtils;
37 import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ControlLoop;
38 import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ControlLoopElement;
39 import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ControlLoopOrderedState;
40 import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ControlLoopState;
41 import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ParticipantDefinition;
42 import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ParticipantUpdates;
43 import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ParticipantUtils;
44 import org.onap.policy.clamp.controlloop.models.messages.dmaap.participant.ControlLoopStateChange;
45 import org.onap.policy.clamp.controlloop.models.messages.dmaap.participant.ControlLoopUpdate;
46 import org.onap.policy.clamp.controlloop.models.messages.dmaap.participant.ParticipantUpdate;
47 import org.onap.policy.clamp.controlloop.participant.policy.main.parameters.CommonTestData;
48 import org.onap.policy.common.utils.coder.Coder;
49 import org.onap.policy.common.utils.coder.CoderException;
50 import org.onap.policy.common.utils.coder.StandardCoder;
51 import org.onap.policy.common.utils.coder.YamlJsonTranslator;
52 import org.onap.policy.common.utils.resources.ResourceUtils;
53 import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier;
54 import org.onap.policy.models.tosca.authorative.concepts.ToscaNodeTemplate;
55 import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate;
56 import org.slf4j.Logger;
57 import org.slf4j.LoggerFactory;
58
59 @NoArgsConstructor(access = AccessLevel.PRIVATE)
60 public final class TestListenerUtils {
61
62     private static final YamlJsonTranslator yamlTranslator = new YamlJsonTranslator();
63     private static final Coder CODER = new StandardCoder();
64     static CommonTestData commonTestData = new CommonTestData();
65     private static final Logger LOGGER = LoggerFactory.getLogger(TestListenerUtils.class);
66
67     /**
68      * Method to create a controlLoop from a yaml file.
69      *
70      * @return ControlLoop controlloop
71      */
72     public static ControlLoop createControlLoop() {
73         ControlLoop controlLoop = new ControlLoop();
74         Map<UUID, ControlLoopElement> elements = new LinkedHashMap<>();
75         ToscaServiceTemplate toscaServiceTemplate = testControlLoopRead();
76         Map<String, ToscaNodeTemplate> nodeTemplatesMap =
77                 toscaServiceTemplate.getToscaTopologyTemplate().getNodeTemplates();
78         for (Map.Entry<String, ToscaNodeTemplate> toscaInputEntry : nodeTemplatesMap.entrySet()) {
79             ControlLoopElement clElement = new ControlLoopElement();
80             clElement.setId(UUID.randomUUID());
81
82             ToscaConceptIdentifier clElementParticipantId = new ToscaConceptIdentifier();
83             clElementParticipantId.setName(toscaInputEntry.getKey());
84             clElementParticipantId.setVersion(toscaInputEntry.getValue().getVersion());
85             clElement.setParticipantId(clElementParticipantId);
86
87             clElement.setDefinition(clElementParticipantId);
88             clElement.setState(ControlLoopState.UNINITIALISED);
89             clElement.setDescription(toscaInputEntry.getValue().getDescription());
90             clElement.setOrderedState(ControlLoopOrderedState.UNINITIALISED);
91             elements.put(clElement.getId(), clElement);
92         }
93         controlLoop.setElements(elements);
94         controlLoop.setName("PMSHInstance0");
95         controlLoop.setVersion("1.0.0");
96
97         ToscaConceptIdentifier definition = new ToscaConceptIdentifier();
98         definition.setName("PMSHInstance0");
99         definition.setVersion("1.0.0");
100         controlLoop.setDefinition(definition);
101
102         return controlLoop;
103     }
104
105     /**
106      * Method to create ControlLoopStateChange message from the arguments passed.
107      *
108      * @param controlLoopOrderedState controlLoopOrderedState
109      *
110      * @return ControlLoopStateChange message
111      */
112     public static ControlLoopStateChange createControlLoopStateChangeMsg(
113             final ControlLoopOrderedState controlLoopOrderedState) {
114         final ControlLoopStateChange clStateChangeMsg = new ControlLoopStateChange();
115
116         ToscaConceptIdentifier controlLoopId = new ToscaConceptIdentifier();
117         controlLoopId.setName("PMSHInstance0");
118         controlLoopId.setVersion("1.0.0");
119
120         ToscaConceptIdentifier participantId = new ToscaConceptIdentifier();
121         participantId.setName("org.onap.PM_Policy");
122         participantId.setVersion("0.0.0");
123
124         clStateChangeMsg.setControlLoopId(controlLoopId);
125         clStateChangeMsg.setParticipantId(participantId);
126         clStateChangeMsg.setTimestamp(Instant.now());
127         clStateChangeMsg.setOrderedState(controlLoopOrderedState);
128
129         return clStateChangeMsg;
130     }
131
132     /**
133      * Method to create ControlLoopUpdateMsg.
134      *
135      * @return ControlLoopUpdate message
136      */
137     public static ControlLoopUpdate createControlLoopUpdateMsg() {
138         final ControlLoopUpdate clUpdateMsg = new ControlLoopUpdate();
139         ToscaConceptIdentifier controlLoopId = new ToscaConceptIdentifier("PMSHInstance0", "1.0.0");
140         ToscaConceptIdentifier participantId = new ToscaConceptIdentifier("org.onap.PM_Policy", "0.0.0");
141
142         clUpdateMsg.setControlLoopId(controlLoopId);
143         clUpdateMsg.setParticipantId(participantId);
144         clUpdateMsg.setMessageId(UUID.randomUUID());
145         clUpdateMsg.setTimestamp(Instant.now());
146
147         Map<UUID, ControlLoopElement> elements = new LinkedHashMap<>();
148         ToscaServiceTemplate toscaServiceTemplate = testControlLoopRead();
149         TestListenerUtils.addPoliciesToToscaServiceTemplate(toscaServiceTemplate);
150         Map<String, ToscaNodeTemplate> nodeTemplatesMap =
151                 toscaServiceTemplate.getToscaTopologyTemplate().getNodeTemplates();
152         for (Map.Entry<String, ToscaNodeTemplate> toscaInputEntry : nodeTemplatesMap.entrySet()) {
153             if (ParticipantUtils.checkIfNodeTemplateIsControlLoopElement(toscaInputEntry.getValue(),
154                     toscaServiceTemplate)) {
155                 ControlLoopElement clElement = new ControlLoopElement();
156                 clElement.setId(UUID.randomUUID());
157                 var clParticipantType =
158                         ParticipantUtils.findParticipantType(toscaInputEntry.getValue().getProperties());
159
160                 clElement.setParticipantId(clParticipantType);
161                 clElement.setParticipantType(clParticipantType);
162
163                 clElement.setDefinition(
164                         new ToscaConceptIdentifier(toscaInputEntry.getKey(), toscaInputEntry.getValue().getVersion()));
165                 clElement.setState(ControlLoopState.UNINITIALISED);
166                 clElement.setDescription(toscaInputEntry.getValue().getDescription());
167                 clElement.setOrderedState(ControlLoopOrderedState.PASSIVE);
168                 elements.put(clElement.getId(), clElement);
169             }
170         }
171
172         List<ParticipantUpdates> participantUpdates = new ArrayList<>();
173         for (ControlLoopElement element : elements.values()) {
174             CommonUtils.setServiceTemplatePolicyInfo(element, toscaServiceTemplate);
175             CommonUtils.prepareParticipantUpdate(element, participantUpdates);
176         }
177         clUpdateMsg.setParticipantUpdatesList(participantUpdates);
178         return clUpdateMsg;
179     }
180
181     /**
182      * Method to create participantUpdateMsg.
183      *
184      * @return ParticipantUpdate message
185      */
186     public static ParticipantUpdate createParticipantUpdateMsg() {
187         final ParticipantUpdate participantUpdateMsg = new ParticipantUpdate();
188         ToscaConceptIdentifier participantId = new ToscaConceptIdentifier("org.onap.PM_Policy", "1.0.0");
189         ToscaConceptIdentifier participantType =
190                 new ToscaConceptIdentifier("org.onap.policy.controlloop.PolicyControlLoopParticipant", "2.3.1");
191
192         participantUpdateMsg.setParticipantId(participantId);
193         participantUpdateMsg.setTimestamp(Instant.now());
194         participantUpdateMsg.setParticipantType(participantType);
195         participantUpdateMsg.setTimestamp(Instant.ofEpochMilli(3000));
196         participantUpdateMsg.setMessageId(UUID.randomUUID());
197
198         ToscaServiceTemplate toscaServiceTemplate = testControlLoopRead();
199         // Add policies to the toscaServiceTemplate
200         TestListenerUtils.addPoliciesToToscaServiceTemplate(toscaServiceTemplate);
201
202         List<ParticipantDefinition> participantDefinitionUpdates = new ArrayList<>();
203         for (Map.Entry<String, ToscaNodeTemplate> toscaInputEntry : toscaServiceTemplate.getToscaTopologyTemplate()
204                 .getNodeTemplates().entrySet()) {
205             if (ParticipantUtils.checkIfNodeTemplateIsControlLoopElement(toscaInputEntry.getValue(),
206                     toscaServiceTemplate)) {
207                 CommonUtils.prepareParticipantDefinitionUpdate(
208                         ParticipantUtils.findParticipantType(toscaInputEntry.getValue().getProperties()),
209                         toscaInputEntry.getKey(), toscaInputEntry.getValue(),
210                         participantDefinitionUpdates, null);
211             }
212         }
213
214         participantUpdateMsg.setParticipantDefinitionUpdates(participantDefinitionUpdates);
215         return participantUpdateMsg;
216     }
217
218     /**
219      * Method to create ControlLoopUpdate using the arguments passed.
220      *
221      * @param jsonFilePath the path of the controlloop content
222      *
223      * @return ControlLoopUpdate message
224      * @throws CoderException exception while reading the file to object
225      */
226     public static ControlLoopUpdate createParticipantClUpdateMsgFromJson(String jsonFilePath) throws CoderException {
227         ControlLoopUpdate controlLoopUpdateMsg = CODER.decode(new File(jsonFilePath), ControlLoopUpdate.class);
228         return controlLoopUpdateMsg;
229     }
230
231     private static ToscaServiceTemplate testControlLoopRead() {
232         Set<String> controlLoopDirectoryContents =
233                 ResourceUtils.getDirectoryContents("src/test/resources/utils/servicetemplates");
234
235         boolean atLeastOneControlLoopTested = false;
236         ToscaServiceTemplate toscaServiceTemplate = null;
237
238         for (String controlLoopFilePath : controlLoopDirectoryContents) {
239             if (!controlLoopFilePath.endsWith(".yaml")) {
240                 continue;
241             }
242             atLeastOneControlLoopTested = true;
243             toscaServiceTemplate = testControlLoopYamlSerialization(controlLoopFilePath);
244         }
245
246         // Add policy_types to the toscaServiceTemplate
247         addPolicyTypesToToscaServiceTemplate(toscaServiceTemplate);
248
249         assertTrue(atLeastOneControlLoopTested);
250         return toscaServiceTemplate;
251     }
252
253     private static void addPolicyTypesToToscaServiceTemplate(ToscaServiceTemplate toscaServiceTemplate) {
254         Set<String> policyTypeDirectoryContents = ResourceUtils.getDirectoryContents("policytypes");
255
256         for (String policyTypeFilePath : policyTypeDirectoryContents) {
257             String policyTypeString = ResourceUtils.getResourceAsString(policyTypeFilePath);
258
259             ToscaServiceTemplate foundPolicyTypeSt =
260                     yamlTranslator.fromYaml(policyTypeString, ToscaServiceTemplate.class);
261
262             toscaServiceTemplate.setDerivedFrom(foundPolicyTypeSt.getDerivedFrom());
263             toscaServiceTemplate.setDescription(foundPolicyTypeSt.getDescription());
264             toscaServiceTemplate.setMetadata(foundPolicyTypeSt.getMetadata());
265             toscaServiceTemplate.setName(foundPolicyTypeSt.getName());
266             toscaServiceTemplate.setToscaDefinitionsVersion(foundPolicyTypeSt.getToscaDefinitionsVersion());
267             toscaServiceTemplate.setVersion(foundPolicyTypeSt.getVersion());
268
269             if (foundPolicyTypeSt.getDataTypes() != null) {
270                 if (toscaServiceTemplate.getDataTypes() == null) {
271                     toscaServiceTemplate.setDataTypes(foundPolicyTypeSt.getDataTypes());
272                 } else {
273                     toscaServiceTemplate.getDataTypes().putAll(foundPolicyTypeSt.getDataTypes());
274                 }
275             }
276
277             if (toscaServiceTemplate.getPolicyTypes() == null) {
278                 toscaServiceTemplate.setPolicyTypes(foundPolicyTypeSt.getPolicyTypes());
279             } else {
280                 toscaServiceTemplate.getPolicyTypes().putAll(foundPolicyTypeSt.getPolicyTypes());
281             }
282         }
283     }
284
285     /**
286      * Method to add polcies to the toscaServiceTemplate.
287      *
288      * @param toscaServiceTemplate to add policies
289      */
290     public static void addPoliciesToToscaServiceTemplate(ToscaServiceTemplate toscaServiceTemplate) {
291         Set<String> policiesDirectoryContents = ResourceUtils.getDirectoryContents("policies");
292
293         for (String policiesFilePath : policiesDirectoryContents) {
294             String policiesString = ResourceUtils.getResourceAsString(policiesFilePath);
295
296             ToscaServiceTemplate foundPoliciesSt = yamlTranslator.fromYaml(policiesString, ToscaServiceTemplate.class);
297             toscaServiceTemplate.getToscaTopologyTemplate()
298                     .setPolicies(foundPoliciesSt.getToscaTopologyTemplate().getPolicies());
299         }
300     }
301
302     private static ToscaServiceTemplate testControlLoopYamlSerialization(String controlLoopFilePath) {
303         try {
304             String controlLoopString = ResourceUtils.getResourceAsString(controlLoopFilePath);
305             if (controlLoopString == null) {
306                 throw new FileNotFoundException(controlLoopFilePath);
307             }
308
309             ToscaServiceTemplate serviceTemplate =
310                     yamlTranslator.fromYaml(controlLoopString, ToscaServiceTemplate.class);
311             return serviceTemplate;
312         } catch (FileNotFoundException e) {
313             LOGGER.error("cannot find YAML file", controlLoopFilePath);
314             throw new IllegalArgumentException(e);
315         }
316     }
317 }