0318bed6ea50ff7f5a3e5518297f3b6dad387365
[policy/drools-pdp.git] /
1 /*
2  * ============LICENSE_START=======================================================
3  * feature-active-standby-management
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.drools.controller.test;
22
23 import static org.junit.Assert.assertTrue;
24
25 import java.io.File;
26 import java.io.FileInputStream;
27 import java.util.Date;
28 import java.util.Properties;
29
30 import javax.persistence.EntityManager;
31 import javax.persistence.EntityManagerFactory;
32 import javax.persistence.EntityTransaction;
33 import javax.persistence.Persistence;
34
35 import org.apache.commons.lang3.time.DateUtils;
36 import org.junit.After;
37 import org.junit.AfterClass;
38 import org.junit.Before;
39 import org.junit.BeforeClass;
40 import org.junit.Ignore;
41 import org.junit.Test;
42 import org.onap.policy.common.im.StateManagement;
43 import org.onap.policy.drools.activestandby.ActiveStandbyFeatureAPI;
44 import org.onap.policy.drools.activestandby.ActiveStandbyProperties;
45 import org.onap.policy.drools.activestandby.DroolsPdpEntity;
46 import org.onap.policy.drools.activestandby.DroolsPdpImpl;
47 import org.onap.policy.drools.activestandby.DroolsPdpsConnector;
48 import org.onap.policy.drools.activestandby.DroolsPdpsElectionHandler;
49 import org.onap.policy.drools.activestandby.JpaDroolsPdpsConnector;
50 import org.onap.policy.drools.core.PolicySessionFeatureAPI;
51 import org.onap.policy.drools.statemanagement.StateManagementFeatureAPI;
52 import org.slf4j.Logger;
53 import org.slf4j.LoggerFactory;
54
55 /*
56  * Testing the allSeemsWell interface to verify that it correctly affects the 
57  * operational state.
58  */ 
59  
60 public class AllSeemsWellTest {
61         private static final Logger  logger = LoggerFactory.getLogger(AllSeemsWellTest.class);
62         /*
63          * Currently, the DroolsPdpsElectionHandler.DesignationWaiter is invoked every 1 seconds, starting 
64          * at the start of the next multiple of pdpUpdateInterval, but with a minimum of 5 sec cushion
65          * to ensure that we wait for the DesignationWaiter to do its job, before 
66          * checking the results. Add a few seconds for safety
67          */ 
68          
69         long sleepTime = 10000;
70         
71         /*
72          * DroolsPdpsElectionHandler runs every 1 seconds, so it takes 10 seconds for the
73          * checkWaitTimer() method to time out and call allSeemsWell which then requires
74          * the forward progress counter to go stale which should add an additional 5 sec.
75          */
76          
77         long stalledElectionHandlerSleepTime = 15000;
78         
79         /*
80          * As soon as the election hander successfully runs, it will resume the forward progress.
81          * If the election handler runs ever 1 sec and test transaction is run every 1 sec and
82          * then fpc is written every 1 sec and then the fpc is checked every 2 sec, that could
83          * take a total of 5 sec to recognize the resumption of progress.  So, add 1 for safety.
84          */
85         long resumedElectionHandlerSleepTime = 6000;
86         
87         private static EntityManagerFactory emfx;
88         private static EntityManagerFactory emfd;
89         private static EntityManager emx;
90         private static EntityManager emd;
91         private static EntityTransaction et;
92         
93         private final String configDir = "src/test/resources/asw";
94
95         /*
96          * See the IntegrityMonitor.getJmxUrl() method for the rationale behind this jmx related processing.
97          */
98          
99         @BeforeClass
100         public static void setUpClass() throws Exception {
101                 
102                 String userDir = System.getProperty("user.dir");
103                 logger.debug("setUpClass: userDir={}", userDir);
104                 System.setProperty("com.sun.management.jmxremote.port", "9980");
105                 System.setProperty("com.sun.management.jmxremote.authenticate","false");
106         }
107
108         @AfterClass
109         public static void tearDownClass() throws Exception {
110         }
111
112         @Before
113         public void setUp() throws Exception {
114                 //Create teh data access for xaml db
115                 Properties stateManagementProperties = new Properties();
116                 stateManagementProperties.load(new FileInputStream(new File(
117                                 configDir + "/feature-state-management.properties")));
118
119                 emfx = Persistence.createEntityManagerFactory("junitXacmlPU", stateManagementProperties);
120
121                 // Create an entity manager to use the DB
122                 emx = emfx.createEntityManager();
123                 
124                 //Create the data access for drools db
125                 Properties activeStandbyProperties = new Properties();
126                 activeStandbyProperties.load(new FileInputStream(new File(
127                                 configDir + "/feature-active-standby-management.properties")));
128
129                 emfd = Persistence.createEntityManagerFactory("junitDroolsPU", activeStandbyProperties);
130
131                 // Create an entity manager to use the DB
132                 emd = emfd.createEntityManager();
133                 
134                 DroolsPdpsElectionHandler.setIsUnitTesting(true);
135         }
136
137         @After
138         public void tearDown() throws Exception {
139                                 
140         }
141         
142         public void cleanXacmlDb(){
143                 et = emx.getTransaction();
144                 
145                 et.begin();
146                 // Make sure we leave the DB clean
147                 emx.createQuery("DELETE FROM StateManagementEntity").executeUpdate();
148                 emx.createQuery("DELETE FROM ResourceRegistrationEntity").executeUpdate();
149                 emx.createQuery("DELETE FROM ForwardProgressEntity").executeUpdate();
150                 emx.flush();
151                 et.commit();
152         }
153         
154         public void cleanDroolsDb(){
155                 et = emd.getTransaction();
156                 
157                 et.begin();
158                 // Make sure we leave the DB clean
159                 emd.createQuery("DELETE FROM DroolsPdpEntity").executeUpdate();
160                 emd.flush();
161                 et.commit();
162         }
163         
164
165         // Tests hot standby when there is only one PDP.
166          
167         //@Ignore
168         @Test
169         public void testAllSeemsWell() throws Exception {
170         
171                 logger.debug("\n\ntestAllSeemsWell: Entering\n\n");
172                 cleanXacmlDb();
173                 cleanDroolsDb();
174                 
175                 logger.debug("testAllSeemsWell: Reading stateManagementProperties");
176                 Properties stateManagementProperties = new Properties();
177                 stateManagementProperties.load(new FileInputStream(new File(
178                                 configDir + "/feature-state-management.properties")));
179
180                 logger.debug("testAllSeemsWell: Creating emfXacml");
181                 EntityManagerFactory emfXacml = Persistence.createEntityManagerFactory(
182                                 "junitXacmlPU", stateManagementProperties);
183                 
184                 logger.debug("testAllSeemsWell: Reading activeStandbyProperties");
185                 Properties activeStandbyProperties = new Properties();
186                 activeStandbyProperties.load(new FileInputStream(new File(
187                                 configDir + "/feature-active-standby-management.properties")));
188                 String thisPdpId = activeStandbyProperties
189                                 .getProperty(ActiveStandbyProperties.NODE_NAME);
190
191                 logger.debug("testAllSeemsWell: Creating emfDrools");
192                 EntityManagerFactory emfDrools = Persistence.createEntityManagerFactory(
193                                 "junitDroolsPU", activeStandbyProperties);
194                 
195                 DroolsPdpsConnector conn = new JpaDroolsPdpsConnector(emfDrools);
196                 
197                 logger.debug("testAllSeemsWell: Cleaning up tables");
198                 conn.deleteAllPdps();
199                                         
200                 /*
201                  * Insert this PDP as not designated.  Initial standby state will be 
202                  * either null or cold standby.   Demoting should transit state to
203                  * hot standby.
204                  */
205                  
206                 logger.debug("testAllSeemsWell: Inserting PDP={} as not designated", thisPdpId);
207                 Date yesterday = DateUtils.addDays(new Date(), -1);
208                 DroolsPdpImpl pdp = new DroolsPdpImpl(thisPdpId, false, 4, yesterday);
209                 conn.insertPdp(pdp);
210                 DroolsPdpEntity droolsPdpEntity = conn.getPdp(thisPdpId);
211                 logger.debug("testAllSeemsWell: After insertion, PDP={} has DESIGNATED={}",
212                                 thisPdpId, droolsPdpEntity.isDesignated());
213                 assertTrue(droolsPdpEntity.isDesignated() == false);
214                 
215                 logger.debug("testAllSeemsWell: Instantiating stateManagement object");
216                 StateManagement sm = new StateManagement(emfXacml, "dummy");
217                 sm.deleteAllStateManagementEntities();
218                 
219                 
220                 // Now we want to create a StateManagementFeature and initialize it.  It will be
221                 // discovered by the ActiveStandbyFeature when the election handler initializes.
222
223                 StateManagementFeatureAPI smf = null;
224                 for (StateManagementFeatureAPI feature : StateManagementFeatureAPI.impl.getList())
225                 {
226                         ((PolicySessionFeatureAPI) feature).globalInit(null, configDir);
227                         smf = feature;
228                         logger.debug("testAllSeemsWell stateManagementFeature.getResourceName(): {}", smf.getResourceName());
229                         break;
230                 }
231                 if(smf == null){
232                         logger.error("testAllSeemsWell failed to initialize.  "
233                                         + "Unable to get instance of StateManagementFeatureAPI "
234                                         + "with resourceID: {}", thisPdpId);
235                         logger.debug("testAllSeemsWell failed to initialize.  "
236                                         + "Unable to get instance of StateManagementFeatureAPI "
237                                         + "with resourceID: {}", thisPdpId);
238                 }
239                 
240                 // Create an ActiveStandbyFeature and initialize it. It will discover the StateManagementFeature
241                 // that has been created.
242                 ActiveStandbyFeatureAPI activeStandbyFeature = null;
243                 for (ActiveStandbyFeatureAPI feature : ActiveStandbyFeatureAPI.impl.getList())
244                 {
245                         ((PolicySessionFeatureAPI) feature).globalInit(null, configDir);
246                         activeStandbyFeature = feature;
247                         logger.debug("testAllSeemsWell activeStandbyFeature.getResourceName(): {}", activeStandbyFeature.getResourceName());
248                         break;
249                 }
250                 if(activeStandbyFeature == null){
251                         logger.error("testAllSeemsWell failed to initialize.  "
252                                         + "Unable to get instance of ActiveStandbyFeatureAPI "
253                                         + "with resourceID: {}", thisPdpId);
254                         logger.debug("testAllSeemsWell failed to initialize.  "
255                                         + "Unable to get instance of ActiveStandbyFeatureAPI "
256                                         + "with resourceID: {}", thisPdpId);
257                 }
258                 
259
260                 logger.debug("testAllSeemsWell: Demoting PDP={}", thisPdpId);
261                 // demoting should cause state to transit to hotstandby
262                 smf.demote();
263                 
264                                 
265                 logger.debug("testAllSeemsWell: Sleeping {} ms, to allow JpaDroolsPdpsConnector "
266                                 + "time to check droolspdpentity table", sleepTime);
267                 Thread.sleep(sleepTime);
268                 
269                 
270                 // Verify that this formerly un-designated PDP in HOT_STANDBY is now designated and providing service.
271                  
272                 droolsPdpEntity = conn.getPdp(thisPdpId);
273                 logger.debug("testAllSeemsWell: After sm.demote() invoked, DESIGNATED= {} "
274                                 + "for PDP= {}", droolsPdpEntity.isDesignated(), thisPdpId);
275                 assertTrue(droolsPdpEntity.isDesignated() == true);
276                 String standbyStatus = smf.getStandbyStatus(thisPdpId);
277                 logger.debug("testAllSeemsWell: After demotion, PDP= {} "
278                                 + "has standbyStatus= {}", thisPdpId, standbyStatus);
279                 assertTrue(standbyStatus != null  &&  standbyStatus.equals(StateManagement.PROVIDING_SERVICE));
280                 
281                 //Now we want to stall the election handler and see the if AllSeemsWell will make the
282                 //standbystatus = coldstandby
283                 
284                 DroolsPdpsElectionHandler.setIsStalled(true);
285                 
286                 logger.debug("testAllSeemsWell: Sleeping {} ms, to allow checkWaitTimer to recognize "
287                                 + "the election handler has stalled and for the testTransaction to fail to "
288                                 + "increment forward progress and for the lack of forward progress to be recognized.",
289                                 stalledElectionHandlerSleepTime);
290
291
292                 //It takes 10x the update interval (1 sec) before the watcher will declare the election handler dead
293                 //and that just stops forward progress counter.  So, the fp monitor must then run to determine
294                 //if the fpc has stalled.  That will take about another 5 sec.
295                 Thread.sleep(stalledElectionHandlerSleepTime);
296                 
297                 logger.debug("testAllSeemsWell: After isStalled=true, PDP= {} "
298                                 + "has standbyStatus= {}", thisPdpId, smf.getStandbyStatus(thisPdpId));
299                 
300                 assertTrue(smf.getStandbyStatus().equals(StateManagement.COLD_STANDBY));
301                 
302                 //Now lets resume the election handler
303                 DroolsPdpsElectionHandler.setIsStalled(false);
304                 
305                 Thread.sleep(resumedElectionHandlerSleepTime);
306                 
307                 logger.debug("testAllSeemsWell: After isStalled=false, PDP= {} "
308                                 + "has standbyStatus= {}", thisPdpId, smf.getStandbyStatus(thisPdpId));
309                 
310                 assertTrue(smf.getStandbyStatus().equals(StateManagement.PROVIDING_SERVICE));
311
312                 //resumedElectionHandlerSleepTime = 5000;
313                 logger.debug("\n\ntestAllSeemsWell: Exiting\n\n");
314
315         }
316 }