diff options
Diffstat (limited to 'feature-distributed-locking')
10 files changed, 135 insertions, 287 deletions
diff --git a/feature-distributed-locking/src/assembly/assemble_zip.xml b/feature-distributed-locking/src/assembly/assemble_zip.xml index 2112fbcd..3def9898 100644 --- a/feature-distributed-locking/src/assembly/assemble_zip.xml +++ b/feature-distributed-locking/src/assembly/assemble_zip.xml @@ -3,6 +3,7 @@ feature-distributed-locking ================================================================================ Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + Modifications Copyright (C) 2024 Nordix Foundation. ================================================================================ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -59,12 +60,6 @@ <excludes/> </fileSet> <fileSet> - <directory>src/main/feature/db</directory> - <outputDirectory>db</outputDirectory> - <fileMode>0744</fileMode> - <excludes/> - </fileSet> - <fileSet> <directory>src/main/feature/install</directory> <outputDirectory>install</outputDirectory> <fileMode>0744</fileMode> diff --git a/feature-distributed-locking/src/main/feature/config/feature-distributed-locking.properties b/feature-distributed-locking/src/main/feature/config/feature-distributed-locking.properties index 69629e15..fa311260 100644 --- a/feature-distributed-locking/src/main/feature/config/feature-distributed-locking.properties +++ b/feature-distributed-locking/src/main/feature/config/feature-distributed-locking.properties @@ -3,7 +3,7 @@ # ONAP # ================================================================================ # Copyright (C) 2018-2019, 2021-2022 AT&T Intellectual Property. All rights reserved. -# Modifications Copyright (C) 2023 Nordix Foundation. +# Modifications Copyright (C) 2023-2024 Nordix Foundation. # ================================================================================ # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -20,7 +20,7 @@ ### #Database properties -jakarta.persistence.jdbc.driver=org.mariadb.jdbc.Driver +jakarta.persistence.jdbc.driver=${envd:JDBC_DRIVER} jakarta.persistence.jdbc.url=${envd:JDBC_URL}pooling${envd:JDBC_OPTS} jakarta.persistence.jdbc.user=${envd:SQL_USER} jakarta.persistence.jdbc.password=${envd:SQL_PASSWORD} diff --git a/feature-distributed-locking/src/main/feature/db/pooling/sql/1804-distributedlocking.downgrade.sql b/feature-distributed-locking/src/main/feature/db/pooling/sql/1804-distributedlocking.downgrade.sql deleted file mode 100644 index cd1b815d..00000000 --- a/feature-distributed-locking/src/main/feature/db/pooling/sql/1804-distributedlocking.downgrade.sql +++ /dev/null @@ -1,20 +0,0 @@ -# ============LICENSE_START======================================================= -# feature-distributed-locking -# ================================================================================ -# Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. -# ================================================================================ -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# ============LICENSE_END========================================================= - -use pooling; -drop table if exists locks;
\ No newline at end of file diff --git a/feature-distributed-locking/src/main/feature/db/pooling/sql/1804-distributedlocking.upgrade.sql b/feature-distributed-locking/src/main/feature/db/pooling/sql/1804-distributedlocking.upgrade.sql deleted file mode 100644 index 07b30738..00000000 --- a/feature-distributed-locking/src/main/feature/db/pooling/sql/1804-distributedlocking.upgrade.sql +++ /dev/null @@ -1,30 +0,0 @@ -# ============LICENSE_START======================================================= -# feature-distributed-locking -# ================================================================================ -# Copyright (C) 2018, 2022 AT&T Intellectual Property. All rights reserved. -# ================================================================================ -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# ============LICENSE_END========================================================= - -SET foreign_key_checks=0; - -CREATE TABLE if NOT EXISTS pooling.locks( - resourceId VARCHAR(128), - host VARCHAR(128), - owner VARCHAR(128), - expirationTime BIGINT, - PRIMARY KEY (resourceId), - INDEX idx_expirationTime(expirationTime), - INDEX idx_host(host)); - -SET foreign_key_checks=1;
\ No newline at end of file diff --git a/feature-distributed-locking/src/main/feature/db/pooling/sql/1811-distributedlocking.downgrade.sql b/feature-distributed-locking/src/main/feature/db/pooling/sql/1811-distributedlocking.downgrade.sql deleted file mode 100644 index 55a883f2..00000000 --- a/feature-distributed-locking/src/main/feature/db/pooling/sql/1811-distributedlocking.downgrade.sql +++ /dev/null @@ -1,19 +0,0 @@ -# ============LICENSE_START======================================================= -# feature-distributed-locking -# ================================================================================ -# Copyright (C) 2018, 2021 AT&T Intellectual Property. All rights reserved. -# ================================================================================ -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# ============LICENSE_END========================================================= - -ALTER TABLE pooling.locks modify if exists expirationTime bigint(20) default 0; diff --git a/feature-distributed-locking/src/main/feature/db/pooling/sql/1811-distributedlocking.upgrade.sql b/feature-distributed-locking/src/main/feature/db/pooling/sql/1811-distributedlocking.upgrade.sql deleted file mode 100644 index 0cdad5b9..00000000 --- a/feature-distributed-locking/src/main/feature/db/pooling/sql/1811-distributedlocking.upgrade.sql +++ /dev/null @@ -1,23 +0,0 @@ -# ============LICENSE_START======================================================= -# feature-distributed-locking -# ================================================================================ -# Copyright (C) 2018, 2021-2022 AT&T Intellectual Property. All rights reserved. -# ================================================================================ -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# ============LICENSE_END========================================================= - -SET foreign_key_checks=0; - -ALTER TABLE pooling.locks MODIFY expirationTime TIMESTAMP DEFAULT '1971-01-01 00:00:00.000000'; - -SET foreign_key_checks=1; diff --git a/feature-distributed-locking/src/main/feature/install/disable b/feature-distributed-locking/src/main/feature/install/disable deleted file mode 100644 index be455734..00000000 --- a/feature-distributed-locking/src/main/feature/install/disable +++ /dev/null @@ -1,26 +0,0 @@ -#!/usr/bin/env sh - -# ============LICENSE_START======================================================= -# ONAP -# ================================================================================ -# Copyright (C) 2018-2021 AT&T Intellectual Property. All rights reserved. -# ================================================================================ -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# ============LICENSE_END========================================================= - -if [ "${DEBUG}" = "y" ]; then - set -x -fi - -${POLICY_HOME}/bin/db-migrator -s pooling -o downgrade - diff --git a/feature-distributed-locking/src/main/feature/install/enable b/feature-distributed-locking/src/main/feature/install/enable deleted file mode 100644 index af202f56..00000000 --- a/feature-distributed-locking/src/main/feature/install/enable +++ /dev/null @@ -1,26 +0,0 @@ -#!/usr/bin/env sh - -# ============LICENSE_START======================================================= -# ONAP -# ================================================================================ -# Copyright (C) 2018-2021 AT&T Intellectual Property. All rights reserved. -# ================================================================================ -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# ============LICENSE_END========================================================= - -if [ "${DEBUG}" = "y" ]; then - set -x -fi - -${POLICY_HOME}/bin/db-migrator -s pooling -o upgrade - diff --git a/feature-distributed-locking/src/main/java/org/onap/policy/distributed/locking/DistributedLockManager.java b/feature-distributed-locking/src/main/java/org/onap/policy/distributed/locking/DistributedLockManager.java index d7f857eb..e9f1453a 100644 --- a/feature-distributed-locking/src/main/java/org/onap/policy/distributed/locking/DistributedLockManager.java +++ b/feature-distributed-locking/src/main/java/org/onap/policy/distributed/locking/DistributedLockManager.java @@ -3,6 +3,7 @@ * ONAP * ================================================================================ * Copyright (C) 2019-2022 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2024 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,6 +25,9 @@ import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.SQLTransientException; +import java.sql.Timestamp; +import java.time.Instant; +import java.time.temporal.ChronoUnit; import java.util.HashSet; import java.util.Map; import java.util.Properties; @@ -57,11 +61,8 @@ import org.slf4j.LoggerFactory; * Distributed implementation of the Lock Feature. Maintains locks across servers using a * shared DB. * - * <p/> - * Note: this implementation does <i>not</i> honor the waitForLocks={@code true} - * parameter. - * - * <p/> + * <p>Note: this implementation does <i>not</i> honor the waitForLocks={@code true} + * parameter.<p/> * Additional Notes: * <dl> * <li>The <i>owner</i> field in the DB is not derived from the lock's owner info, but is @@ -77,7 +78,7 @@ import org.slf4j.LoggerFactory; * </dl> */ public class DistributedLockManager extends LockManager<DistributedLockManager.DistributedLock> - implements PolicyEngineFeatureApi { + implements PolicyEngineFeatureApi { private static final Logger logger = LoggerFactory.getLogger(DistributedLockManager.class); @@ -141,11 +142,11 @@ public class DistributedLockManager extends LockManager<DistributedLockManager.D } @Override - public PolicyResourceLockManager beforeCreateLockManager(PolicyEngine engine, Properties properties) { + public PolicyResourceLockManager beforeCreateLockManager() { try { this.pdpName = PolicyEngineConstants.getManager().getPdpName(); - this.featProps = new DistributedLockProperties(getProperties(CONFIGURATION_PROPERTIES_NAME)); + this.featProps = new DistributedLockProperties(getProperties()); this.dataSource = makeDataSource(); return this; @@ -176,9 +177,9 @@ public class DistributedLockManager extends LockManager<DistributedLockManager.D * Make data source. * * @return a new, pooled data source - * @throws Exception exception + * @throws SQLException exception */ - protected BasicDataSource makeDataSource() throws Exception { + protected BasicDataSource makeDataSource() throws SQLException { var props = new Properties(); props.put("driverClassName", featProps.getDbDriver()); props.put("url", featProps.getDbUrl()); @@ -199,7 +200,7 @@ public class DistributedLockManager extends LockManager<DistributedLockManager.D logger.info("deleting all expired locks from the DB"); try (var conn = dataSource.getConnection(); - var stmt = conn.prepareStatement("DELETE FROM pooling.locks WHERE expirationTime <= now()")) { + var stmt = conn.prepareStatement("DELETE FROM pooling.locks WHERE expirationTime <= now()")) { int ndel = stmt.executeUpdate(); logger.info("deleted {} expired locks from the DB", ndel); @@ -398,17 +399,17 @@ public class DistributedLockManager extends LockManager<DistributedLockManager.D /** * Constructs the object. * - * @param state initial state of the lock + * @param state initial state of the lock * @param resourceId identifier of the resource to be locked - * @param ownerKey information identifying the owner requesting the lock - * @param holdSec amount of time, in seconds, for which the lock should be held, - * after which it will automatically be released - * @param callback callback to be invoked once the lock is granted, or - * subsequently lost; must not be {@code null} - * @param feature feature containing this lock + * @param ownerKey information identifying the owner requesting the lock + * @param holdSec amount of time, in seconds, for which the lock should be held, + * after which it will automatically be released + * @param callback callback to be invoked once the lock is granted, or + * subsequently lost; must not be {@code null} + * @param feature feature containing this lock */ public DistributedLock(LockState state, String resourceId, String ownerKey, int holdSec, LockCallback callback, - DistributedLockManager feature) { + DistributedLockManager feature) { super(state, resourceId, ownerKey, holdSec, callback); this.feature = feature; @@ -531,7 +532,6 @@ public class DistributedLockManager extends LockManager<DistributedLockManager.D * there are no more requests in the queue. * * @param prevReq the previous request that was just run - * * @return the next request, or {@code null} if the queue is empty */ private synchronized RunnableWithEx getNextRequest(RunnableWithEx prevReq) { @@ -699,19 +699,19 @@ public class DistributedLockManager extends LockManager<DistributedLockManager.D * Inserts the lock into the DB. * * @param conn DB connection - * @return {@code true} if a record was successfully inserted, {@code false} - * otherwise + * @return {@code true} if a record was successfully inserted, {@code false}otherwise * @throws SQLException if a DB error occurs */ protected boolean doDbInsert(Connection conn) throws SQLException { logger.info("insert lock record {}", this); - try (var stmt = conn.prepareStatement("INSERT INTO pooling.locks (resourceId, host, owner, expirationTime) " - + "values (?, ?, ?, timestampadd(second, ?, now()))")) { + var time = Instant.now().plus(getHoldSec(), ChronoUnit.SECONDS); + String sql = "INSERT INTO pooling.locks (resourceId, host, owner, expirationTime) values (?, ?, ?, ?)"; + try (var stmt = conn.prepareStatement(sql)) { stmt.setString(1, getResourceId()); stmt.setString(2, feature.pdpName); stmt.setString(3, feature.uuidString); - stmt.setInt(4, getHoldSec()); + stmt.setTimestamp(4, new Timestamp(time.toEpochMilli())); stmt.executeUpdate(); @@ -726,20 +726,21 @@ public class DistributedLockManager extends LockManager<DistributedLockManager.D * Updates the lock in the DB. * * @param conn DB connection - * @return {@code true} if a record was successfully updated, {@code false} - * otherwise + * @return {@code true} if a record was successfully updated, {@code false} otherwise * @throws SQLException if a DB error occurs */ protected boolean doDbUpdate(Connection conn) throws SQLException { logger.info("update lock record {}", this); - try (var stmt = conn.prepareStatement("UPDATE pooling.locks SET resourceId=?, host=?, owner=?," - + " expirationTime=timestampadd(second, ?, now()) WHERE resourceId=?" - + " AND ((host=? AND owner=?) OR expirationTime < now())")) { + var time = Instant.now().plus(getHoldSec(), ChronoUnit.SECONDS); + var query = "UPDATE pooling.locks SET resourceId=?, host=?, owner=?," + + " expirationTime=? WHERE resourceId=?" + + " AND ((host=? AND owner=?) OR expirationTime < now())"; + try (var stmt = conn.prepareStatement(query)) { stmt.setString(1, getResourceId()); stmt.setString(2, feature.pdpName); stmt.setString(3, feature.uuidString); - stmt.setInt(4, getHoldSec()); + stmt.setTimestamp(4, new Timestamp(time.toEpochMilli())); stmt.setString(5, getResourceId()); stmt.setString(6, this.hostName); @@ -764,8 +765,8 @@ public class DistributedLockManager extends LockManager<DistributedLockManager.D */ protected void doDbDelete(Connection conn) throws SQLException { logger.info("delete lock record {}", this); - try (var stmt = conn - .prepareStatement("DELETE FROM pooling.locks WHERE resourceId=? AND host=? AND owner=?")) { + var query = "DELETE FROM pooling.locks WHERE resourceId=? AND host=? AND owner=?"; + try (var stmt = conn.prepareStatement(query)) { stmt.setString(1, getResourceId()); stmt.setString(2, this.hostName); @@ -793,8 +794,8 @@ public class DistributedLockManager extends LockManager<DistributedLockManager.D @Override public String toString() { return "DistributedLock [state=" + getState() + ", resourceId=" + getResourceId() + ", ownerKey=" - + getOwnerKey() + ", holdSec=" + getHoldSec() + ", hostName=" + hostName + ", uuidString=" - + uuidString + "]"; + + getOwnerKey() + ", holdSec=" + getHoldSec() + ", hostName=" + hostName + ", uuidString=" + + uuidString + "]"; } } @@ -811,12 +812,13 @@ public class DistributedLockManager extends LockManager<DistributedLockManager.D // these may be overridden by junit tests - protected Properties getProperties(String fileName) { - return SystemPersistenceConstants.getManager().getProperties(fileName); + protected Properties getProperties() { + return SystemPersistenceConstants.getManager().getProperties( + DistributedLockManager.CONFIGURATION_PROPERTIES_NAME); } protected DistributedLock makeLock(LockState state, String resourceId, String ownerKey, int holdSec, - LockCallback callback) { + LockCallback callback) { return new DistributedLock(state, resourceId, ownerKey, holdSec, callback, this); } } diff --git a/feature-distributed-locking/src/test/java/org/onap/policy/distributed/locking/DistributedLockManagerTest.java b/feature-distributed-locking/src/test/java/org/onap/policy/distributed/locking/DistributedLockManagerTest.java index 2e173cf0..579d53cc 100644 --- a/feature-distributed-locking/src/test/java/org/onap/policy/distributed/locking/DistributedLockManagerTest.java +++ b/feature-distributed-locking/src/test/java/org/onap/policy/distributed/locking/DistributedLockManagerTest.java @@ -141,12 +141,12 @@ class DistributedLockManagerTest { private LockCallback callback; @Mock - private BasicDataSource datasrc; + private BasicDataSource dataSource; private DistributedLock lock; - private AtomicInteger nactive; - private AtomicInteger nsuccesses; + private AtomicInteger numActive; + private AtomicInteger numSuccess; private DistributedLockManager feature; AutoCloseable closeable; @@ -204,8 +204,8 @@ class DistributedLockManagerTest { session.setPolicySession(); - nactive = new AtomicInteger(0); - nsuccesses = new AtomicInteger(0); + numActive = new AtomicInteger(0); + numSuccess = new AtomicInteger(0); cleanDb(); @@ -248,7 +248,7 @@ class DistributedLockManagerTest { @Test void testBeforeCreateLockManager() { - assertSame(feature, feature.beforeCreateLockManager(engine, new Properties())); + assertSame(feature, feature.beforeCreateLockManager()); } /** @@ -260,13 +260,12 @@ class DistributedLockManagerTest { feature = new MyLockingFeature(false) { @Override - protected Properties getProperties(String fileName) { + protected Properties getProperties() { throw new IllegalArgumentException(EXPECTED_EXCEPTION); } }; - Properties props = new Properties(); - assertThatThrownBy(() -> feature.beforeCreateLockManager(engine, props)) + assertThatThrownBy(() -> feature.beforeCreateLockManager()) .isInstanceOf(DistributedLockManagerException.class); } @@ -317,7 +316,6 @@ class DistributedLockManagerTest { /** * Tests deleteExpiredDbLocks(), when getConnection() throws an exception. - * */ @Test void testDeleteExpiredDbLocksEx() { @@ -347,7 +345,6 @@ class DistributedLockManagerTest { /** * Tests afterStop(), when the data source throws an exception when close() is called. - * */ @Test void testAfterStopEx() { @@ -416,10 +413,10 @@ class DistributedLockManagerTest { void testCreateLockNotLatestInstance() { DistributedLockManager.setLatestInstance(null); - Lock lock = feature.createLock(RESOURCE, OWNER_KEY, HOLD_SEC, callback, false); - assertTrue(lock.isUnavailable()); + Lock newLock = feature.createLock(RESOURCE, OWNER_KEY, HOLD_SEC, callback, false); + assertTrue(newLock.isUnavailable()); verify(callback, never()).lockAvailable(any()); - verify(callback).lockUnavailable(lock); + verify(callback).lockUnavailable(newLock); } @Test @@ -532,11 +529,11 @@ class DistributedLockManagerTest { feature = new MyLockingFeature(true) { @Override - protected BasicDataSource makeDataSource() throws Exception { + protected BasicDataSource makeDataSource() throws SQLException { // get the real data source BasicDataSource src2 = super.makeDataSource(); - when(datasrc.getConnection()).thenAnswer(answer -> { + when(dataSource.getConnection()).thenAnswer(answer -> { DistributedLock lck = freeLock.getAndSet(null); if (lck != null) { // free it @@ -549,7 +546,7 @@ class DistributedLockManagerTest { return src2.getConnection(); }); - return datasrc; + return dataSource; } }; @@ -596,11 +593,11 @@ class DistributedLockManagerTest { @Test void testDistributedLockNoArgs() { - DistributedLock lock = new DistributedLock(); - assertNull(lock.getResourceId()); - assertNull(lock.getOwnerKey()); - assertNull(lock.getCallback()); - assertEquals(0, lock.getHoldSec()); + DistributedLock newLock = new DistributedLock(); + assertNull(newLock.getResourceId()); + assertNull(newLock.getOwnerKey()); + assertNull(newLock.getCallback()); + assertEquals(0, newLock.getHoldSec()); } @Test @@ -615,15 +612,15 @@ class DistributedLockManagerTest { @Test void testDistributedLockSerializable() throws Exception { - DistributedLock lock = getLock(RESOURCE, callback); - lock = roundTrip(lock); + DistributedLock newLock = getLock(RESOURCE, callback); + newLock = roundTrip(newLock); - assertTrue(lock.isWaiting()); + assertTrue(newLock.isWaiting()); - assertEquals(RESOURCE, lock.getResourceId()); - assertEquals(OWNER_KEY, lock.getOwnerKey()); - assertNull(lock.getCallback()); - assertEquals(HOLD_SEC, lock.getHoldSec()); + assertEquals(RESOURCE, newLock.getResourceId()); + assertEquals(OWNER_KEY, newLock.getOwnerKey()); + assertNull(newLock.getCallback()); + assertEquals(HOLD_SEC, newLock.getHoldSec()); } @Test @@ -690,13 +687,13 @@ class DistributedLockManagerTest { */ @Test void testDistributedLockFreeSerialized() throws Exception { - DistributedLock lock = getLock(RESOURCE, callback); + DistributedLock newLock = getLock(RESOURCE, callback); feature = new MyLockingFeature(true); - lock = roundTrip(lock); - assertTrue(lock.free()); - assertTrue(lock.isUnavailable()); + newLock = roundTrip(newLock); + assertTrue(newLock.free()); + assertTrue(newLock.isUnavailable()); } /** @@ -706,13 +703,13 @@ class DistributedLockManagerTest { */ @Test void testDistributedLockFreeNoFeature() throws Exception { - DistributedLock lock = getLock(RESOURCE, callback); + DistributedLock newLock = getLock(RESOURCE, callback); DistributedLockManager.setLatestInstance(null); - lock = roundTrip(lock); - assertFalse(lock.free()); - assertTrue(lock.isUnavailable()); + newLock = roundTrip(newLock); + assertFalse(newLock.free()); + assertTrue(newLock.isUnavailable()); } /** @@ -788,28 +785,28 @@ class DistributedLockManagerTest { */ @Test void testDistributedLockExtendSerialized() throws Exception { - DistributedLock lock = getLock(RESOURCE, callback); + DistributedLock newLock = getLock(RESOURCE, callback); // run doLock runLock(0, 0); - assertTrue(lock.isActive()); + assertTrue(newLock.isActive()); feature = new MyLockingFeature(true); - lock = roundTrip(lock); - assertTrue(lock.isActive()); + newLock = roundTrip(newLock); + assertTrue(newLock.isActive()); - LockCallback scallback = mock(LockCallback.class); + LockCallback mockCallback = mock(LockCallback.class); - lock.extend(HOLD_SEC, scallback); - assertTrue(lock.isWaiting()); + newLock.extend(HOLD_SEC, mockCallback); + assertTrue(newLock.isWaiting()); // run doExtend (in new feature) runLock(0, 0); - assertTrue(lock.isActive()); + assertTrue(newLock.isActive()); - verify(scallback).lockAvailable(lock); - verify(scallback, never()).lockUnavailable(lock); + verify(mockCallback).lockAvailable(newLock); + verify(mockCallback, never()).lockUnavailable(newLock); } /** @@ -819,24 +816,24 @@ class DistributedLockManagerTest { */ @Test void testDistributedLockExtendNoFeature() throws Exception { - DistributedLock lock = getLock(RESOURCE, callback); + DistributedLock newLock = getLock(RESOURCE, callback); // run doLock runLock(0, 0); - assertTrue(lock.isActive()); + assertTrue(newLock.isActive()); DistributedLockManager.setLatestInstance(null); - lock = roundTrip(lock); - assertTrue(lock.isActive()); + newLock = roundTrip(newLock); + assertTrue(newLock.isActive()); LockCallback scallback = mock(LockCallback.class); - lock.extend(HOLD_SEC, scallback); - assertTrue(lock.isUnavailable()); + newLock.extend(HOLD_SEC, scallback); + assertTrue(newLock.isUnavailable()); - verify(scallback, never()).lockAvailable(lock); - verify(scallback).lockUnavailable(lock); + verify(scallback, never()).lockAvailable(newLock); + verify(scallback).lockUnavailable(newLock); } /** @@ -964,7 +961,7 @@ class DistributedLockManagerTest { feature = new MyLockingFeature(true) { @Override protected DistributedLock makeLock(LockState state, String resourceId, String ownerKey, int holdSec, - LockCallback callback) { + LockCallback callback) { return new DistributedLock(state, resourceId, ownerKey, holdSec, callback, feature) { private static final long serialVersionUID = 1L; @@ -1015,13 +1012,13 @@ class DistributedLockManagerTest { @Test void testDistributedLockDoRequestRunExWaiting() throws SQLException { // throw run-time exception - when(datasrc.getConnection()).thenThrow(new IllegalStateException(EXPECTED_EXCEPTION)); + when(dataSource.getConnection()).thenThrow(new IllegalStateException(EXPECTED_EXCEPTION)); // use a data source that throws an exception when getConnection() is called feature = new MyLockingFeature(true) { @Override protected BasicDataSource makeDataSource() { - return datasrc; + return dataSource; } }; @@ -1045,7 +1042,7 @@ class DistributedLockManagerTest { @Test void testDistributedLockDoRequestRunExUnavailable() throws SQLException { // throw run-time exception - when(datasrc.getConnection()).thenAnswer(answer -> { + when(dataSource.getConnection()).thenAnswer(answer -> { lock.free(); throw new IllegalStateException(EXPECTED_EXCEPTION); }); @@ -1054,7 +1051,7 @@ class DistributedLockManagerTest { feature = new MyLockingFeature(true) { @Override protected BasicDataSource makeDataSource() { - return datasrc; + return dataSource; } }; @@ -1232,7 +1229,6 @@ class DistributedLockManagerTest { /** * Tests doUnlock() when a DB exception is thrown. - * */ @Test void testDistributedLockDoUnlockEx() { @@ -1337,7 +1333,6 @@ class DistributedLockManagerTest { /** * Tests doExtend() when both update and insert fail. - * */ @Test void testDistributedLockDoExtendNeitherSucceeds() { @@ -1348,7 +1343,7 @@ class DistributedLockManagerTest { feature = new MyLockingFeature(true) { @Override protected DistributedLock makeLock(LockState state, String resourceId, String ownerKey, int holdSec, - LockCallback callback) { + LockCallback callback) { return new DistributedLock(state, resourceId, ownerKey, holdSec, callback, feature) { private static final long serialVersionUID = 1L; private int ntimes = 0; @@ -1437,7 +1432,7 @@ class DistributedLockManagerTest { feature = new DistributedLockManager(); // this should create a thread pool - feature.beforeCreateLockManager(engine, new Properties()); + feature.beforeCreateLockManager(); feature.afterStart(engine); assertThatCode(this::shutdownFeature).doesNotThrowAnyException(); @@ -1447,14 +1442,14 @@ class DistributedLockManagerTest { * Performs a multithreaded test of the locking facility. * * @throws InterruptedException if the current thread is interrupted while waiting for - * the background threads to complete + * the background threads to complete */ @Test void testMultiThreaded() throws InterruptedException { ReflectionTestUtils.setField(PolicyEngineConstants.getManager(), POLICY_ENGINE_EXECUTOR_FIELD, realExec); feature = new DistributedLockManager(); - feature.beforeCreateLockManager(PolicyEngineConstants.getManager(), new Properties()); + feature.beforeCreateLockManager(); feature.afterStart(PolicyEngineConstants.getManager()); List<MyThread> threads = new ArrayList<>(MAX_THREADS); @@ -1475,7 +1470,7 @@ class DistributedLockManagerTest { } } - assertTrue(nsuccesses.get() > 0); + assertTrue(numSuccess.get() > 0); } private DistributedLock getLock(String resource, LockCallback callback) { @@ -1511,9 +1506,9 @@ class DistributedLockManagerTest { /** * Runs a lock action (e.g., doLock, doUnlock). * - * @param nskip number of actions in the work queue to skip + * @param nskip number of actions in the work queue to skip * @param nadditional number of additional actions that appear in the work queue - * <i>after</i> the desired action + * <i>after</i> the desired action */ void runLock(int nskip, int nadditional) { ArgumentCaptor<Runnable> captor = ArgumentCaptor.forClass(Runnable.class); @@ -1544,7 +1539,7 @@ class DistributedLockManagerTest { */ private int getRecordCount() throws SQLException { try (PreparedStatement stmt = conn.prepareStatement("SELECT count(*) FROM pooling.locks"); - ResultSet result = stmt.executeQuery()) { + ResultSet result = stmt.executeQuery()) { if (result.next()) { return result.getInt(1); @@ -1561,16 +1556,16 @@ class DistributedLockManagerTest { * * @param resourceId ID of the resource of interest * @param uuidString UUID string of the owner - * @param holdSec seconds for which the lock was to be held - * @param tbegin earliest time, in milliseconds, at which the record could have been - * inserted into the DB + * @param holdSec seconds for which the lock was to be held + * @param tbegin earliest time, in milliseconds, at which the record could have been + * inserted into the DB * @return {@code true} if a record is found, {@code false} otherwise * @throws SQLException if an error occurs accessing the DB */ private boolean recordInRange(String resourceId, String uuidString, int holdSec, long tbegin) throws SQLException { try (PreparedStatement stmt = - conn.prepareStatement("SELECT timestampdiff(second, now(), expirationTime) FROM pooling.locks" - + " WHERE resourceId=? AND host=? AND owner=?")) { + conn.prepareStatement("SELECT timestampdiff(second, now(), expirationTime) FROM pooling.locks" + + " WHERE resourceId=? AND host=? AND owner=?")) { stmt.setString(1, resourceId); stmt.setString(2, feature.getPdpName()); @@ -1592,8 +1587,8 @@ class DistributedLockManagerTest { /** * Inserts a record into the DB. * - * @param resourceId ID of the resource of interest - * @param uuidString UUID string of the owner + * @param resourceId ID of the resource of interest + * @param uuidString UUID string of the owner * @param expireOffset offset, in seconds, from "now", at which the lock should expire * @throws SQLException if an error occurs accessing the DB */ @@ -1604,8 +1599,8 @@ class DistributedLockManagerTest { private void insertRecord(String resourceId, String hostName, String uuidString, int expireOffset) throws SQLException { try (PreparedStatement stmt = - conn.prepareStatement("INSERT INTO pooling.locks (resourceId, host, owner, expirationTime) " - + "values (?, ?, ?, timestampadd(second, ?, now()))")) { + conn.prepareStatement("INSERT INTO pooling.locks (resourceId, host, owner, expirationTime) " + + "values (?, ?, ?, timestampadd(second, ?, now()))")) { stmt.setString(1, resourceId); stmt.setString(2, hostName); @@ -1619,8 +1614,8 @@ class DistributedLockManagerTest { /** * Updates a record in the DB. * - * @param resourceId ID of the resource of interest - * @param newUuid UUID string of the <i>new</i> owner + * @param resourceId ID of the resource of interest + * @param newUuid UUID string of the <i>new</i> owner * @param expireOffset offset, in seconds, from "now", at which the lock should expire * @throws SQLException if an error occurs accessing the DB */ @@ -1650,7 +1645,7 @@ class DistributedLockManagerTest { ReflectionTestUtils.setField(PolicyEngineConstants.getManager(), POLICY_ENGINE_EXECUTOR_FIELD, exsvc); if (init) { - beforeCreateLockManager(engine, new Properties()); + beforeCreateLockManager(); start(); afterStart(engine); } @@ -1671,14 +1666,14 @@ class DistributedLockManagerTest { this.isTransient = isTransient; - this.beforeCreateLockManager(engine, new Properties()); + this.beforeCreateLockManager(); this.start(); this.afterStart(engine); } @Override - protected BasicDataSource makeDataSource() throws Exception { - lenient().when(datasrc.getConnection()).thenAnswer(answer -> { + protected BasicDataSource makeDataSource() throws SQLException { + lenient().when(dataSource.getConnection()).thenAnswer(answer -> { if (freeLock) { freeLock = false; lock.free(); @@ -1687,9 +1682,9 @@ class DistributedLockManagerTest { throw makeEx(); }); - doThrow(makeEx()).when(datasrc).close(); + doThrow(makeEx()).when(dataSource).close(); - return datasrc; + return dataSource; } protected SQLException makeEx() { @@ -1715,7 +1710,7 @@ class DistributedLockManagerTest { @Override protected DistributedLock makeLock(LockState state, String resourceId, String ownerKey, int holdSec, - LockCallback callback) { + LockCallback callback) { return new DistributedLock(state, resourceId, ownerKey, holdSec, callback, feature) { private static final long serialVersionUID = 1L; @@ -1785,27 +1780,27 @@ class DistributedLockManagerTest { } }; - Lock lock = feature.createLock(RESOURCE, getName(), HOLD_SEC, cb, false); + Lock newLock = feature.createLock(RESOURCE, getName(), HOLD_SEC, cb, false); // wait for callback, whether available or unavailable assertTrue(sem.tryAcquire(5, TimeUnit.SECONDS)); - if (!lock.isActive()) { + if (!newLock.isActive()) { return; } - nsuccesses.incrementAndGet(); + numSuccess.incrementAndGet(); - assertEquals(1, nactive.incrementAndGet()); + assertEquals(1, numActive.incrementAndGet()); - lock.extend(HOLD_SEC2, cb); + newLock.extend(HOLD_SEC2, cb); assertTrue(sem.tryAcquire(5, TimeUnit.SECONDS)); - assertTrue(lock.isActive()); + assertTrue(newLock.isActive()); // decrement BEFORE free() - nactive.decrementAndGet(); + numActive.decrementAndGet(); - assertTrue(lock.free()); - assertTrue(lock.isUnavailable()); + assertTrue(newLock.free()); + assertTrue(newLock.isUnavailable()); } catch (InterruptedException e) { Thread.currentThread().interrupt(); |