Repository navigation
Expand file tree
/
Copy pathMerovingian.java
More file actions
351 lines (310 loc) · 11.3 KB
/
Copy pathMerovingian.java
File metadata and controls
351 lines (310 loc) · 11.3 KB
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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// 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.
package com.cloud.utils.db;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Savepoint;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import org.apache.log4j.Logger;
import com.cloud.utils.Pair;
import com.cloud.utils.Ternary;
import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.utils.net.MacAddress;
import com.cloud.utils.time.InaccurateClock;
public class Merovingian {
private static final Logger s_logger = Logger.getLogger(Merovingian.class);
private static final String ACQUIRE_SQL = "INSERT IGNORE INTO op_lock (op_lock.key, op_lock.mac, op_lock.ip, op_lock.thread) VALUES (?, ?, ?, ?)";
private static final String INQUIRE_SQL = "SELECT op_lock.ip FROM op_lock WHERE op_lock.key = ?";
private static final String RELEASE_SQL = "DELETE FROM op_lock WHERE op_lock.key = ?";
private static final String CLEAR_SQL = "DELETE FROM op_lock WHERE op_lock.mac = ? AND op_lock.ip = ?";
private final static HashMap<String, Pair<Lock, Integer>> s_memLocks = new HashMap<String, Pair<Lock, Integer>>(1027);
private final LinkedHashMap<String, Ternary<Savepoint, Integer, Long>> _locks = new LinkedHashMap<String, Ternary<Savepoint, Integer, Long>>();
private int _previousIsolation = Connection.TRANSACTION_NONE;
private final static String s_macAddress;
private final static String s_ipAddress;
static {
s_macAddress = MacAddress.getMacAddress().toString(":");
String address = null;
try {
InetAddress addr = InetAddress.getLocalHost();
address = addr.getHostAddress().toString();
} catch (UnknownHostException e) {
address = "127.0.0.1";
}
s_ipAddress = address;
}
Connection _conn = null;
public Merovingian(short dbId) {
_conn = null;
}
protected void checkIsolationLevel(Connection conn) throws SQLException {
PreparedStatement pstmt = conn.prepareStatement("SELECT @@global.tx_isolation, @@session.tx_isolation;");
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
s_logger.info("global isolation = " + rs.getString(1));
s_logger.info("session isolation = " + rs.getString(2));
}
}
protected Connection getConnection(String key, boolean test) {
try {
if (_conn != null) {
return _conn;
}
_conn = Transaction.getStandaloneConnection();
if (_previousIsolation == Connection.TRANSACTION_NONE) {
_previousIsolation = _conn.getTransactionIsolation();
_conn.setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
if (!test && !_conn.getAutoCommit()) {
_conn.setAutoCommit(false);
}
}
return _conn;
} catch (SQLException e) {
try {
_conn.rollback();
} catch (SQLException e1) {
}
throw new CloudRuntimeException("Unable to acquire db connection for locking " + key, e);
}
}
public boolean acquire(String key, int timeInSeconds) {
Pair<Lock, Integer> memLock = null;
boolean acquiredDbLock = false;
boolean acquiredMemLock = false;
try {
synchronized(s_memLocks) {
memLock = s_memLocks.get(key);
if (memLock == null) {
Lock l = new ReentrantLock(true);
memLock = new Pair<Lock, Integer>(l, 0);
s_memLocks.put(key, memLock);
}
memLock.second(memLock.second() + 1);
}
if (!memLock.first().tryLock(timeInSeconds, TimeUnit.SECONDS)) {
return false;
}
acquiredMemLock = true;
Ternary<Savepoint, Integer, Long> lock = _locks.get(key);
if (lock != null) {
lock.second(lock.second() + 1);
if (s_logger.isTraceEnabled()) {
s_logger.trace("Lock: Reacquiring " + key + " Count: " + lock.second());
}
acquiredDbLock = true;
return true;
}
long startTime = InaccurateClock.getTime();
while ((InaccurateClock.getTime() - startTime) < (timeInSeconds * 1000)) {
if (isLocked(key)) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
} else {
acquiredDbLock = doAcquire(key);
if (acquiredDbLock) {
return true;
}
}
}
if (s_logger.isTraceEnabled()) {
s_logger.trace("Lock: Timed out on acquiring lock " + key);
}
return false;
} catch (InterruptedException e) {
s_logger.debug("Interrupted while trying to acquire " + key);
return false;
} finally {
if (!acquiredMemLock || !acquiredDbLock) {
synchronized(s_memLocks) {
if (memLock.second(memLock.second() - 1) <= 0) {
s_memLocks.remove(key);
}
}
}
if (acquiredMemLock && !acquiredDbLock) {
memLock.first().unlock();
}
}
}
protected boolean doAcquire(String key) {
Connection conn = getConnection(key, true);
PreparedStatement pstmt = null;
Savepoint sp = null;
try {
sp = conn.setSavepoint(key);
} catch (SQLException e) {
s_logger.warn("Unable to set save point " + key);
return false;
}
try {
long startTime = InaccurateClock.getTime();
try {
pstmt = conn.prepareStatement(ACQUIRE_SQL);
pstmt.setString(1, key);
pstmt.setString(2, s_macAddress);
pstmt.setString(3, s_ipAddress);
pstmt.setString(4, Thread.currentThread().getName());
String exceptionMessage = null;
int rows = pstmt.executeUpdate();
if (rows == 1) {
if (s_logger.isTraceEnabled()) {
s_logger.trace("Lock: lock acquired for " + key);
}
Ternary<Savepoint, Integer, Long> lock = new Ternary<Savepoint, Integer, Long>(sp, 1, InaccurateClock.getTime());
_locks.put(key, lock);
return true;
}
} catch(SQLException e) {
s_logger.warn("Lock: Retrying lock " + key + ". Waited " + (InaccurateClock.getTime() - startTime), e);
}
conn.rollback(sp);
s_logger.trace("Lock: Unable to acquire DB lock " + key);
} catch (SQLException e) {
s_logger.warn("Lock: Unable to acquire db connection for locking " + key, e);
} finally {
if (pstmt != null) {
try {
pstmt.close();
} catch (SQLException e) {
}
}
}
return false;
}
public boolean isLocked(String key) {
Connection conn = getConnection(key, false);
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
pstmt = conn.prepareStatement(INQUIRE_SQL);
pstmt.setString(1, key);
rs = pstmt.executeQuery();
return rs.next();
} catch (SQLException e) {
s_logger.warn("SQL exception " + e.getMessage(), e);
throw new CloudRuntimeException("SQL Exception on inquiry", e);
} finally {
try {
if (rs != null) {
rs.close();
}
if (pstmt != null) {
pstmt.close();
}
} catch (SQLException e) {
s_logger.warn("Unexpected SQL exception " + e.getMessage(), e);
}
}
}
public void clear() {
if (_locks.size() == 0) {
return;
}
Set<String> keys = new HashSet<String>(_locks.keySet());
//
// disable assertion, when assert support is enabled, it throws an exception
// which eventually eats the following on important messages for diagnostic
//
// assert (false) : "Who acquired locks but didn't release them? " + keys.toArray(new String[keys.size()]);
for (String key : keys) {
s_logger.warn("Lock: This is not good guys! Automatically releasing lock: " + key);
release(key);
}
_locks.clear();
}
public boolean release(String key) {
boolean validLock = false;
try {
assert _locks.size() > 0 : "There are no locks here. Why are you trying to release " + key;
Ternary<Savepoint, Integer, Long> lock = _locks.get(key);
if (lock != null) {
validLock = true;
if (lock.second() > 1) {
lock.second(lock.second() - 1);
if (s_logger.isTraceEnabled()) {
s_logger.trace("Lock: Releasing " + key + " but not in DB " + lock.second());
}
return false;
}
if (s_logger.isDebugEnabled() && !_locks.keySet().iterator().next().equals(key)) {
s_logger.trace("Lock: Releasing out of order for " + key);
}
_locks.remove(key);
if (s_logger.isTraceEnabled()) {
s_logger.trace("Lock: Releasing " + key + " after " + (InaccurateClock.getTime() - lock.third()));
}
Connection conn = getConnection(key, true);
conn.rollback(lock.first());
} else {
s_logger.warn("Merovingian.release() is called against key " + key + " but the lock of this key does not exist!");
}
if (_locks.size() == 0) {
closeConnection();
}
} catch (SQLException e) {
s_logger.warn("unable to rollback for " + key);
} finally {
synchronized(s_memLocks) {
Pair<Lock, Integer> memLock = s_memLocks.get(key);
if(memLock != null) {
memLock.second(memLock.second() - 1);
if (memLock.second() <= 0) {
s_memLocks.remove(key);
}
if(validLock)
memLock.first().unlock();
} else {
throw new CloudRuntimeException("Merovingian.release() is called for key " + key + ", but its memory lock no longer exist! This is not good, guys");
}
}
}
return true;
}
public void closeConnection() {
try {
if (_conn == null) {
_previousIsolation = Connection.TRANSACTION_NONE;
return;
}
if (_previousIsolation != Connection.TRANSACTION_NONE) {
_conn.setTransactionIsolation(_previousIsolation);
}
try { // rollback just in case but really there shoul be nothing.
_conn.rollback();
} catch (SQLException e) {
}
_conn.setAutoCommit(true);
_previousIsolation = Connection.TRANSACTION_NONE;
_conn.close();
_conn = null;
} catch (SQLException e) {
s_logger.warn("Unexpected SQL exception " + e.getMessage(), e);
}
}
}