7d9791d46abfebefb2f16de0205ccfbda71bca4a
[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.examples.adaptive;
22
23 import static org.junit.Assert.assertEquals;
24 import static org.junit.Assert.assertNotNull;
25 import static org.junit.Assert.assertTrue;
26
27 import java.io.IOException;
28 import java.util.Random;
29
30 import org.junit.Test;
31 import org.onap.policy.apex.core.engine.EngineParameters;
32 import org.onap.policy.apex.core.engine.engine.ApexEngine;
33 import org.onap.policy.apex.core.engine.engine.impl.ApexEngineFactory;
34 import org.onap.policy.apex.core.engine.event.EnEvent;
35 import org.onap.policy.apex.examples.adaptive.model.AdaptiveDomainModelFactory;
36 import org.onap.policy.apex.model.basicmodel.concepts.ApexException;
37 import org.onap.policy.apex.model.basicmodel.concepts.AxArtifactKey;
38 import org.onap.policy.apex.model.basicmodel.concepts.AxValidationResult;
39 import org.onap.policy.apex.model.policymodel.concepts.AxPolicyModel;
40 import org.onap.policy.apex.plugins.executor.java.JavaExecutorParameters;
41 import org.onap.policy.apex.plugins.executor.mvel.MVELExecutorParameters;
42 import org.slf4j.ext.XLogger;
43 import org.slf4j.ext.XLoggerFactory;
44
45 /**
46  * This policy passes, and recieves a Double event context filed called "EVCDouble".<br>
47  * The policy tries to detect anomalies in the pattern of values for EVCDouble<br>
48  * See the 2 test cases below (1 short, 1 long)
49  *
50  * @author John Keeney (John.Keeney@ericsson.com)
51  */
52 public class TestAnomalyDetectionTSLUseCase {
53     private static final XLogger LOGGER = XLoggerFactory.getXLogger(TestAnomalyDetectionTSLUseCase.class);
54
55     private static final int MAXITERATIONS = 3660;
56     private static final Random RAND = new Random(System.currentTimeMillis());
57
58     @Test
59     // once through the long running test below
60     public void TestAnomalyDetectionTSL() throws ApexException, InterruptedException, IOException {
61         final AxPolicyModel apexPolicyModel = new AdaptiveDomainModelFactory().getAnomalyDetectionPolicyModel();
62         assertNotNull(apexPolicyModel);
63
64         final AxValidationResult validationResult = new AxValidationResult();
65         apexPolicyModel.validate(validationResult);
66         assertTrue(validationResult.isValid());
67
68         final AxArtifactKey key = new AxArtifactKey("AnomalyTSLApexEngine", "0.0.1");
69         final EngineParameters parameters = new EngineParameters();
70         parameters.getExecutorParameterMap().put("MVEL", new MVELExecutorParameters());
71         parameters.getExecutorParameterMap().put("JAVA", new JavaExecutorParameters());
72
73         final ApexEngine apexEngine1 = new ApexEngineFactory().createApexEngine(key);
74
75         final TestApexActionListener listener1 = new TestApexActionListener("TestListener1");
76         apexEngine1.addEventListener("listener", listener1);
77         apexEngine1.updateModel(apexPolicyModel);
78         apexEngine1.start();
79         final EnEvent triggerEvent =
80                 apexEngine1.createEvent(new AxArtifactKey("AnomalyDetectionTriggerEvent", "0.0.1"));
81         final double rval = RAND.nextGaussian();
82         triggerEvent.put("Iteration", 0);
83         triggerEvent.put("MonitoredValue", rval);
84         LOGGER.info("Triggering policy in Engine 1 with " + triggerEvent);
85         apexEngine1.handleEvent(triggerEvent);
86         final EnEvent result = listener1.getResult();
87         LOGGER.info("Receiving action event {} ", result);
88         assertEquals("ExecutionIDs are different", triggerEvent.getExecutionID(), result.getExecutionID());
89         triggerEvent.clear();
90         result.clear();
91         Thread.sleep(1);
92         apexEngine1.stop();
93     }
94
95     /**
96      * This policy passes, and recieves a Double event context filed called "EVCDouble"<br>
97      * The policy tries to detect anomalies in the pattern of values for EVCDouble <br>
98      * This test case generates a SineWave-like pattern for the parameter, repeating every 360 iterations. (These Period
99      * should probably be set using TaskParameters!) Every 361st value is a random number!, so should be identified as
100      * an Anomaly. The policy has 3 Decide Tasks, and the Decide TaskSelectionLogic picks one depending on the
101      * 'Anomaliness' of the input data. <br>
102      * To plot the results grep debug results for the string "************", paste into excel and delete non-relevant
103      * columns<br>
104      *
105      * @throws ApexException the apex exception
106      * @throws InterruptedException the interrupted exception
107      * @throws IOException Signals that an I/O exception has occurred.
108      */
109     // Test is disabled by default. uncomment below, or execute using the main() method
110     // @Test
111     // EG Dos command: apex-core.engine> mvn
112     // -Dtest=org.onap.policy.apex.core.engine.ml.TestAnomalyDetectionTSLUseCase test | findstr /L /C:"Apex [main] DEBUG
113     // c.e.a.e.TaskSelectionExecutionLogging -
114     // TestAnomalyDetectionTSL_Policy0000DecideStateTaskSelectionLogic.getTask():"
115     public void TestAnomalyDetectionTSL_main() throws ApexException, InterruptedException, IOException {
116
117         final AxPolicyModel apexPolicyModel = new AdaptiveDomainModelFactory().getAnomalyDetectionPolicyModel();
118         assertNotNull(apexPolicyModel);
119
120         final AxValidationResult validationResult = new AxValidationResult();
121         apexPolicyModel.validate(validationResult);
122         assertTrue(validationResult.isValid());
123
124         final AxArtifactKey key = new AxArtifactKey("AnomalyTSLApexEngine", "0.0.1");
125         final EngineParameters parameters = new EngineParameters();
126         parameters.getExecutorParameterMap().put("MVEL", new MVELExecutorParameters());
127         parameters.getExecutorParameterMap().put("JAVA", new JavaExecutorParameters());
128
129         final ApexEngine apexEngine1 = new ApexEngineFactory().createApexEngine(key);
130
131         final TestApexActionListener listener1 = new TestApexActionListener("TestListener1");
132         apexEngine1.addEventListener("listener1", listener1);
133         apexEngine1.updateModel(apexPolicyModel);
134         apexEngine1.start();
135
136         final EnEvent triggerEvent =
137                 apexEngine1.createEvent(new AxArtifactKey("AnomalyDetectionTriggerEvent", "0.0.1"));
138         assertNotNull(triggerEvent);
139
140         for (int iteration = 0; iteration < MAXITERATIONS; iteration++) {
141             // Trigger the policy in engine 1
142
143             double value = (Math.sin(Math.toRadians(iteration))) + (RAND.nextGaussian() / 25.0);
144             // lets make every 361st number a random value to perhaps flag as an anomaly
145             if (((iteration + 45) % 361) == 0) {
146                 value = (RAND.nextGaussian() * 2.0);
147             }
148             triggerEvent.put("Iteration", iteration);
149             triggerEvent.put("MonitoredValue", value);
150             LOGGER.info("Iteration " + iteration + ":\tTriggering policy in Engine 1 with " + triggerEvent);
151             apexEngine1.handleEvent(triggerEvent);
152             final EnEvent result = listener1.getResult();
153             LOGGER.info("Iteration " + iteration + ":\tReceiving action event {} ", result);
154             triggerEvent.clear();
155             result.clear();
156         }
157         apexEngine1.stop();
158         Thread.sleep(1000);
159     }
160
161     public static void main(final String[] args) throws ApexException, InterruptedException, IOException {
162         new TestAnomalyDetectionTSLUseCase().TestAnomalyDetectionTSL_main();
163     }
164 }