aboutsummaryrefslogtreecommitdiffstats
path: root/feature-distributed-locking/src/main/java/org/onap/policy/distributed/locking/TargetLock.java
blob: 0853f125e6e8bfb5de197061e9c8524dadc4c35b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
/*
 * ============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=========================================================
 */
package org.onap.policy.distributed.locking;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.UUID;
import org.apache.commons.dbcp2.BasicDataSource;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class TargetLock {
	
	private static final Logger logger = LoggerFactory.getLogger(TargetLock.class);
	
	/**
	 * The Target resource we want to lock
	 */
	private String resourceId;
    
    /**
     * Data source used to connect to the DB containing locks.
     */
    private BasicDataSource dataSource;

	/**
	 * UUID 
	 */
	private UUID uuid;
	
	/**
	 * Owner
	 */
	private String owner;
	
	/**
	 * Constructs a TargetLock object.
	 * 
	 * @param resourceId ID of the entity we want to lock
	 * @param dataSource used to connect to the DB containing locks
	 */
	public TargetLock (String resourceId, UUID uuid, String owner, BasicDataSource dataSource) {
		this.resourceId = resourceId;
		this.uuid = uuid;
		this.owner = owner;
		this.dataSource = dataSource;
	}
	
	/**
	 * obtain a lock
     * @param holdSec the amount of time, in seconds, that the lock should be held
	 */
	public boolean lock(int holdSec) {
		
		return grabLock(TimeUnit.SECONDS.toMillis(holdSec));
	}
	
	/**
	 * Unlock a resource by deleting it's associated record in the db
	 */
	public boolean unlock() {
		return deleteLock();
	}
	
	/**
	 * "Grabs" lock by attempting to insert a new record in the db.
	 *  If the insert fails due to duplicate key error resource is already locked
	 *  so we call secondGrab. 
     * @param holdMs the amount of time, in milliseconds, that the lock should be held
	 */
	private boolean grabLock(long holdMs) {

		// try to insert a record into the table(thereby grabbing the lock)
		try (Connection conn = dataSource.getConnection();

				PreparedStatement statement = conn.prepareStatement(
						"INSERT INTO pooling.locks (resourceId, host, owner, expirationTime) values (?, ?, ?, ?)")) {
			
		    int i = 1;
			statement.setString(i++, this.resourceId);
			statement.setString(i++, this.uuid.toString());
			statement.setString(i++, this.owner);
			statement.setLong(i++, System.currentTimeMillis() + holdMs);
			statement.executeUpdate();
		}

		catch (SQLException e) {
			logger.error("error in TargetLock.grabLock()", e);
			return secondGrab(holdMs);
		}

		return true;
	}

	/**
	 * A second attempt at grabbing a lock. It first attempts to update the lock in case it is expired.
	 * If that fails, it attempts to insert a new record again
     * @param holdMs the amount of time, in milliseconds, that the lock should be held
	 */
	private boolean secondGrab(long holdMs) {

		try (Connection conn = dataSource.getConnection();

				PreparedStatement updateStatement = conn.prepareStatement(
						"UPDATE pooling.locks SET host = ?, owner = ?, expirationTime = ? WHERE resourceId = ? AND (owner = ? OR expirationTime <= ?)");

				PreparedStatement insertStatement = conn.prepareStatement(
						"INSERT INTO pooling.locks (resourceId, host, owner, expirationTime) values (?, ?, ?, ?)");) {

		    int i = 1;
			updateStatement.setString(i++, this.uuid.toString());
			updateStatement.setString(i++, this.owner);
			updateStatement.setLong(i++, System.currentTimeMillis() + holdMs);
            updateStatement.setString(i++, this.resourceId);
            updateStatement.setString(i++, this.owner);
			updateStatement.setLong(i++, System.currentTimeMillis());

			// The lock was expired and we grabbed it.
			// return true
			if (updateStatement.executeUpdate() == 1) {
				return true;
			}

			// If our update does not return 1 row, the lock either has not expired
			// or it was removed. Try one last grab
			else {
			    i = 1;
				insertStatement.setString(i++, this.resourceId);
				insertStatement.setString(i++, this.uuid.toString());
				insertStatement.setString(i++, this.owner);
				insertStatement.setLong(i++, System.currentTimeMillis() + holdMs);

				// If our insert returns 1 we successfully grabbed the lock
				return (insertStatement.executeUpdate() == 1);
			}

		} catch (SQLException e) {
			logger.error("error in TargetLock.secondGrab()", e);
			return false;
		}

	}
	
	/**
	 *To remove a lock we simply delete the record from the db 
	 */
	private boolean deleteLock() {

		try (Connection conn = dataSource.getConnection();

				PreparedStatement deleteStatement = conn.prepareStatement(
						"DELETE FROM pooling.locks WHERE resourceId = ? AND owner = ? AND host = ?")) {

			deleteStatement.setString(1, this.resourceId);
			deleteStatement.setString(2, this.owner);
			deleteStatement.setString(3, this.uuid.toString());

			return (deleteStatement.executeUpdate() == 1);

		} catch (SQLException e) {
			logger.error("error in TargetLock.deleteLock()", e);
			return false;
		}

	}

	/**
	 * Is the lock active
	 */
	public boolean isActive() {
		try (Connection conn = dataSource.getConnection();

				PreparedStatement selectStatement = conn.prepareStatement(
						"SELECT * FROM pooling.locks WHERE resourceId = ? AND host = ? AND owner= ? AND expirationTime >= ?")) {

			selectStatement.setString(1, this.resourceId);
			selectStatement.setString(2, this.uuid.toString());
			selectStatement.setString(3, this.owner);
			selectStatement.setLong(4, System.currentTimeMillis());
			try (ResultSet result = selectStatement.executeQuery()) {

				// This will return true if the
				// query returned at least one row
				return result.first();
			}

		}

		catch (SQLException e) {
			logger.error("error in TargetLock.isActive()", e);
			return false;
		}

	}

	/**
	 * Is the resource locked
	 */
	public boolean isLocked() {

		try (Connection conn = dataSource.getConnection();
			
				PreparedStatement selectStatement = conn
						.prepareStatement("SELECT * FROM pooling.locks WHERE resourceId = ? AND expirationTime >= ?")) {

			selectStatement.setString(1, this.resourceId);
			selectStatement.setLong(2, System.currentTimeMillis());
			try (ResultSet result = selectStatement.executeQuery()) {
				// This will return true if the
				// query returned at least one row
				return result.first();
			}
		}

		catch (SQLException e) {
			logger.error("error in TargetLock.isActive()", e);
			return false;
		}
	}

}