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