23f03f7e8b6b4b76dc8afa2a368b3dc22fb9e707
[policy/drools-applications.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  * demo
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
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
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=========================================================
19  */
20
21 package org.onap.policy.template.demo;
22
23 import static org.junit.Assert.assertEquals;
24 import static org.junit.Assert.assertFalse;
25 import static org.junit.Assert.assertNotNull;
26 import static org.junit.Assert.assertTrue;
27 import static org.junit.Assert.fail;
28
29 import java.io.IOException;
30 import java.net.URLEncoder;
31 import java.time.Instant;
32 import java.util.HashMap;
33 import java.util.UUID;
34
35 import org.junit.Ignore;
36 import org.junit.Test;
37 import org.kie.api.runtime.KieSession;
38 import org.kie.api.runtime.rule.FactHandle;
39 import org.onap.policy.appc.Request;
40 import org.onap.policy.appc.Response;
41 import org.onap.policy.appc.ResponseCode;
42 import org.onap.policy.appc.ResponseValue;
43 import org.onap.policy.controlloop.ControlLoopEventStatus;
44 import org.onap.policy.controlloop.ControlLoopNotificationType;
45
46 import org.onap.policy.controlloop.VirtualControlLoopEvent;
47 import org.onap.policy.controlloop.VirtualControlLoopNotification;
48 import org.onap.policy.controlloop.policy.ControlLoopPolicy;
49 import org.onap.policy.controlloop.policy.TargetType;
50 import org.onap.policy.drools.impl.PolicyEngineJUnitImpl;
51 import org.onap.policy.guard.PolicyGuard;
52 import org.slf4j.Logger;
53 import org.slf4j.LoggerFactory;
54 //import org.onap.policy.controlloop.policy.guard.ControlLoopGuard;
55
56
57 public class ControlLoopXacmlGuardTest {
58         private static final Logger logger = LoggerFactory.getLogger(ControlLoopXacmlGuardTest.class);
59         
60         @Test
61         public void test() {
62                 try {
63                         this.runTest("src/main/resources/ControlLoop_Template_xacml_guard.drl", 
64                                         "src/test/resources/yaml/policy_ControlLoop_Service123.yaml",
65                                         "service=Service123;resource=Res123;type=operational", 
66                                         "CL_SERV123_8888", 
67                                         "org.onap.closed_loop.Service123:VNFS:0.0.1");
68                 } catch (IOException e) {
69                         e.printStackTrace();
70                         fail(e.getMessage());
71                 }
72         }
73         
74         public void runTest(String droolsTemplate, 
75                         String yamlFile, 
76                         String policyScope, 
77                         String policyName, 
78                         String policyVersion) throws IOException {
79                 //
80                 // Pull info from the yaml
81                 //
82                 final Util.Pair<ControlLoopPolicy, String> pair = Util.loadYaml(yamlFile);
83                 assertNotNull(pair);
84                 assertNotNull(pair.a);
85                 assertNotNull(pair.a.getControlLoop());
86                 assertNotNull(pair.a.getControlLoop().getControlLoopName());
87                 assertTrue(pair.a.getControlLoop().getControlLoopName().length() > 0);
88                 //
89                 // Build a container
90                 //
91                 final KieSession kieSession = Util.buildContainer(droolsTemplate, 
92                                 pair.a.getControlLoop().getControlLoopName(), 
93                                 policyScope, 
94                                 policyName, 
95                                 policyVersion, 
96                                 URLEncoder.encode(pair.b, "UTF-8"));
97                 
98                 
99                 logger.debug("============");
100                 logger.debug(URLEncoder.encode(pair.b, "UTF-8"));
101                 logger.debug("============");
102                 
103                 final PolicyEngineJUnitImpl engine = (PolicyEngineJUnitImpl) kieSession.getGlobal("Engine");
104                 
105                 //
106                 // Initial fire of rules
107                 //
108                 kieSession.fireAllRules();
109                 //
110                 // Kick a thread that starts testing
111                 //
112                 new Thread(new Runnable() {
113
114
115                         @Override
116                         public void run() {
117                                 try {
118                                         
119                                                 
120                                         //
121                                         // Let's use a unique ID for the request and
122                                         // a unique trigger source.
123                                         //
124                                         UUID requestID = UUID.randomUUID();
125                                         String triggerSourceName = "foobartriggersource36";
126                                         
127                                         Object obj = null;
128                                         
129                                         sendGoodEvents(kieSession, pair.a, requestID, triggerSourceName);
130                                         obj = engine.subscribe("UEB", "POLICY-CL-MGT");
131                                         assertNotNull(obj);
132                                         assertTrue(obj instanceof VirtualControlLoopNotification);
133                                         assertTrue(((VirtualControlLoopNotification)obj).notification.equals(ControlLoopNotificationType.ACTIVE));
134                                         //
135                                         // Give the control loop a little time to acquire the lock and publish the request
136                                         //
137                                         Thread.sleep(2000);
138                                         
139                                         
140                                         // "About to query Guard" notification (Querying about Restart)
141                                         obj = engine.subscribe("UEB", "POLICY-CL-MGT");
142                                         assertNotNull(obj);
143                                         logger.debug("\n\n####################### GOING TO QUERY GUARD about Restart!!!!!!");
144                                         logger.debug("Rule: {} Message {}", ((VirtualControlLoopNotification)obj).policyName, ((VirtualControlLoopNotification)obj).message);
145                                         assertTrue(obj instanceof VirtualControlLoopNotification);
146                                         assertTrue(((VirtualControlLoopNotification)obj).notification.equals(ControlLoopNotificationType.OPERATION));
147                                 
148                                         Thread.sleep(2000);
149                                         // "Response from Guard" notification
150                                         obj = engine.subscribe("UEB", "POLICY-CL-MGT");
151                                         assertNotNull(obj);
152                                         logger.debug("Rule: {} Message {}", ((VirtualControlLoopNotification)obj).policyName, ((VirtualControlLoopNotification)obj).message);
153                                         assertTrue(obj instanceof VirtualControlLoopNotification);
154                                         assertTrue(((VirtualControlLoopNotification)obj).notification.equals(ControlLoopNotificationType.OPERATION));
155                                 
156                                         
157                                         if(true == ((VirtualControlLoopNotification)obj).message.contains("Guard result: Deny")){
158                                                 
159                                                 // "About to query Guard" notification (Querying about Rebuild)
160                                                 obj = engine.subscribe("UEB", "POLICY-CL-MGT");
161                                                 assertNotNull(obj);
162                                                 logger.debug("\n\n####################### GOING TO QUERY GUARD about Rebuild!!!!!!");
163                                                 logger.debug("Rule: {} Message", ((VirtualControlLoopNotification)obj).policyName, ((VirtualControlLoopNotification)obj).message);
164                                                 assertTrue(obj instanceof VirtualControlLoopNotification);
165                                                 assertTrue(((VirtualControlLoopNotification)obj).notification.equals(ControlLoopNotificationType.OPERATION));
166                                         
167                                                 Thread.sleep(2000);
168                                                 
169                                                 // "Response from Guard" notification
170                                                 obj = engine.subscribe("UEB", "POLICY-CL-MGT");
171                                                 assertNotNull(obj);
172                                                 logger.debug("Rule: {} Message {}", ((VirtualControlLoopNotification)obj).policyName, ((VirtualControlLoopNotification)obj).message);
173                                                 assertTrue(obj instanceof VirtualControlLoopNotification);
174                                                 assertTrue(((VirtualControlLoopNotification)obj).notification.equals(ControlLoopNotificationType.OPERATION));
175                                                 
176                                                 
177                                                 if(true == ((VirtualControlLoopNotification)obj).message.contains("Guard result: Deny")){
178                                                         
179                                                         // "About to query Guard" notification (Querying about Migrate)
180                                                         obj = engine.subscribe("UEB", "POLICY-CL-MGT");
181                                                         assertNotNull(obj);
182                                                         logger.debug("\n\n####################### GOING TO QUERY GUARD!!!!!!");
183                                                         logger.debug("Rule: {} Message {}", ((VirtualControlLoopNotification)obj).policyName, ((VirtualControlLoopNotification)obj).message);
184                                                         assertTrue(obj instanceof VirtualControlLoopNotification);
185                                                         assertTrue(((VirtualControlLoopNotification)obj).notification.equals(ControlLoopNotificationType.OPERATION));
186                                                         
187                                                         Thread.sleep(2000);
188                                                         
189                                                         // "Response from Guard" notification
190                                                         obj = engine.subscribe("UEB", "POLICY-CL-MGT");
191                                                         assertNotNull(obj);
192                                                         logger.debug("Rule: " + ((VirtualControlLoopNotification)obj).policyName +" Message: " + ((VirtualControlLoopNotification)obj).message);
193                                                         assertTrue(obj instanceof VirtualControlLoopNotification);
194                                                         assertTrue(((VirtualControlLoopNotification)obj).notification.equals(ControlLoopNotificationType.OPERATION));
195                                                         
196                                                         
197                                                         if(true == ((VirtualControlLoopNotification)obj).message.contains("Guard result: Deny")){
198                                                                 //All the 3 operations were Denied by Guard
199                                                                 Thread.sleep(30000);
200                                                                 
201                                                         }       
202                                                 }
203                                         }
204                                         
205                                         //
206                                         // In case one of the operations was permitted by Guard
207                                         //
208                                         if(true == ((VirtualControlLoopNotification)obj).message.contains("Guard result: Permit")){
209                                                 obj = engine.subscribe("UEB", "POLICY-CL-MGT");
210                                                 assertNotNull(obj);
211                                                 logger.debug("Rule: {} Message {}", ((VirtualControlLoopNotification)obj).policyName, ((VirtualControlLoopNotification)obj).message);
212                                                 assertTrue(obj instanceof VirtualControlLoopNotification);
213                                                 assertTrue(((VirtualControlLoopNotification)obj).notification.equals(ControlLoopNotificationType.OPERATION));
214                                                 
215                                                 Thread.sleep(500);
216                                                 
217                                                 obj = engine.subscribe("UEB", "APPC-CL");
218                                                 assertNotNull(obj);
219                                                 assertTrue(obj instanceof Request);
220                                                 assertTrue(((Request)obj).CommonHeader.SubRequestID.equals("1"));
221                                                 
222                                                 logger.debug("\n============ APP-C Got request!!! ===========\n");
223                                                 //
224                                                 // Ok - let's simulate ACCEPT
225                                                 //
226
227                                                 //
228                                                 // now wait for it to finish
229                                                 //
230                                                 Thread.sleep(500);
231                                                 
232                                                 //
233                                                 // Now we are going to success it
234                                                 //
235                                                 Response response = new Response((Request) obj);
236                                                 response.Status.Code = ResponseCode.SUCCESS.getValue();
237                                                 response.Status.Value = ResponseValue.SUCCESS.toString();
238                                                 response.Status.Description = "AppC success";
239                                                 kieSession.insert(response);
240                                                 //
241                                                 // Give it some time to process
242                                                 //
243                                                 Thread.sleep(2000);
244                                                 //
245                                                 // Insert the abatement event
246                                                 //
247                                                 sendAbatement(kieSession, pair.a, requestID, triggerSourceName);
248                                                 //
249                                                 // now wait for it to finish
250                                                 //
251                                                 Thread.sleep(5000);                             
252                                                 //
253                                                 // Ensure they released the lock
254                                                 //
255                                                 assertFalse(PolicyGuard.isLocked(TargetType.VM, triggerSourceName, requestID));
256                                                 
257                                         }
258                                         
259                                         
260                                         
261                                 } catch (InterruptedException e) {
262                                         logger.error("Test thread got InterruptedException ", e.getLocalizedMessage());
263                                 } catch (AssertionError e) {
264                                         logger.error("Test thread got AssertionError ", e.getLocalizedMessage());
265                                         e.printStackTrace();
266                                 } catch (Exception e) {
267                                         logger.error("Test thread got Exception ", e.getLocalizedMessage());
268                                         e.printStackTrace();
269                                 }
270                                 kieSession.halt();
271                         }
272                         
273                 }).start();
274                 //
275                 // Start firing rules
276                 //
277                 kieSession.fireUntilHalt();
278                 //
279                 // Dump working memory
280                 //
281                 dumpFacts(kieSession);
282                 //
283                 // See if there is anything left in memory
284                 //
285                 assertEquals(1, kieSession.getFactCount());
286                 
287                 for (FactHandle handle : kieSession.getFactHandles()) {
288                         Object fact = kieSession.getObject(handle);
289                         assertEquals("", "org.onap.policy.controlloop.Params", fact.getClass().getName());
290                 }
291         }
292         
293
294         
295         
296         public static void dumpFacts(KieSession kieSession) {
297                 logger.debug("Fact Count: {}", kieSession.getFactCount());
298                 for (FactHandle handle : kieSession.getFactHandles()) {
299                         logger.debug("FACT: {}", handle);
300                 }
301         }
302
303         protected void sendAbatement(KieSession kieSession, ControlLoopPolicy policy, UUID requestID, String triggerSourceName) throws InterruptedException {
304                 VirtualControlLoopEvent event = new VirtualControlLoopEvent();
305                 event.closedLoopControlName = policy.getControlLoop().getControlLoopName();
306                 event.requestID = requestID;
307                 event.target = "vserver.vserver-name";
308                 event.closedLoopAlarmStart = Instant.now().minusSeconds(5);
309                 event.closedLoopAlarmEnd = Instant.now();
310                 event.AAI = new HashMap<String, String>();
311                 event.AAI.put("cloud-region.identity-url", "foo");
312                 event.AAI.put("vserver.selflink", "bar");
313                 event.AAI.put("vserver.is-closed-loop-disabled", "false");
314                 event.AAI.put("generic-vnf.vnf-name", "testGenericVnfName");
315                 event.closedLoopEventStatus = ControlLoopEventStatus.ABATED;
316                 kieSession.insert(event);
317         }
318         
319         protected void sendGoodEvents(KieSession kieSession, ControlLoopPolicy policy, UUID requestID, String triggerSourceName) throws InterruptedException {
320                 VirtualControlLoopEvent event = new VirtualControlLoopEvent();
321                 event.closedLoopControlName = policy.getControlLoop().getControlLoopName();
322                 event.requestID = requestID;
323                 event.target = "vserver.vserver-name";
324                 event.closedLoopAlarmStart = Instant.now();
325                 event.AAI = new HashMap<String, String>();
326                 event.AAI.put("cloud-region.identity-url", "foo");
327                 event.AAI.put("vserver.selflink", "bar");
328                 event.AAI.put("vserver.is-closed-loop-disabled", "false");
329                 event.AAI.put("vserver.vserver-name", "testGenericVnfName");
330                 event.closedLoopEventStatus = ControlLoopEventStatus.ONSET;
331                 kieSession.insert(event);
332                 Thread.sleep(1000);
333                 
334         }
335         
336         protected void sendBadEvents(KieSession kieSession, ControlLoopPolicy policy, UUID requestID, String triggerSourceName) throws InterruptedException {
337                 //
338                 // Insert a bad Event
339                 //
340                 VirtualControlLoopEvent event = new VirtualControlLoopEvent();
341                 event.closedLoopControlName = policy.getControlLoop().getControlLoopName();
342                 kieSession.insert(event);
343                 Thread.sleep(250);
344                 //
345                 // add the request id
346                 //
347                 event.requestID = requestID;
348                 kieSession.insert(event);
349                 Thread.sleep(250);
350                 //
351                 // add some aai
352                 //
353                 event.AAI = new HashMap<String, String>();
354                 event.AAI.put("cloud-region.identity-url", "foo");
355                 event.AAI.put("vserver.selflink", "bar");
356                 event.AAI.put("vserver.vserver-name", "vmfoo");
357                 kieSession.insert(event);
358                 Thread.sleep(250);
359                 //
360                 // set a valid status
361                 //
362                 event.closedLoopEventStatus = ControlLoopEventStatus.ONSET;
363                 kieSession.insert(event);
364                 Thread.sleep(250);
365                 //
366                 // add a trigger sourcename
367                 //
368                 kieSession.insert(event);
369                 Thread.sleep(250);
370                 //
371                 // add is closed-loop-disabled
372                 //
373                 event.AAI.put("vserver.is-closed-loop-disabled", "true");
374                 kieSession.insert(event);
375                 Thread.sleep(250);
376                 //
377                 // now enable
378                 //
379                 event.AAI.put("vserver.is-closed-loop-disabled", "false");
380                 kieSession.insert(event);
381                 Thread.sleep(250);
382                 //
383                 // Add target, but bad.
384                 //
385                 event.target = "VM_BLAH";
386                 kieSession.insert(event);
387                 Thread.sleep(250);
388         }
389 }