29fdc195af33a2a5cb975568da894c16150a9883
[policy/drools-applications.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  * demo
4  * ================================================================================
5  * Copyright (C) 2017 Intel Corp. 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.assertNotNull;
25 import static org.junit.Assert.assertTrue;
26 import static org.junit.Assert.fail;
27
28 import java.io.IOException;
29 import java.net.URLEncoder;
30 import java.nio.file.Files;
31 import java.nio.file.Path;
32 import java.nio.file.Paths;
33 import java.time.Instant;
34 import java.util.HashMap;
35 import java.util.UUID;
36 import java.util.regex.Matcher;
37 import java.util.regex.Pattern;
38
39 import org.junit.AfterClass;
40 import org.junit.BeforeClass;
41 import org.junit.Test;
42 import org.kie.api.KieServices;
43 import org.kie.api.builder.KieBuilder;
44 import org.kie.api.builder.KieFileSystem;
45 import org.kie.api.builder.Message;
46 import org.kie.api.builder.ReleaseId;
47 import org.kie.api.builder.Results;
48 import org.kie.api.builder.model.KieModuleModel;
49 import org.kie.api.runtime.KieContainer;
50 import org.kie.api.runtime.KieSession;
51 import org.kie.api.runtime.rule.FactHandle;
52 import org.onap.policy.controlloop.ControlLoopEventStatus;
53 import org.onap.policy.controlloop.ControlLoopLogger;
54 import org.onap.policy.controlloop.ControlLoopTargetType;
55 import org.onap.policy.controlloop.VirtualControlLoopEvent;
56 import org.onap.policy.controlloop.impl.ControlLoopLoggerStdOutImpl;
57 import org.onap.policy.controlloop.policy.ControlLoopPolicy;
58 import org.onap.policy.drools.http.server.HttpServletServer;
59 import org.onap.policy.drools.impl.PolicyEngineJUnitImpl;
60 import org.onap.policy.drools.system.PolicyEngine;
61 import org.onap.policy.vfc.util.Serialization;
62 import org.slf4j.Logger;
63 import org.slf4j.LoggerFactory;
64
65
66 public class VFCControlLoopTest {
67
68         private static final Logger log = LoggerFactory.getLogger(VFCControlLoopTest.class);
69         private KieSession kieSession;
70         private Util.Pair<ControlLoopPolicy, String> pair;
71         private PolicyEngineJUnitImpl engine;
72
73         static {
74             /* Set environment properties */
75         PolicyEngine.manager.setEnvironmentProperty("aai.url", "http://localhost:6666");
76         PolicyEngine.manager.setEnvironmentProperty("aai.username", "AAI");
77         PolicyEngine.manager.setEnvironmentProperty("aai.password", "AAI");
78         
79         PolicyEngine.manager.setEnvironmentProperty("vfc.url", "http://localhost:6668");
80         PolicyEngine.manager.setEnvironmentProperty("vfc.username", "VFC");
81         PolicyEngine.manager.setEnvironmentProperty("vfc.password", "VFC");
82         }
83         
84         @BeforeClass
85         public static void setUpSimulator() {
86                 try {
87                         Util.buildAaiSim();
88                         Util.buildVfcSim();
89                 } catch (Exception e) {
90                         fail(e.getMessage());
91                 }
92         }
93
94         @AfterClass
95         public static void tearDownSimulator() {
96                 HttpServletServer.factory.destroy();
97         }
98
99         @Test
100         public void testVolte() throws IOException {
101
102                 final String yaml = "src/test/resources/yaml/policy_ControlLoop_VFC.yaml";
103
104                 //
105                 // Pull info from the yaml
106                 //
107                 final Util.Pair<ControlLoopPolicy, String> pair = Util.loadYaml(yaml);
108                 assertNotNull(pair);
109                 assertNotNull(pair.a);
110                 assertNotNull(pair.a.getControlLoop());
111                 assertNotNull(pair.a.getControlLoop().getControlLoopName());
112                 assertTrue(pair.a.getControlLoop().getControlLoopName().length() > 0);
113                 final String closedLoopControlName = pair.a.getControlLoop().getControlLoopName();
114
115                  /*
116          * Start the kie session
117          */
118                 try {
119                         kieSession = startSession("src/main/resources/ControlLoop_Template_xacml_guard.drl",
120                                         "src/test/resources/yaml/policy_ControlLoop_VFC.yaml",
121                                         "service=ServiceTest;resource=ResourceTest;type=operational",
122                                         "CL_VFC",
123                                         "org.onap.closed_loop.ServiceTest:VNFS:1.0.0");
124                 } catch (IOException e) {
125                         e.printStackTrace();
126                         log.debug("Could not create kieSession");
127                         fail("Could not create kieSession");
128                 }
129
130
131                 //
132                 // Insert our globals
133                 //
134                 final ControlLoopLogger logger = new ControlLoopLoggerStdOutImpl();
135                 kieSession.setGlobal("Logger", logger);
136                 final PolicyEngineJUnitImpl engine = new PolicyEngineJUnitImpl();
137                 kieSession.setGlobal("Engine", engine);
138
139                 //
140                 // Initial fire of rules
141                 //
142                 kieSession.fireAllRules();
143                 //
144                 // Kick a thread that starts testing
145                 //
146                 new Thread(new Runnable() {
147
148                         @Override
149                         public void run() {
150
151                                 log.debug("\n************ Starting VoLTE Test *************\n");
152
153                                 //
154                                 // Generate an invalid DCAE Event with requestID=null
155                                 //
156                                 VirtualControlLoopEvent invalidEvent = new VirtualControlLoopEvent();
157                                 invalidEvent.closedLoopControlName = closedLoopControlName;
158                                 invalidEvent.requestID = null;
159                                 invalidEvent.closedLoopEventClient = "tca.instance00009";
160                                 invalidEvent.target_type = ControlLoopTargetType.VNF;
161                                 invalidEvent.target = "generic-vnf.vnf-id";
162                                 invalidEvent.from = "DCAE";
163                                 invalidEvent.closedLoopAlarmStart = Instant.now();
164                                 invalidEvent.AAI = new HashMap<String, String>();
165                                 invalidEvent.AAI.put("vserver.vserver-name", "vserver-name-16102016-aai3255-data-11-1");
166                                 invalidEvent.closedLoopEventStatus = ControlLoopEventStatus.ONSET;
167
168                                 log.debug("-------- Sending Invalid ONSET --------");
169                                 log.debug(Serialization.gsonPretty.toJson(invalidEvent));
170
171                                 //
172                                 // Insert invalid DCAE Event into memory
173                                 //
174                                 kieSession.insert(invalidEvent);
175                                 try {
176                                         Thread.sleep(500);
177                                 } catch (InterruptedException e) {
178                                 }
179                                 //
180                                 // Generate first DCAE ONSET Event
181                                 //
182                                 VirtualControlLoopEvent onsetEvent = new VirtualControlLoopEvent();
183                                 onsetEvent.closedLoopControlName = closedLoopControlName;
184                                 onsetEvent.requestID = UUID.randomUUID();
185                                 onsetEvent.closedLoopEventClient = "tca.instance00009";
186                                 onsetEvent.target_type = ControlLoopTargetType.VM;
187                                 onsetEvent.target = "VM_NAME";
188                                 onsetEvent.from = "DCAE";
189                                 onsetEvent.closedLoopAlarmStart = Instant.now();
190                                 onsetEvent.AAI = new HashMap<String, String>();
191                                 onsetEvent.AAI.put("vserver.vserver-name", "vserver-name-16102016-aai3255-data-11-1");
192                                 onsetEvent.AAI.put("vserver.vserver-id", "vserver-id-16102016-aai3255-data-11-1");
193                                 onsetEvent.AAI.put("generic-vnf.vnf-id", "vnf-id-16102016-aai3255-data-11-1");
194                                 onsetEvent.AAI.put("service-instance.service-instance-id", "service-instance-id-16102016-aai3255-data-11-1");
195                                 onsetEvent.AAI.put("vserver.is-closed-loop-disabled", "false");
196                                 onsetEvent.closedLoopEventStatus = ControlLoopEventStatus.ONSET;
197
198                                 log.debug("-------- Sending Valid ONSET --------");
199                                 log.debug(Serialization.gsonPretty.toJson(onsetEvent));
200
201                                 //
202                                 // Insert first DCAE ONSET Event into memory
203                                 //
204                                 kieSession.insert(onsetEvent);
205                                 //
206                                 // We have test for subsequent ONSET Events in testvFirewall()
207                                 // So no need to test it again here
208                                 //
209                                 try {
210                                         Thread.sleep(30000);
211                                 } catch (InterruptedException e) {
212                                 }
213                                 //
214                                 // Test is finished, so stop the kieSession
215                                 //
216                                 kieSession.halt();
217                         }
218                 //
219                 }).start();
220                 //
221                 // Start firing rules
222                 //
223                 kieSession.fireUntilHalt();
224                 //
225                 // Dump working memory
226                 //
227                 dumpFacts(kieSession);
228
229                 //
230                 // See if there is anything left in memory, there SHOULD only be
231                 // a params fact.
232                 //
233                 assertEquals("There should only be 1 Fact left in memory.", 1, kieSession.getFactCount());
234                 for (FactHandle handle : kieSession.getFactHandles()) {
235                         Object fact = kieSession.getObject(handle);
236                         assertEquals("Non-Param Fact left in working memory", "org.onap.policy.controlloop.Params", fact.getClass().getName());
237                 }
238
239         }
240
241         public static void dumpFacts(KieSession kieSession) {
242                 log.debug("Fact Count: " + kieSession.getFactCount());
243                 for (FactHandle handle : kieSession.getFactHandles()) {
244                         log.debug("FACT: " + handle);
245                 }
246         }
247
248         /**
249          * This method will start a kie session and instantiate
250          * the Policy Engine.
251          *
252          * @param droolsTemplate
253          *          the DRL rules file
254          * @param yamlFile
255          *          the yaml file containing the policies
256          * @param policyScope
257          *          scope for policy
258          * @param policyName
259          *          name of the policy
260          * @param policyVersion
261          *          version of the policy
262          * @return the kieSession to be used to insert facts
263          * @throws IOException
264          */
265         private KieSession startSession(String droolsTemplate,
266                                         String yamlFile,
267                                         String policyScope,
268                                         String policyName,
269                                         String policyVersion) throws IOException {
270
271         /*
272          * Load policies from yaml
273          */
274                 pair = Util.loadYaml(yamlFile);
275                 assertNotNull(pair);
276                 assertNotNull(pair.a);
277                 assertNotNull(pair.a.getControlLoop());
278                 assertNotNull(pair.a.getControlLoop().getControlLoopName());
279                 assertTrue(pair.a.getControlLoop().getControlLoopName().length() > 0);
280
281         /*
282          * Construct a kie session
283          */
284                 final KieSession kieSession = Util.buildContainer(droolsTemplate,
285                                 pair.a.getControlLoop().getControlLoopName(),
286                                 policyScope,
287                                 policyName,
288                                 policyVersion,
289                                 URLEncoder.encode(pair.b, "UTF-8"));
290
291         /*
292          * Retrieve the Policy Engine
293          */
294                 engine = (PolicyEngineJUnitImpl) kieSession.getGlobal("Engine");
295
296                 log.debug("============");
297                 log.debug(URLEncoder.encode(pair.b, "UTF-8"));
298                 log.debug("============");
299
300                 return kieSession;
301         }
302
303 }
304