e624afb9e8b71e20606f162b55659704fae660b5
[policy/drools-pdp.git] /
1 /*
2  * ============LICENSE_START=======================================================
3  * feature-distributed-locking
4  * ================================================================================
5  * Copyright (C) 2018 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.distributed.locking.test;
22
23 import org.junit.AfterClass;
24 import org.junit.Before;
25 import org.junit.BeforeClass;
26 import org.junit.Test;
27 import org.onap.policy.distributed.locking.DistributedLockingFeature;
28 import org.onap.policy.drools.persistence.SystemPersistence;
29 import org.slf4j.Logger;
30 import org.slf4j.LoggerFactory;
31
32 import static org.junit.Assert.assertFalse;
33 import static org.junit.Assert.assertTrue;
34
35 import java.sql.Connection;
36 import java.sql.DriverManager;
37 import java.sql.PreparedStatement;
38 import java.sql.SQLException;
39 import java.util.concurrent.CountDownLatch;
40 import java.util.concurrent.ExecutionException;
41 import java.util.concurrent.TimeUnit;
42
43 public class TargetLockTest {
44         private static final Logger logger = LoggerFactory.getLogger(TargetLockTest.class);
45         private static final String DB_CONNECTION = "jdbc:h2:mem:pooling;INIT=CREATE SCHEMA IF NOT EXISTS pooling\\;SET SCHEMA pooling";
46         private static final String DB_USER = "user";
47         private static final String DB_PASSWORD = "password";
48         private static Connection conn = null;
49         private static DistributedLockingFeature distLockFeat;
50
51         @BeforeClass
52         public static void setup() {
53                 getDBConnection();
54                 createTable();
55                 SystemPersistence.manager.setConfigurationDir("src/test/resources");
56                 distLockFeat = new DistributedLockingFeature();
57                 distLockFeat.afterStart(null);
58         
59         }
60         
61         @AfterClass
62         public static void cleanUp() {
63                 distLockFeat.beforeShutdown(null);
64                 try {
65                         conn.close();
66                 } catch (SQLException e) {
67                         logger.error("Error in TargetLockTest.cleanUp()", e);
68                 }
69         }
70         
71         @Before
72         public void wipeDb() {
73                 
74                 try (PreparedStatement lockDelete = conn.prepareStatement("DELETE FROM pooling.locks");){
75                         lockDelete.executeUpdate();
76                 } catch (SQLException e) {
77                         logger.error("Error in TargetLockTest.wipeDb()", e);
78                         throw new RuntimeException(e);
79                 }
80
81         }
82         
83         @Test
84         public void testGrabLockSuccess() throws InterruptedException, ExecutionException {
85                 assertTrue(distLockFeat.beforeLock("resource1", "owner1", null).get());
86         
87                         //attempt to grab expiredLock
88                 try (PreparedStatement updateStatement = conn.prepareStatement("UPDATE pooling.locks SET expirationTime = ? WHERE resourceId = ?");)
89                 {
90                         updateStatement.setLong(1, System.currentTimeMillis() - 1000);
91                         updateStatement.setString(2, "resource1");
92                         updateStatement.executeUpdate();
93                                 
94                 } catch (SQLException e) {
95                         logger.error("Error in TargetLockTest.testGrabLockSuccess()", e);
96                         throw new RuntimeException(e);
97                 }
98                 
99                 assertTrue(distLockFeat.beforeLock("resource1", "owner1", null).get());
100         }
101
102         @Test
103         public void testExpiredLocks() throws InterruptedException, ExecutionException {
104                 CountDownLatch latch = new CountDownLatch(1);
105                 
106                 distLockFeat.beforeLock("resource1", "owner1", null);
107                 
108                 try {
109                         latch.await(1000, TimeUnit.MILLISECONDS);
110                 } catch (InterruptedException e) {
111                         logger.error("Error in testExpiredLocks", e);
112                 }
113                 
114                         //Heartbeat should keep it active
115                 assertFalse(distLockFeat.beforeLock("resource1", "owner1", null).get());
116         }
117         
118         @Test
119         public void testGrabLockFail() throws InterruptedException, ExecutionException {
120                 CountDownLatch latch = new CountDownLatch(1);
121                 
122                 distLockFeat.beforeLock("resource1", "owner1", null);
123                 
124                 try {
125                         latch.await(10, TimeUnit.MILLISECONDS);
126                 } catch (InterruptedException e) {
127                         logger.error("Error in testExpiredLocks", e);
128                 }
129                 assertFalse(distLockFeat.beforeLock("resource1", "owner1", null).get());
130
131         }
132         
133         
134         @Test
135         public void testUnlock() throws InterruptedException, ExecutionException {
136                 distLockFeat.beforeLock("resource1", "owner1", null);
137
138                 assertTrue(distLockFeat.beforeUnlock("resource1", "owner1"));
139                 assertTrue(distLockFeat.beforeLock("resource1", "owner1", null).get());
140         }
141         
142         @Test
143         public void testIsActive() {
144                 assertFalse(distLockFeat.beforeIsLockedBy("resource1", "owner1"));
145                 distLockFeat.beforeLock("resource1", "owner1", null);
146                 assertTrue(distLockFeat.beforeIsLockedBy("resource1", "owner1"));
147                 assertFalse(distLockFeat.beforeIsLockedBy("resource1", "owner2"));
148
149                 // isActive on expiredLock
150                 try (PreparedStatement updateStatement = conn
151                                 .prepareStatement("UPDATE pooling.locks SET expirationTime = ? WHERE resourceId = ?");) {
152                         updateStatement.setLong(1, System.currentTimeMillis() - 5000);
153                         updateStatement.setString(2, "resource1");
154                         updateStatement.executeUpdate();
155
156                 } catch (SQLException e) {
157                         logger.error("Error in TargetLockTest.testIsActive()", e);
158                         throw new RuntimeException(e);
159                 }
160
161                 assertFalse(distLockFeat.beforeIsLockedBy("resource1", "owner1"));
162
163                 distLockFeat.beforeLock("resource1", "owner1", null);
164                         //Unlock record, next isActive attempt should fail
165                 distLockFeat.beforeUnlock("resource1", "owner1");
166                 assertFalse(distLockFeat.beforeIsLockedBy("resource1", "owner1"));
167                 
168         }
169         
170         @Test
171         public void testHeartbeat() {
172                 CountDownLatch latch = new CountDownLatch(1);
173                 
174                 distLockFeat.beforeLock("resource1", "owner1", null);
175                 try {
176                         latch.await(1000, TimeUnit.MILLISECONDS);
177                 } catch (InterruptedException e) {
178                         logger.error("Error in testExpiredLocks", e);
179                 }
180                 
181                         // This test always returns true.
182                 assertTrue(distLockFeat.beforeIsLocked("resource1"));
183         }
184         
185         @Test
186         public void unlockBeforeLock() {
187                 assertFalse(distLockFeat.beforeUnlock("resource1", "owner1"));
188                 distLockFeat.beforeLock("resource1", "owner1", null);
189                 assertTrue(distLockFeat.beforeUnlock("resource1", "owner1"));
190                 assertFalse(distLockFeat.beforeUnlock("resource1", "owner1"));
191         }
192         
193         @Test
194         public void testIsLocked() {
195                 assertFalse(distLockFeat.beforeIsLocked("resource1"));
196                 distLockFeat.beforeLock("resource1", "owner1", null);
197                 assertTrue(distLockFeat.beforeIsLocked("resource1"));
198         
199         }
200         
201         private static void getDBConnection() {
202                 try {
203                         conn = DriverManager.getConnection(DB_CONNECTION, DB_USER, DB_PASSWORD);
204                 } catch (SQLException e) {
205                         logger.error("Error in TargetLockTest.getDBConnection()", e);
206                 }
207         }
208
209         private static void createTable() {
210                 String createString = "create table if not exists pooling.locks (resourceId VARCHAR(128), host VARCHAR(128), owner VARCHAR(128), expirationTime BIGINT, PRIMARY KEY (resourceId))";
211                 try (PreparedStatement createStmt = conn.prepareStatement(createString);) {
212                         createStmt.executeUpdate();
213                         
214                 } catch (SQLException e) {
215                         logger.error("Error in TargetLockTest.createTable()", e);
216                 }
217         }       
218          
219
220 }