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