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