aa95e73b3ac15dfdd5762157c4e0eb112e3056b8
[policy/apex-pdp.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2016-2018 Ericsson. All rights reserved.
4  * ================================================================================
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  * 
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  * 
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  * 
17  * SPDX-License-Identifier: Apache-2.0
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.policy.apex.service.engine.runtime;
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.util.Date;
30 import java.util.HashMap;
31 import java.util.Map;
32
33 import org.junit.After;
34 import org.junit.Before;
35 import org.junit.Test;
36 import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities;
37 import org.onap.policy.apex.model.basicmodel.concepts.ApexException;
38 import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey;
39 import org.onap.policy.apex.model.basicmodel.service.ModelService;
40 import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel;
41 import org.onap.policy.apex.plugins.executor.mvel.MvelExecutorParameters;
42 import org.onap.policy.apex.service.engine.event.ApexEvent;
43 import org.onap.policy.apex.service.engine.event.ApexEventException;
44 import org.onap.policy.apex.service.engine.runtime.impl.EngineServiceImpl;
45 import org.onap.policy.apex.service.engine.utils.Utils;
46 import org.onap.policy.apex.service.parameters.engineservice.EngineServiceParameters;
47 import org.onap.policy.apex.test.common.model.SampleDomainModelFactory;
48 import org.slf4j.ext.XLogger;
49 import org.slf4j.ext.XLoggerFactory;
50
51
52 /**
53  * The Class ApexServiceTest.
54  *
55  * @author Liam Fallon (liam.fallon@ericsson.com)
56  */
57 public class ApexServiceModelUpdateTest {
58     // Logger for this class
59     private static final XLogger LOGGER = XLoggerFactory.getXLogger(ApexServiceModelUpdateTest.class);
60
61     private final AxArtifactKey engineServiceKey = new AxArtifactKey("Machine-1_process-1_engine-1", "0.0.0");
62     private final EngineServiceParameters parameters = new EngineServiceParameters();
63     private EngineService service = null;
64     private TestListener listener = null;
65     private int actionEventsReceived = 0;
66
67     private AxPolicyModel apexSamplePolicyModel = null;
68     private String apexSampleModelString;
69
70     /**
71      * Sets up the test by creating an engine and reading in the test policy.
72      *
73      * @throws ApexException if something goes wron
74      * @throws IOException
75      */
76     @Before
77     public void setUp() throws ApexException, IOException {
78         // create engine with 3 threads
79         parameters.setInstanceCount(3);
80         parameters.setName(engineServiceKey.getName());
81         parameters.setVersion(engineServiceKey.getVersion());
82         parameters.setId(100);
83         parameters.getEngineParameters().getExecutorParameterMap().put("MVEL", new MvelExecutorParameters());
84         service = EngineServiceImpl.create(parameters);
85
86         LOGGER.debug("Running TestApexEngine. . .");
87
88         apexSamplePolicyModel = new SampleDomainModelFactory().getSamplePolicyModel("MVEL");
89         assertNotNull(apexSamplePolicyModel);
90
91         apexSampleModelString = Utils.getModelString(apexSamplePolicyModel);
92
93         // create engine
94         listener = new TestListener();
95         service.registerActionListener("MyListener", listener);
96     }
97
98     /**
99      * Tear down the the test infrastructure.
100      *
101      * @throws ApexException if there is an error
102      */
103     @After
104     public void tearDown() throws Exception {
105         if (service != null) {
106             service.stop();
107         }
108         service = null;
109     }
110
111     /**
112      * Test start with no model.
113      */
114     @Test
115     public void testNoModelStart() {
116         try {
117             service.startAll();
118             fail("Engine should not start with no model");
119         } catch (final Exception e) {
120             e.printStackTrace();
121             assertEquals("start()<-Machine-1_process-1_engine-1-0:0.0.0,STOPPED,  cannot start engine, "
122                     + "engine has not been initialized, its model is not loaded", e.getMessage());
123         }
124     }
125
126     /**
127      * Test model update with string model without force.
128      *
129      * @throws ApexException if there is an error
130      */
131     @Test
132     public void testModelUpdateStringNewNoForce() throws ApexException {
133         service.updateModel(parameters.getEngineKey(), apexSampleModelString, false);
134         service.startAll();
135         assertEquals(apexSamplePolicyModel.getKey(), ModelService.getModel(AxPolicyModel.class).getKey());
136     }
137
138     /**
139      * Test model update with string model with force.
140      *
141      * @throws ApexException if there is an error
142      */
143     @Test
144     public void testModelUpdateStringNewForce() throws ApexException {
145         service.updateModel(parameters.getEngineKey(), apexSampleModelString, true);
146         service.startAll();
147         assertEquals(apexSamplePolicyModel.getKey(), ModelService.getModel(AxPolicyModel.class).getKey());
148     }
149
150     /**
151      * Test model update with a new string model without force.
152      *
153      * @throws ApexException if there is an error
154      */
155     @Test
156     public void testModelUpdateStringNewNewNoForce() throws ApexException {
157         service.updateModel(parameters.getEngineKey(), apexSampleModelString, false);
158         service.startAll();
159         assertEquals(apexSamplePolicyModel.getKey(), ModelService.getModel(AxPolicyModel.class).getKey());
160
161         sendEvents();
162
163         service.updateModel(parameters.getEngineKey(), apexSampleModelString, false);
164         assertEquals(apexSamplePolicyModel.getKey(), ModelService.getModel(AxPolicyModel.class).getKey());
165
166         sendEvents();
167     }
168
169     /**
170      * Test incompatible model update with a model object without force.
171      *
172      * @throws ApexException if there is an error
173      */
174     @Test
175     public void testModelUpdateIncoNoForce() throws ApexException {
176         service.updateModel(parameters.getEngineKey(), apexSamplePolicyModel, false);
177         service.startAll();
178         assertEquals(apexSamplePolicyModel.getKey(), ModelService.getModel(AxPolicyModel.class).getKey());
179
180         // Different model name, incompatible
181         final AxPolicyModel incoPolicyModel0 = new AxPolicyModel(apexSamplePolicyModel);
182         incoPolicyModel0.getKey().setName("INCOMPATIBLE");
183
184         try {
185             service.updateModel(parameters.getEngineKey(), incoPolicyModel0, false);
186             fail("model update should fail on incompatible model without force being true");
187         } catch (final Exception e) {
188             System.err.println(e.getMessage());
189             assertEquals(
190                     "apex model update failed, supplied model with key \"INCOMPATIBLE:0.0.1\" is not a compatible "
191                             + "model update from the existing engine model with key \"SamplePolicyModelMVEL:0.0.1\"",
192                     e.getMessage());
193         }
194
195         // Still on old model
196         sendEvents();
197
198         // Different major version, incompatible
199         final AxPolicyModel incoPolicyModel1 = new AxPolicyModel(apexSamplePolicyModel);
200         incoPolicyModel1.getKey().setVersion("1.0.1");
201
202         try {
203             service.updateModel(parameters.getEngineKey(), incoPolicyModel1, false);
204             fail("model update should fail on incompatible model without force being true");
205         } catch (final Exception e) {
206             System.err.println(e.getMessage());
207             e.printStackTrace();
208             assertEquals(
209                     "apex model update failed, supplied model with key \"SamplePolicyModelMVEL:1.0.1\" is not a compatible "
210                             + "model update from the existing engine model with key \"SamplePolicyModelMVEL:0.0.1\"",
211                     e.getMessage());
212         }
213
214         // Still on old model
215         sendEvents();
216
217         // Different minor version, compatible
218         final AxPolicyModel coPolicyModel0 = new AxPolicyModel(apexSamplePolicyModel);
219         coPolicyModel0.getKey().setVersion("0.1.0");
220         service.updateModel(parameters.getEngineKey(), coPolicyModel0, false);
221
222         // On new compatible model
223         sendEvents();
224
225         // Different patch version, compatible
226         final AxPolicyModel coPolicyModel1 = new AxPolicyModel(apexSamplePolicyModel);
227         coPolicyModel1.getKey().setVersion("0.0.2");
228         service.updateModel(parameters.getEngineKey(), coPolicyModel1, false);
229
230         // On new compatible model
231         sendEvents();
232
233     }
234
235     /**
236      * Test incompatible model update with a model object with force.
237      *
238      * @throws ApexException if there is an error
239      */
240     @Test
241     public void testModelUpdateIncoForce() throws ApexException {
242         service.updateModel(parameters.getEngineKey(), apexSamplePolicyModel, false);
243         service.startAll();
244         assertEquals(apexSamplePolicyModel.getKey(), ModelService.getModel(AxPolicyModel.class).getKey());
245
246         // Different model name, incompatible
247         final AxPolicyModel incoPolicyModel0 = new AxPolicyModel(apexSamplePolicyModel);
248         incoPolicyModel0.getKey().setName("INCOMPATIBLE");
249         service.updateModel(parameters.getEngineKey(), incoPolicyModel0, true);
250
251         // On updated model
252         sendEvents();
253
254         // Different major version, incompatible
255         final AxPolicyModel incoPolicyModel1 = new AxPolicyModel(apexSamplePolicyModel);
256         incoPolicyModel1.getKey().setVersion("1.0.1");
257         service.updateModel(parameters.getEngineKey(), incoPolicyModel1, true);
258
259         // On updated model
260         sendEvents();
261
262         // Different minor version, compatible
263         final AxPolicyModel coPolicyModel0 = new AxPolicyModel(apexSamplePolicyModel);
264         coPolicyModel0.getKey().setVersion("0.1.0");
265         service.updateModel(parameters.getEngineKey(), coPolicyModel0, true);
266
267         // On new compatible model
268         sendEvents();
269
270         // Different patch version, compatible
271         final AxPolicyModel coPolicyModel1 = new AxPolicyModel(apexSamplePolicyModel);
272         coPolicyModel1.getKey().setVersion("0.0.2");
273         service.updateModel(parameters.getEngineKey(), coPolicyModel1, true);
274
275         // On new compatible model
276         sendEvents();
277
278     }
279
280     /**
281      * Utility method to send some events into the test engine.
282      * 
283      * @throws ApexEventException if there is an error
284      */
285     private void sendEvents() throws ApexEventException {
286         final EngineServiceEventInterface engineServiceEventInterface = service.getEngineServiceEventInterface();
287
288         // Send some events
289         final Date testStartTime = new Date();
290         final Map<String, Object> eventDataMap = new HashMap<String, Object>();
291         eventDataMap.put("TestSlogan", "This is a test slogan");
292         eventDataMap.put("TestMatchCase", (byte) 123);
293         eventDataMap.put("TestTimestamp", testStartTime.getTime());
294         eventDataMap.put("TestTemperature", 34.5445667);
295
296         final ApexEvent event =
297                 new ApexEvent("Event0000", "0.0.1", "org.onap.policy.apex.domains.sample.events", "test", "apex");
298         event.putAll(eventDataMap);
299         engineServiceEventInterface.sendEvent(event);
300
301         final ApexEvent event2 =
302                 new ApexEvent("Event0100", "0.0.1", "org.onap.policy.apex.domains.sample.events", "test", "apex");
303         event2.putAll(eventDataMap);
304         engineServiceEventInterface.sendEvent(event2);
305
306         // Wait for results
307         while (actionEventsReceived < 2) {
308             ThreadUtilities.sleep(100);
309         }
310         ThreadUtilities.sleep(500);
311     }
312
313     /**
314      * The listener interface for receiving test events. The class that is interested in processing
315      * a test event implements this interface, and the object created with that class is registered
316      * with a component using the component's <code>addTestListener</code> method. When the test
317      * event occurs, that object's appropriate method is invoked.
318      *
319      * @see TestEvent
320      */
321     private final class TestListener implements ApexEventListener {
322
323         /*
324          * (non-Javadoc)
325          *
326          * @see
327          * org.onap.policy.apex.service.engine.runtime.ApexEventListener#onApexEvent(org.onap.policy
328          * .apex.service.engine.event.ApexEvent)
329          */
330         @Override
331         public synchronized void onApexEvent(final ApexEvent event) {
332             LOGGER.debug("result 1 is:" + event);
333             checkResult(event);
334             actionEventsReceived++;
335
336             final Date testStartTime = new Date((Long) event.get("TestTimestamp"));
337             final Date testEndTime = new Date();
338
339             LOGGER.info("policy execution time: " + (testEndTime.getTime() - testStartTime.getTime()) + "ms");
340         }
341
342         /**
343          * Check result.
344          *
345          * @param result the result
346          */
347         private void checkResult(final ApexEvent result) {
348             assertTrue(result.getName().startsWith("Event0004") || result.getName().startsWith("Event0104"));
349
350             assertTrue(result.get("TestSlogan").equals("This is a test slogan"));
351             assertTrue(result.get("TestMatchCase").equals(new Byte((byte) 123)));
352             assertTrue(result.get("TestTemperature").equals(34.5445667));
353             assertTrue(((byte) result.get("TestMatchCaseSelected")) >= 0
354                     && ((byte) result.get("TestMatchCaseSelected") <= 3));
355             assertTrue(((byte) result.get("TestEstablishCaseSelected")) >= 0
356                     && ((byte) result.get("TestEstablishCaseSelected") <= 3));
357             assertTrue(((byte) result.get("TestDecideCaseSelected")) >= 0
358                     && ((byte) result.get("TestDecideCaseSelected") <= 3));
359             assertTrue(
360                     ((byte) result.get("TestActCaseSelected")) >= 0 && ((byte) result.get("TestActCaseSelected") <= 3));
361         }
362     }
363 }