2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
21 package org.onap.policy.template.demo;
23 import static org.junit.Assert.*;
25 import java.io.IOException;
26 import java.net.URLEncoder;
27 import java.time.Instant;
28 import java.util.HashMap;
29 import java.util.UUID;
31 import org.junit.Test;
32 import org.kie.api.runtime.KieSession;
33 import org.kie.api.runtime.rule.FactHandle;
34 import org.onap.policy.appclcm.LCMRequest;
35 import org.onap.policy.appclcm.LCMRequestWrapper;
36 import org.onap.policy.appclcm.LCMResponse;
37 import org.onap.policy.appclcm.LCMResponseWrapper;
38 import org.onap.policy.controlloop.ControlLoopEventStatus;
39 import org.onap.policy.controlloop.ControlLoopNotificationType;
40 import org.onap.policy.controlloop.VirtualControlLoopEvent;
41 import org.onap.policy.controlloop.VirtualControlLoopNotification;
42 import org.onap.policy.controlloop.policy.ControlLoopPolicy;
43 import org.onap.policy.controlloop.policy.TargetType;
44 import org.onap.policy.drools.impl.PolicyEngineJUnitImpl;
45 import org.onap.policy.guard.PolicyGuard;
46 import org.slf4j.Logger;
47 import org.slf4j.LoggerFactory;
49 public class VCPEControlLoopTest {
51 private static final Logger logger = LoggerFactory.getLogger(VCPEControlLoopTest.class);
53 private KieSession kieSession;
54 private Util.Pair<ControlLoopPolicy, String> pair;
55 private PolicyEngineJUnitImpl engine;
58 public void successTest() {
61 * Start the kie session
64 kieSession = startSession("src/main/resources/ControlLoop_Template_xacml_guard.drl",
65 "src/test/resources/yaml/policy_ControlLoop_vCPE.yaml",
66 "service=ServiceTest;resource=ResourceTest;type=operational",
68 "org.onap.closed_loop.ServiceTest:VNFS:1.0.0");
69 } catch (IOException e) {
71 logger.debug("Could not create kieSession");
72 fail("Could not create kieSession");
76 * Create a thread to continuously fire rules
77 * until main thread calls halt
79 new Thread( new Runnable() {
82 kieSession.fireUntilHalt();
87 * Create a unique requestId and a unique trigger source
89 UUID requestID = UUID.randomUUID();
90 String triggerSourceName = "foobartriggersource36";
93 * This will be the object returned from the PolicyEngine
98 * Simulate an onset event the policy engine will
99 * receive from DCAE to kick off processing through
103 sendOnset(pair.a, requestID, triggerSourceName);
104 } catch (InterruptedException e) {
106 logger.debug("Unable to send onset event");
107 fail("Unable to send onset event");
111 * Pull the object that was sent out to DMAAP and make
112 * sure it is a ControlLoopNoticiation of type active
114 obj = engine.subscribe("UEB", "POLICY-CL-MGT");
116 assertTrue(obj instanceof VirtualControlLoopNotification);
117 assertTrue(((VirtualControlLoopNotification)obj).notification.equals(ControlLoopNotificationType.ACTIVE));
120 * Give the control loop time to acquire a lock
124 } catch (InterruptedException e) {
126 logger.debug("An interrupt Exception was thrown");
127 fail("An interrupt Exception was thrown");
131 * The fact should be ready to query guard now to see
132 * if a ModifyConfig recipe is allowed
134 obj = engine.subscribe("UEB", "POLICY-CL-MGT");
136 logger.debug("\n\n####################### GOING TO QUERY GUARD about Restart!!!!!!");
137 logger.debug("Rule: {} Message {}", ((VirtualControlLoopNotification)obj).policyName, ((VirtualControlLoopNotification)obj).message);
140 * Make sure the object is an instance of a ControlLoopNotification
141 * and is of type operation
143 assertTrue(obj instanceof VirtualControlLoopNotification);
144 assertTrue(((VirtualControlLoopNotification)obj).notification.equals(ControlLoopNotificationType.OPERATION));
148 } catch (InterruptedException e) {
150 logger.debug("An interrupt Exception was thrown");
151 fail("An interrupt Exception was thrown");
155 * The guard response should be received at this point
157 obj = engine.subscribe("UEB", "POLICY-CL-MGT");
159 logger.debug("Rule: {} Message {}", ((VirtualControlLoopNotification)obj).policyName, ((VirtualControlLoopNotification)obj).message);
162 * The object should be a ControlLoopNotification with type operation
164 assertTrue(obj instanceof VirtualControlLoopNotification);
165 assertTrue(((VirtualControlLoopNotification)obj).notification.equals(ControlLoopNotificationType.OPERATION));
168 * See if Guard permits this action, if it does
169 * not then the test should fail
171 if (((VirtualControlLoopNotification)obj).message.contains("Guard result: Permit")) {
174 * A notification should be sent out of the Policy
175 * Engine at this point, it will be of type operation
177 obj = engine.subscribe("UEB", "POLICY-CL-MGT");
179 logger.debug("Rule: {} Message {}", ((VirtualControlLoopNotification)obj).policyName, ((VirtualControlLoopNotification)obj).message);
181 /* A notification should be sent out of the Policy
182 * Engine at this point, it will be of type operation
184 assertTrue(obj instanceof VirtualControlLoopNotification);
185 assertTrue(((VirtualControlLoopNotification)obj).notification.equals(ControlLoopNotificationType.OPERATION));
189 } catch (InterruptedException e) {
191 logger.debug("An interrupt Exception was thrown");
192 fail("An interrupt Exception was thrown");
196 * Obtain the request sent from the Policy Engine
198 obj = engine.subscribe("UEB", "APPC-LCM-READ");
202 * The request should be of type LCMRequestWrapper
203 * and the subrequestid should be 1
205 assertTrue(obj instanceof LCMRequestWrapper);
206 LCMRequestWrapper dmaapRequest = (LCMRequestWrapper) obj;
207 LCMRequest appcRequest = dmaapRequest.getBody();
208 assertTrue(appcRequest.getCommonHeader().getSubRequestId().equals("1"));
210 logger.debug("\n============ APPC received the request!!! ===========\n");
213 * Give some time for processing
217 } catch (InterruptedException e) {
219 logger.debug("An interrupt Exception was thrown");
220 fail("An interrupt Exception was thrown");
224 * Simulate a success response from APPC and insert
225 * the response into the working memory
227 LCMResponseWrapper dmaapResponse = new LCMResponseWrapper();
228 LCMResponse appcResponse = new LCMResponse(appcRequest);
229 appcResponse.getStatus().setCode(400);
230 appcResponse.getStatus().setMessage("AppC success");
231 dmaapResponse.setBody(appcResponse);
232 kieSession.insert(dmaapResponse);
235 * Give time for processing
239 } catch (InterruptedException e) {
241 logger.debug("An interrupt Exception was thrown");
242 fail("An interrupt Exception was thrown");
246 * Make sure the next notification is delivered
248 obj = engine.subscribe("UEB", "POLICY-CL-MGT");
250 logger.debug("Rule: {} Message {}", ((VirtualControlLoopNotification)obj).policyName, ((VirtualControlLoopNotification)obj).message);
253 * The ControlLoopNotification should be
254 * an OPERATION_SUCCESS
256 assertTrue(obj instanceof VirtualControlLoopNotification);
257 assertTrue(((VirtualControlLoopNotification)obj).notification.equals(ControlLoopNotificationType.OPERATION_SUCCESS));
260 * Now simulate the abatement sent from DCAE
263 sendAbatement(pair.a, requestID, triggerSourceName);
264 } catch (InterruptedException e1) {
265 e1.printStackTrace();
266 logger.debug("Abatement could not be sent");
267 fail("Abatement could not be sent");
271 * Give time to finish processing
275 } catch (InterruptedException e) {
277 logger.debug("An interrupt Exception was thrown");
278 fail("An interrupt Exception was thrown");
282 * This should be the final notification from the Policy Engine
284 obj = engine.subscribe("UEB", "POLICY-CL-MGT");
286 logger.debug("Rule: {} Message {}", ((VirtualControlLoopNotification)obj).policyName, ((VirtualControlLoopNotification)obj).message);
289 * The ControlLoopNotification should be of type FINAL_SUCCESS
291 assertTrue(obj instanceof VirtualControlLoopNotification);
292 assertTrue(((VirtualControlLoopNotification)obj).notification.equals(ControlLoopNotificationType.FINAL_SUCCESS));
295 * One final check to make sure the lock is released
297 assertFalse(PolicyGuard.isLocked(TargetType.VNF, triggerSourceName, requestID));
300 fail("Operation Denied by Guard");
304 * This will stop the thread that is firing the rules
309 * The only fact in memory should be Params
311 assertEquals(1, kieSession.getFactCount());
314 * Print what's left in memory
316 dumpFacts(kieSession);
319 * Gracefully shut down the kie session
321 kieSession.dispose();
325 * This method will start a kie session and instantiate
328 * @param droolsTemplate
331 * the yaml file containing the policies
336 * @param policyVersion
337 * version of the policy
338 * @return the kieSession to be used to insert facts
339 * @throws IOException
341 private KieSession startSession(String droolsTemplate,
345 String policyVersion) throws IOException {
348 * Load policies from yaml
350 pair = Util.loadYaml(yamlFile);
352 assertNotNull(pair.a);
353 assertNotNull(pair.a.getControlLoop());
354 assertNotNull(pair.a.getControlLoop().getControlLoopName());
355 assertTrue(pair.a.getControlLoop().getControlLoopName().length() > 0);
358 * Construct a kie session
360 final KieSession kieSession = Util.buildContainer(droolsTemplate,
361 pair.a.getControlLoop().getControlLoopName(),
365 URLEncoder.encode(pair.b, "UTF-8"));
368 * Retrieve the Policy Engine
370 engine = (PolicyEngineJUnitImpl) kieSession.getGlobal("Engine");
372 logger.debug("============");
373 logger.debug(URLEncoder.encode(pair.b, "UTF-8"));
374 logger.debug("============");
380 * This method is used to simulate event messages from DCAE
381 * that start the control loop (onset message).
383 * @param policy the controlLoopName comes from the policy
384 * @param requestID the requestId for this event
385 * @param triggerSourceName
386 * @throws InterruptedException
388 protected void sendOnset(ControlLoopPolicy policy, UUID requestID, String triggerSourceName) throws InterruptedException {
389 VirtualControlLoopEvent event = new VirtualControlLoopEvent();
390 event.closedLoopControlName = policy.getControlLoop().getControlLoopName();
391 event.requestID = requestID;
392 event.target = "generic-vnf.vnf-id";
393 event.closedLoopAlarmStart = Instant.now();
394 event.AAI = new HashMap<>();
395 event.AAI.put("cloud-region.identity-url", "foo");
396 event.AAI.put("vserver.selflink", "bar");
397 event.AAI.put("vserver.is-closed-loop-disabled", "false");
398 event.AAI.put("generic-vnf.vnf-id", "testGenericVnfId");
399 event.closedLoopEventStatus = ControlLoopEventStatus.ONSET;
400 kieSession.insert(event);
405 * This method is used to simulate event messages from DCAE
406 * that end the control loop (abatement message).
408 * @param policy the controlLoopName comes from the policy
409 * @param requestID the requestId for this event
410 * @param triggerSourceName
411 * @throws InterruptedException
413 protected void sendAbatement(ControlLoopPolicy policy, UUID requestID, String triggerSourceName) throws InterruptedException {
414 VirtualControlLoopEvent event = new VirtualControlLoopEvent();
415 event.closedLoopControlName = policy.getControlLoop().getControlLoopName();
416 event.requestID = requestID;
417 event.target = "generic-vnf.vnf-id";
418 event.closedLoopAlarmStart = Instant.now().minusSeconds(5);
419 event.closedLoopAlarmEnd = Instant.now();
420 event.AAI = new HashMap<>();
421 event.AAI.put("cloud-region.identity-url", "foo");
422 event.AAI.put("vserver.selflink", "bar");
423 event.AAI.put("vserver.is-closed-loop-disabled", "false");
424 event.AAI.put("generic-vnf.vnf-id", "testGenericVnfId");
425 event.closedLoopEventStatus = ControlLoopEventStatus.ABATED;
426 kieSession.insert(event);
430 * This method will dump all the facts in the working memory.
432 * @param kieSession the session containing the facts
434 public void dumpFacts(KieSession kieSession) {
435 logger.debug("Fact Count: {}", kieSession.getFactCount());
436 for (FactHandle handle : kieSession.getFactHandles()) {
437 logger.debug("FACT: {}", handle);