[POLICY-22] Reorganizing drools-apps
[policy/drools-applications.git] / controlloop / templates / template.demo.v1.0.0 / template.demo / src / test / java / org / onap / policy / template / demo / TestFirewallDemo.java
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
25 import java.io.IOException;
26 import java.nio.file.Files;
27 import java.nio.file.Path;
28 import java.nio.file.Paths;
29 import java.time.Instant;
30 import java.util.HashMap;
31 import java.util.UUID;
32 import java.util.regex.Matcher;
33 import java.util.regex.Pattern;
34
35 import org.junit.Test;
36 import org.kie.api.KieServices;
37 import org.kie.api.builder.KieBuilder;
38 import org.kie.api.builder.KieFileSystem;
39 import org.kie.api.builder.Message;
40 import org.kie.api.builder.ReleaseId;
41 import org.kie.api.builder.Results;
42 import org.kie.api.builder.model.KieModuleModel;
43 import org.kie.api.runtime.KieContainer;
44 import org.kie.api.runtime.KieSession;
45 import org.kie.api.runtime.rule.FactHandle;
46 import org.onap.policy.appc.CommonHeader;
47 import org.onap.policy.appc.Response;
48 import org.onap.policy.appc.ResponseStatus;
49 import org.onap.policy.controlloop.ControlLoopEventStatus;
50 import org.onap.policy.controlloop.ControlLoopTargetType;
51 import org.onap.policy.controlloop.VirtualControlLoopEvent;
52 import org.onap.policy.appc.util.Serialization;
53
54
55
56 public class TestFirewallDemo {
57
58         
59         @Test
60         public void testvDNS() throws IOException {
61                 //
62                 // Build a container
63                 //
64                 final String closedLoopControlName = "CL-DNS-LOW-TRAFFIC-SIG-d925ed73-8231-4d02-9545-db4e101f88f8";
65                 final KieSession kieSession = buildContainer("src/main/resources/archetype-resources/src/main/resources/ControlLoopDemo__closedLoopControlName__.drl", 
66                                 closedLoopControlName, 
67                                 "type=operational", 
68                                 "myFirewallDemoPolicy", 
69                                 "v1.0",
70                                 "MSO",
71                                 "http://localhost:8080/TestREST/Test",
72                                 "POLICY",
73                                 "POLICY",
74                                 "http://localhost:8080/TestREST/Test",
75                                 "POLICY",
76                                 "POLICY",
77                                 "4ff56a54-9e3f-46b7-a337-07a1d3c6b469",
78                                 0,
79                                 "POLICY-CL-MGT",
80                                 "APPC-CL"
81                                 );
82                 //
83                 // Initial fire of rules
84                 //
85                 kieSession.fireAllRules();
86                 //
87                 // Kick a thread that starts testing
88                 //
89                 new Thread(new Runnable() {
90
91                         @Override
92                         public void run() {
93                                 //
94                                 // Generate an invalid DCAE Event with requestID=null
95                                 //
96                                 VirtualControlLoopEvent invalidEvent = new VirtualControlLoopEvent();
97                                 invalidEvent.closedLoopControlName = closedLoopControlName;
98                                 invalidEvent.requestID = null;
99                                 invalidEvent.closedLoopEventClient = "tca.instance00001";
100                                 invalidEvent.target_type = ControlLoopTargetType.VF;
101                                 invalidEvent.target = "generic-vnf.vnf-id";
102                                 invalidEvent.from = "DCAE";
103                                 invalidEvent.closedLoopAlarmStart = Instant.now();
104                                 invalidEvent.AAI = new HashMap<String, String>();
105                                 invalidEvent.AAI.put("vserver.vserver-name", "vserver-name-16102016-aai3255-data-11-1");
106                                 invalidEvent.closedLoopEventStatus = ControlLoopEventStatus.ONSET;
107                                 
108                                 System.out.println("----- Invalid ONSET -----");
109                                 System.out.println(Serialization.gsonPretty.toJson(invalidEvent));
110                                 
111                                 //
112                                 // Insert invalid DCAE Event into memory
113                                 //
114                                 kieSession.insert(invalidEvent);        
115                                 try {
116                                         Thread.sleep(500);
117                                 } catch (InterruptedException e) {
118                                 }
119                                 //
120                                 // Generate first DCAE ONSET Event
121                                 //
122                                 VirtualControlLoopEvent onsetEvent = new VirtualControlLoopEvent();
123                                 onsetEvent.closedLoopControlName = closedLoopControlName;
124                                 onsetEvent.requestID = UUID.randomUUID();
125                                 onsetEvent.closedLoopEventClient = "tca.instance00001";
126                                 onsetEvent.target_type = ControlLoopTargetType.VF;
127                                 onsetEvent.target = "generic-vnf.vnf-id";
128                                 onsetEvent.from = "DCAE";
129                                 onsetEvent.closedLoopAlarmStart = Instant.now();
130                                 onsetEvent.AAI = new HashMap<String, String>();
131                                 onsetEvent.AAI.put("vserver.vserver-name", "vserver-name-16102016-aai3255-data-11-1");
132                                 onsetEvent.closedLoopEventStatus = ControlLoopEventStatus.ONSET;
133                                 
134                                 System.out.println("----- ONSET -----");
135                                 System.out.println(Serialization.gsonPretty.toJson(onsetEvent));
136                                 
137                                 //
138                                 // Insert first DCAE ONSET Event into memory
139                                 //
140                                 kieSession.insert(onsetEvent);
141                                 //
142                                 // We have test for subsequent ONSET Events in testvFirewall()
143                                 // So no need to test it again here
144                                 //
145                                 try {
146                                         Thread.sleep(3000);
147                                 } catch (InterruptedException e) {
148                                 }
149                                 //
150                                 // Test is finished, so stop the kieSession
151                                 //
152                                 kieSession.halt();
153                         }
154                 //
155                 }).start();
156                 //
157                 // Start firing rules
158                 //
159                 kieSession.fireUntilHalt();
160                 //
161                 // Dump working memory
162                 //
163                 dumpFacts(kieSession);
164                 //
165                 // See if there is anything left in memory, there SHOULD only be
166                 // a params fact.
167                 //
168                 assertEquals("There should only be 1 Fact left in memory.", 1, kieSession.getFactCount());
169                 for (FactHandle handle : kieSession.getFactHandles()) {
170                         Object fact = kieSession.getObject(handle);
171                         assertEquals("Non-Param Fact left in working memory", "org.onap.policy.controlloop.Params", fact.getClass().getName());
172                 }
173         }
174         
175         @Test
176         public void testvFirewall() throws IOException {
177                 //
178                 // Build a container
179                 //
180                 final String closedLoopControlName = "CL-FRWL-LOW-TRAFFIC-SIG-d925ed73-8231-4d02-9545-db4e101f88f8";
181                 final KieSession kieSession = buildContainer("src/main/resources/archetype-resources/src/main/resources/ControlLoopDemo__closedLoopControlName__.drl", 
182                                 closedLoopControlName, 
183                                 "type=operational", 
184                                 "myFirewallDemoPolicy", 
185                                 "v1.0",
186                                 "APPC",
187                                 "http://localhost:8080/TestREST/Test",
188                                 "POLICY",
189                                 "POLICY",
190                                 null,
191                                 null,
192                                 null,
193                                 null,
194                                 1,
195                                 "POLICY-CL-MGT",
196                                 "APPC-CL"
197                                 );
198                 //
199                 // Initial fire of rules
200                 //
201                 kieSession.fireAllRules();
202                 //
203                 // Kick a thread that starts testing
204                 //
205                 new Thread(new Runnable() {
206
207                         @Override
208                         public void run() {
209                                 //
210                                 // Generate an invalid DCAE Event with requestID=null
211                                 //
212                                 VirtualControlLoopEvent invalidEvent = new VirtualControlLoopEvent();
213                                 invalidEvent.closedLoopControlName = closedLoopControlName;
214                                 invalidEvent.requestID = null;
215                                 invalidEvent.closedLoopEventClient = "tca.instance00001";
216                                 invalidEvent.target_type = ControlLoopTargetType.VF;
217                                 invalidEvent.target = "generic-vnf.vnf-id";
218                                 invalidEvent.from = "DCAE";
219                                 invalidEvent.closedLoopAlarmStart = Instant.now();
220                                 invalidEvent.AAI = new HashMap<String, String>();
221                                 invalidEvent.AAI.put("generic-vnf.vnf-id", "foo");
222                                 invalidEvent.closedLoopEventStatus = ControlLoopEventStatus.ONSET;
223                                 
224                                 System.out.println("----- Invalid ONSET -----");
225                                 System.out.println(Serialization.gsonPretty.toJson(invalidEvent));
226                                 
227                                 //
228                                 // Insert invalid DCAE Event into memory
229                                 //
230                                 kieSession.insert(invalidEvent);        
231                                 try {
232                                         Thread.sleep(500);
233                                 } catch (InterruptedException e) {
234                                 }
235                                 //
236                                 // Generate first DCAE ONSET Event
237                                 //
238                                 VirtualControlLoopEvent onsetEvent = new VirtualControlLoopEvent();
239                                 onsetEvent.closedLoopControlName = closedLoopControlName;
240                                 onsetEvent.requestID = UUID.randomUUID();
241                                 onsetEvent.closedLoopEventClient = "tca.instance00001";
242                                 onsetEvent.target_type = ControlLoopTargetType.VF;
243                                 onsetEvent.target = "generic-vnf.vnf-id";
244                                 onsetEvent.from = "DCAE";
245                                 onsetEvent.closedLoopAlarmStart = Instant.now();
246                                 onsetEvent.AAI = new HashMap<String, String>();
247                                 onsetEvent.AAI.put("generic-vnf.vnf-id", "fw0001vm001fw001");
248                                 //onsetEvent.AAI.put("vserver.vserver-name", "vserver-name-16102016-aai3255-data-11-1");
249                                 onsetEvent.closedLoopEventStatus = ControlLoopEventStatus.ONSET;
250                                 
251                                 System.out.println("----- ONSET -----");
252                                 System.out.println(Serialization.gsonPretty.toJson(onsetEvent));
253                                 
254                                 //
255                                 // Insert first DCAE ONSET Event into memory
256                                 //
257                                 kieSession.insert(onsetEvent);
258                                 try {
259                                         Thread.sleep(500);
260                                 } catch (InterruptedException e) {
261                                 }
262                                 
263                                 
264                                 Thread thread = new Thread(new Runnable() {
265
266                                         @Override
267                                         public void run() {
268                                                 while (true) {
269                                                         //
270                                                         // Generate subsequent DCAE ONSET Event
271                                                         //
272                                                         VirtualControlLoopEvent subOnsetEvent = new VirtualControlLoopEvent();
273                                                         subOnsetEvent.closedLoopControlName = closedLoopControlName;
274                                                         subOnsetEvent.requestID = UUID.randomUUID();
275                                                         subOnsetEvent.closedLoopEventClient = "tca.instance00001";
276                                                         subOnsetEvent.target_type = ControlLoopTargetType.VF;
277                                                         subOnsetEvent.target = "generic-vnf.vnf-id";
278                                                         subOnsetEvent.from = "DCAE";
279                                                         subOnsetEvent.closedLoopAlarmStart = Instant.now();
280                                                         subOnsetEvent.AAI = new HashMap<String, String>();
281                                                         subOnsetEvent.AAI.put("generic-vnf.vnf-id", "fw0001vm001fw001");
282                                                         //subOnsetEvent.AAI.put("vserver.vserver-name", "vserver-name-16102016-aai3255-data-11-1");
283                                                         subOnsetEvent.closedLoopEventStatus = ControlLoopEventStatus.ONSET;
284                                                         
285                                                         System.out.println("----- Subsequent ONSET -----");
286                                                         System.out.println(Serialization.gsonPretty.toJson(subOnsetEvent));
287                                                         
288                                                         //
289                                                         // Insert subsequent DCAE ONSET Event into memory
290                                                         //
291                                                         kieSession.insert(subOnsetEvent);
292                                                         try {
293                                                                 Thread.sleep(500);
294                                                         } catch (InterruptedException e) {
295                                                                 break;
296                                                         }
297                                                 }
298                                         }
299                                         
300                                 });
301                                 thread.start();
302                                 try {
303                                         Thread.sleep(3000);
304                                 } catch (InterruptedException e) {
305                                 }
306                                 //
307                                 // Stop the thread
308                                 //
309                                 thread.interrupt();
310                                 //
311                                 // Generate APPC ACCEPT Response
312                                 //
313                                 Response response1 = new Response();
314                                 // CommonHeader
315                                 CommonHeader commonHeader1 = new CommonHeader();
316                                 commonHeader1.RequestID = onsetEvent.requestID;
317                                 response1.CommonHeader = commonHeader1;
318                                 // ResponseStatus
319                                 ResponseStatus responseStatus1 = new ResponseStatus();
320                                 responseStatus1.Code = 100;
321                                 response1.Status = responseStatus1;
322                                 //
323                                 System.out.println("----- APP-C RESPONSE 100 -----");
324                                 System.out.println(Serialization.gsonPretty.toJson(response1));
325                                 //
326                                 // Insert APPC Response into memory
327                                 //
328                                 kieSession.insert(response1);
329                                 //
330                                 // Simulating APPC takes some time for processing the recipe 
331                                 // and then gives response
332                                 //
333                                 try {
334                                         Thread.sleep(1000);
335                                 } catch (InterruptedException e) {
336                                 }
337                                 //
338                                 // Generate APPC SUCCESS Response
339                                 //
340                                 Response response2 = new Response();
341                                 // CommonHeader
342                                 CommonHeader commonHeader2 = new CommonHeader();
343                                 commonHeader2.RequestID = onsetEvent.requestID;
344                                 response2.CommonHeader = commonHeader2;
345                                 // ResponseStatus
346                                 ResponseStatus responseStatus2 = new ResponseStatus();
347                                 responseStatus2.Code = 400;
348                                 response2.Status = responseStatus2;
349                                 //
350                                 System.out.println("----- APP-C RESPONSE 400 -----");
351                                 System.out.println(Serialization.gsonPretty.toJson(response2));
352                                 //
353                                 // Insert APPC Response into memory
354                                 //
355                                 kieSession.insert(response2);
356                                 //
357                                 try {
358                                         Thread.sleep(3000);
359                                 } catch (InterruptedException e) {
360                                 }
361                                 //
362                                 // Test is finished, so stop the kieSession
363                                 //
364                                 kieSession.halt();
365                         }
366                 //
367                 }).start();
368                 //
369                 // Start firing rules
370                 //
371                 kieSession.fireUntilHalt();
372                 //
373                 // Dump working memory
374                 //
375                 dumpFacts(kieSession);
376                 //
377                 // See if there is anything left in memory, there SHOULD only be
378                 // a params fact.
379                 //
380                 assertEquals("There should only be 1 Fact left in memory.", 1, kieSession.getFactCount());
381                 for (FactHandle handle : kieSession.getFactHandles()) {
382                         Object fact = kieSession.getObject(handle);
383                         assertEquals("Non-Param Fact left in working memory", "org.onap.policy.controlloop.Params", fact.getClass().getName());
384                 }
385         }
386         
387         public static void dumpFacts(KieSession kieSession) {
388                 System.out.println("Fact Count: " + kieSession.getFactCount());
389                 for (FactHandle handle : kieSession.getFactHandles()) {
390                         System.out.println("FACT: " + handle);
391                 }
392         }
393
394         public static KieSession buildContainer(String droolsTemplate, 
395                         String closedLoopControlName, 
396                         String policyScope, 
397                         String policyName, 
398                         String policyVersion, 
399                         String actor, 
400                         String aaiURL,
401                         String aaiUsername,
402                         String aaiPassword,
403                         String msoURL,
404                         String msoUsername,
405                         String msoPassword,
406                         String aaiNamedQuery,
407                         int aaiPatternMatch,
408                         String notificationTopic,
409                         String appcTopic ) throws IOException {
410                 //
411         // Get our Drools Kie factory
412         //
413         KieServices ks = KieServices.Factory.get();
414         
415         KieModuleModel kModule = ks.newKieModuleModel();
416         
417         System.out.println("KMODULE:" + System.lineSeparator() + kModule.toXML());
418         
419         //
420         // Generate our drools rule from our template
421         //
422         KieFileSystem kfs = ks.newKieFileSystem();
423         
424         kfs.writeKModuleXML(kModule.toXML());
425         {
426                 Path rule = Paths.get(droolsTemplate);
427                 String ruleTemplate = new String(Files.readAllBytes(rule));
428                 String drlContents = generatePolicy(ruleTemplate,
429                                                                 closedLoopControlName,
430                                                                 policyScope,
431                                                                         policyName,
432                                                                         policyVersion,
433                                                                         actor,
434                                                                         aaiURL,
435                                                                         aaiUsername,
436                                                                         aaiPassword,
437                                                                         msoURL,
438                                                                         msoUsername,
439                                                                         msoPassword,
440                                                                         aaiNamedQuery,
441                                                                         aaiPatternMatch,
442                                                                         notificationTopic,
443                                                                         appcTopic
444                                                                         );
445                 
446                 kfs.write("src/main/resources/" + policyName + ".drl", ks.getResources().newByteArrayResource(drlContents.getBytes()));
447         }
448         //
449         // Compile the rule
450         //
451         KieBuilder builder = ks.newKieBuilder(kfs).buildAll();
452         Results results = builder.getResults();
453         if (results.hasMessages(Message.Level.ERROR)) {
454                 for (Message msg : results.getMessages()) {
455                         System.err.println(msg.toString());
456                 }
457                 throw new RuntimeException("Drools Rule has Errors");
458         }
459         for (Message msg : results.getMessages()) {
460                 System.out.println(msg.toString());
461         }
462         //
463         // Create our kie Session and container
464         //
465         ReleaseId releaseId = ks.getRepository().getDefaultReleaseId();
466         System.out.println(releaseId);
467             KieContainer kContainer = ks.newKieContainer(releaseId);
468             
469             return kContainer.newKieSession();
470         }
471         public static String    generatePolicy(String ruleContents, 
472                         String closedLoopControlName, 
473                         String policyScope, 
474                         String policyName, 
475                         String policyVersion,
476                         String actor,
477                         String aaiURL,
478                         String aaiUsername,
479                         String aaiPassword,
480                         String msoURL,
481                         String msoUsername,
482                         String msoPassword,
483                         String aaiNamedQueryUUID,
484                         int aaiPatternMatch,
485                         String notificationTopic,
486                         String appcTopic) {
487
488                 Pattern p = Pattern.compile("\\$\\{closedLoopControlName\\}");
489                 Matcher m = p.matcher(ruleContents);
490                 ruleContents = m.replaceAll(closedLoopControlName);
491
492                 p = Pattern.compile("\\$\\{policyScope\\}");
493                 m = p.matcher(ruleContents);
494                 ruleContents = m.replaceAll(policyScope);
495
496                 p = Pattern.compile("\\$\\{policyName\\}");
497                 m = p.matcher(ruleContents);
498                 ruleContents = m.replaceAll(policyName);
499
500                 p = Pattern.compile("\\$\\{policyVersion\\}");
501                 m = p.matcher(ruleContents);
502                 ruleContents = m.replaceAll(policyVersion);
503                 
504                 p = Pattern.compile("\\$\\{actor\\}");
505                 m = p.matcher(ruleContents);
506                 ruleContents = m.replaceAll(actor);
507                 
508                 p = Pattern.compile("\\$\\{aaiURL\\}");
509                 m = p.matcher(ruleContents);
510                 if (aaiURL == null) {
511                         ruleContents = m.replaceAll("null");
512                 } else {
513                         ruleContents = m.replaceAll(aaiURL);
514                 }
515                 
516                 p = Pattern.compile("\\$\\{aaiUsername\\}");
517                 m = p.matcher(ruleContents);
518                 if (aaiUsername == null) {
519                         ruleContents = m.replaceAll("null");
520                 } else {
521                         ruleContents = m.replaceAll(aaiUsername);
522                 }
523
524                 p = Pattern.compile("\\$\\{aaiPassword\\}");
525                 m = p.matcher(ruleContents);
526                 if (aaiPassword == null) {
527                         ruleContents = m.replaceAll("null");
528                 } else {
529                         ruleContents = m.replaceAll(aaiPassword);
530                 }
531
532                 p = Pattern.compile("\\$\\{msoURL\\}");
533                 m = p.matcher(ruleContents);
534                 if (msoURL == null) {
535                         ruleContents = m.replaceAll("null");
536                 } else {
537                         ruleContents = m.replaceAll(msoURL);
538                 }
539
540                 p = Pattern.compile("\\$\\{msoUsername\\}");
541                 m = p.matcher(ruleContents);
542                 if (msoUsername == null) {
543                         ruleContents = m.replaceAll("null");
544                 } else {
545                         ruleContents = m.replaceAll(msoUsername);
546                 }
547
548                 p = Pattern.compile("\\$\\{msoPassword\\}");
549                 m = p.matcher(ruleContents);
550                 if (msoPassword == null) {
551                         ruleContents = m.replaceAll("null");
552                 } else {
553                         ruleContents = m.replaceAll(msoPassword);
554                 }
555
556                 p = Pattern.compile("\\$\\{aaiNamedQueryUUID\\}");
557                 m = p.matcher(ruleContents);
558                 if (aaiNamedQueryUUID == null) {
559                         ruleContents = m.replaceAll("null");
560                 } else {
561                         ruleContents = m.replaceAll(aaiNamedQueryUUID);
562                 }
563
564                 p = Pattern.compile("\\$\\{aaiPatternMatch\\}");
565                 m = p.matcher(ruleContents);
566                 if (aaiPatternMatch == 1) {
567                         ruleContents = m.replaceAll("1");
568                 } else {
569                         ruleContents = m.replaceAll("0");
570                 }
571                 
572                 p = Pattern.compile("\\$\\{notificationTopic\\}");
573                 m = p.matcher(ruleContents);
574                 if (notificationTopic == null) {
575                         ruleContents = m.replaceAll("null");
576                 } else {
577                         ruleContents = m.replaceAll(notificationTopic);
578                 }
579                 
580                 p = Pattern.compile("\\$\\{appcTopic\\}");
581                 m = p.matcher(ruleContents);
582                 if (appcTopic == null) {
583                         ruleContents = m.replaceAll("null");
584                 } else {
585                         ruleContents = m.replaceAll(appcTopic);
586                 }
587                 
588                 System.out.println(ruleContents);
589
590                 return ruleContents;
591         }
592
593 }