/
ClusterService.java
489 lines (446 loc) · 20.2 KB
/
ClusterService.java
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
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
/**
* Licensed to JumpMind Inc under one or more contributor
* license agreements. See the NOTICE file distributed
* with this work for additional information regarding
* copyright ownership. JumpMind Inc licenses this file
* to you under the GNU General Public License, version 3.0 (GPLv3)
* (the "License"); you may not use this file except in compliance
* with the License.
*
* You should have received a copy of the GNU General Public License,
* version 3.0 (GPLv3) along with this library; if not, see
* <http://www.gnu.org/licenses/>.
*
* 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 org.jumpmind.symmetric.service.impl;
import static org.jumpmind.symmetric.service.ClusterConstants.FILE_SYNC_PULL;
import static org.jumpmind.symmetric.service.ClusterConstants.FILE_SYNC_PUSH;
import static org.jumpmind.symmetric.service.ClusterConstants.FILE_SYNC_SCAN;
import static org.jumpmind.symmetric.service.ClusterConstants.FILE_SYNC_SHARED;
import static org.jumpmind.symmetric.service.ClusterConstants.FILE_SYNC_TRACKER;
import static org.jumpmind.symmetric.service.ClusterConstants.HEARTBEAT;
import static org.jumpmind.symmetric.service.ClusterConstants.INITIAL_LOAD_EXTRACT;
import static org.jumpmind.symmetric.service.ClusterConstants.MONITOR;
import static org.jumpmind.symmetric.service.ClusterConstants.OFFLINE_PULL;
import static org.jumpmind.symmetric.service.ClusterConstants.OFFLINE_PUSH;
import static org.jumpmind.symmetric.service.ClusterConstants.PULL;
import static org.jumpmind.symmetric.service.ClusterConstants.PURGE_DATA_GAPS;
import static org.jumpmind.symmetric.service.ClusterConstants.PURGE_INCOMING;
import static org.jumpmind.symmetric.service.ClusterConstants.PURGE_OUTGOING;
import static org.jumpmind.symmetric.service.ClusterConstants.PURGE_STATISTICS;
import static org.jumpmind.symmetric.service.ClusterConstants.PUSH;
import static org.jumpmind.symmetric.service.ClusterConstants.ROUTE;
import static org.jumpmind.symmetric.service.ClusterConstants.STAGE_MANAGEMENT;
import static org.jumpmind.symmetric.service.ClusterConstants.STATISTICS;
import static org.jumpmind.symmetric.service.ClusterConstants.SYNCTRIGGERS;
import static org.jumpmind.symmetric.service.ClusterConstants.TYPE_CLUSTER;
import static org.jumpmind.symmetric.service.ClusterConstants.TYPE_EXCLUSIVE;
import static org.jumpmind.symmetric.service.ClusterConstants.TYPE_SHARED;
import static org.jumpmind.symmetric.service.ClusterConstants.WATCHDOG;
import static org.jumpmind.symmetric.service.ClusterConstants.SYNC_CONFIG;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateUtils;
import org.jumpmind.db.sql.ConcurrencySqlException;
import org.jumpmind.db.sql.ISqlRowMapper;
import org.jumpmind.db.sql.Row;
import org.jumpmind.db.sql.UniqueKeyException;
import org.jumpmind.symmetric.common.ParameterConstants;
import org.jumpmind.symmetric.common.SystemConstants;
import org.jumpmind.symmetric.db.ISymmetricDialect;
import org.jumpmind.symmetric.model.Lock;
import org.jumpmind.symmetric.service.IClusterService;
import org.jumpmind.symmetric.service.IParameterService;
import org.jumpmind.util.AppUtils;
/**
* @see IClusterService
*/
public class ClusterService extends AbstractService implements IClusterService {
private static final String[] actions = new String[] { ROUTE, PULL, PUSH, HEARTBEAT, PURGE_INCOMING, PURGE_OUTGOING,
PURGE_STATISTICS, SYNCTRIGGERS, PURGE_DATA_GAPS, STAGE_MANAGEMENT, WATCHDOG, STATISTICS, FILE_SYNC_PULL,
FILE_SYNC_PUSH, FILE_SYNC_TRACKER, FILE_SYNC_SCAN, INITIAL_LOAD_EXTRACT, OFFLINE_PUSH, OFFLINE_PULL, MONITOR,
SYNC_CONFIG };
private static final String[] sharedActions = new String[] { FILE_SYNC_SHARED };
private String serverId = null;
private Map<String, Lock> lockCache;
public ClusterService(IParameterService parameterService, ISymmetricDialect dialect) {
super(parameterService, dialect);
setSqlMap(new ClusterServiceSqlMap(symmetricDialect.getPlatform(),
createSqlReplacementTokens()));
initCache();
}
public void init() {
if (isClusteringEnabled()) {
sqlTemplate.update(getSql("initLockSql"), new Object[] { getServerId() });
Map<String, Lock> allLocks = findLocks();
for (String action : actions) {
if (allLocks.get(action) == null) {
initLockTable(action, TYPE_CLUSTER);
}
}
for (String action : sharedActions) {
if (allLocks.get(action) == null) {
initLockTable(action, TYPE_SHARED);
}
}
}
}
@Override
public synchronized void persistToTableForSnapshot() {
sqlTemplate.update(getSql("deleteSql"));
Collection<Lock> values = lockCache.values();
for (Lock lock : values) {
insertLock(lock);
}
}
protected void insertLock(Lock lock) {
sqlTemplate.update(getSql("insertCompleteLockSql"), lock.getLockAction(), lock.getLockType(), lock.getLockingServerId(), lock.getLockTime(), lock.getSharedCount(), lock.isSharedEnable() ? 1 : 0, lock.getLastLockTime(), lock.getLastLockingServerId());
}
protected void initLockTable(final String action) {
initLockTable(action, TYPE_CLUSTER);
}
protected void initLockTable(final String action, final String lockType) {
try {
sqlTemplate.update(getSql("insertLockSql"), new Object[] { action, lockType });
log.debug("Inserted into the LOCK table for {}, {}", action, lockType);
} catch (UniqueKeyException ex) {
log.debug("Failed to insert to the LOCK table for {}, {}. Must be initialized already.",
action, lockType);
}
}
protected void initCache() {
lockCache = new HashMap<String, Lock>();
for (String action : actions) {
Lock lock = new Lock();
lock.setLockAction(action);
lock.setLockType(TYPE_CLUSTER);
lockCache.put(action, lock);
}
for (String action : sharedActions) {
Lock lock = new Lock();
lock.setLockAction(action);
lock.setLockType(TYPE_SHARED);
lockCache.put(action, lock);
}
}
public void clearAllLocks() {
if (isClusteringEnabled()) {
sqlTemplate.update(getSql("initLockSql"), new Object[] { getServerId() });
} else {
initCache();
}
}
public boolean lock(final String action, final String lockType) {
if (lockType.equals(TYPE_CLUSTER)) {
return lock(action);
} else if (lockType.equals(TYPE_SHARED)) {
return lockShared(action);
} else if (lockType.equals(TYPE_EXCLUSIVE)) {
return lockExclusive(action);
} else {
throw new UnsupportedOperationException("Lock type of " + lockType + " is not supported");
}
}
public boolean lock(final String action, final String lockType, long waitMillis) {
if (lockType.equals(TYPE_SHARED) || lockType.equals(TYPE_EXCLUSIVE)) {
return lockWait(action, lockType, waitMillis);
} else {
throw new UnsupportedOperationException("Lock type of " + lockType + " is not supported");
}
}
public boolean lock(final String action) {
final Date timeout = DateUtils.addMilliseconds(new Date(),
(int) -parameterService.getLong(ParameterConstants.CLUSTER_LOCK_TIMEOUT_MS));
return lockCluster(action, timeout, new Date(), getServerId());
}
protected boolean lockCluster(String action, Date timeToBreakLock, Date timeLockAcquired,
String serverId) {
if (isClusteringEnabled()) {
try {
return sqlTemplate.update(getSql("acquireClusterLockSql"), new Object[] { serverId,
timeLockAcquired, action, TYPE_CLUSTER, timeToBreakLock, serverId }) == 1;
} catch (ConcurrencySqlException ex) {
log.debug("Ignoring concurrency error and reporting that we failed to get the cluster lock: {}", ex.getMessage());
}
} else {
Lock lock = lockCache.get(action);
if (lock != null) {
synchronized (lock) {
if (lock.getLockType().equals(TYPE_CLUSTER) && (lock.getLockTime() == null
|| lock.getLockTime().before(timeToBreakLock) || serverId.equals(lock.getLockingServerId()))) {
lock.setLockingServerId(serverId);
lock.setLockTime(timeLockAcquired);
return true;
}
}
}
}
return false;
}
protected boolean lockShared(final String action) {
final Date timeout = DateUtils.addMilliseconds(new Date(),
(int) -parameterService.getLong(ParameterConstants.LOCK_TIMEOUT_MS));
if (isClusteringEnabled()) {
return sqlTemplate.update(getSql("acquireSharedLockSql"), new Object[] {
TYPE_SHARED, getServerId(), new Date(), action, TYPE_SHARED, timeout }) == 1;
} else {
Lock lock = lockCache.get(action);
if (lock != null) {
synchronized (lock) {
if ((lock.getLockType().equals(TYPE_SHARED) || lock.getLockTime() == null || lock.getLockTime().before(timeout))
&& (lock.isSharedEnable() || lock.getSharedCount() == 0)) {
lock.setLockType(TYPE_SHARED);
lock.setLockingServerId(getServerId());
lock.setLockTime(new Date());
if (lock.getSharedCount() == 0) {
lock.setSharedEnable(true);
}
lock.setSharedCount(lock.getSharedCount() + 1);
return true;
}
}
}
}
return false;
}
protected boolean lockExclusive(final String action) {
final Date timeout = DateUtils.addMilliseconds(new Date(),
(int) -parameterService.getLong(ParameterConstants.LOCK_TIMEOUT_MS));
if (isClusteringEnabled()) {
return sqlTemplate.update(getSql("acquireExclusiveLockSql"), new Object[] {
TYPE_EXCLUSIVE, getServerId(), new Date(), action, TYPE_SHARED, timeout }) == 1;
} else {
Lock lock = lockCache.get(action);
if (lock != null) {
synchronized (lock) {
if ((lock.getLockType().equals(TYPE_SHARED) && lock.getSharedCount() == 0) ||
lock.getLockTime() == null || lock.getLockTime().before(timeout)) {
lock.setLockType(TYPE_EXCLUSIVE);
lock.setLockingServerId(getServerId());
lock.setLockTime(new Date());
lock.setSharedCount(0);
return true;
}
}
}
}
return false;
}
protected boolean lockWait(final String action, final String lockType, long waitMillis) {
boolean isLocked = false;
long endTime = System.currentTimeMillis() + waitMillis;
long sleepMillis = parameterService.getLong(ParameterConstants.LOCK_WAIT_RETRY_MILLIS);
do {
if (lockType.equals(TYPE_SHARED)) {
isLocked = lockShared(action);
} else if (lockType.equals(TYPE_EXCLUSIVE)) {
isLocked = lockExclusive(action);
if (!isLocked) {
if (isClusteringEnabled()) {
sqlTemplate.update(getSql("disableSharedLockSql"), new Object[] { action, TYPE_SHARED });
} else {
Lock lock = lockCache.get(action);
if (lock != null) {
synchronized (lock) {
lock.setSharedEnable(false);
}
}
}
}
}
if (isLocked) {
break;
}
AppUtils.sleep(sleepMillis);
} while (waitMillis == 0 || System.currentTimeMillis() < endTime);
return isLocked;
}
public Map<String, Lock> findLocks() {
if (isClusteringEnabled()) {
final Map<String, Lock> locks = new HashMap<String, Lock>();
sqlTemplate.query(getSql("findLocksSql"), new ISqlRowMapper<Lock>() {
public Lock mapRow(Row rs) {
Lock lock = new Lock();
lock.setLockAction(rs.getString("lock_action"));
lock.setLockType(rs.getString("lock_type"));
lock.setLockingServerId(rs.getString("locking_server_id"));
lock.setLockTime(rs.getDateTime("lock_time"));
lock.setSharedCount(rs.getInt("shared_count"));
lock.setSharedEnable(rs.getBoolean("shared_enable"));
lock.setLastLockingServerId(rs.getString("last_locking_server_id"));
lock.setLastLockTime(rs.getDateTime("last_lock_time"));
locks.put(lock.getLockAction(), lock);
return lock;
}
});
return locks;
} else {
return lockCache;
}
}
/**
* Get a unique identifier that represents the JVM instance this server is
* currently running in.
*/
public String getServerId() {
if (StringUtils.isBlank(serverId)) {
serverId = parameterService.getString(ParameterConstants.CLUSTER_SERVER_ID);
if (StringUtils.isBlank(serverId)) {
serverId = System.getProperty(SystemConstants.SYSPROP_CLUSTER_SERVER_ID, null);
}
if (StringUtils.isBlank(serverId)) {
// JBoss uses this system property to identify a server in a
// cluster
serverId = System.getProperty("bind.address", null);
}
if (StringUtils.isBlank(serverId)) {
// JBoss uses this system property to identify a server in a
// cluster
serverId = System.getProperty("jboss.bind.address", null);
}
if (StringUtils.isBlank(serverId)) {
try {
serverId = AppUtils.getHostName();
} catch (Exception ex) {
serverId = "unknown";
}
}
log.info("This node picked a server id of {}", serverId);
}
return serverId;
}
public void unlock(final String action, final String lockType) {
if (lockType.equals(TYPE_CLUSTER)) {
unlock(action);
} else if (lockType.equals(TYPE_SHARED)) {
unlockShared(action);
} else if (lockType.equals(TYPE_EXCLUSIVE)) {
unlockExclusive(action);
} else {
throw new UnsupportedOperationException("Lock type of " + lockType + " is not supported");
}
}
public void unlock(final String action) {
if (!unlockCluster(action, getServerId())) {
log.warn("Failed to release lock for action:{} server:{}", action, getServerId());
}
}
protected boolean unlockCluster(String action, String serverId) {
if (isClusteringEnabled()) {
return sqlTemplate.update(getSql("releaseClusterLockSql"), new Object[] { action,
TYPE_CLUSTER, serverId }) > 0;
} else {
Lock lock = lockCache.get(action);
if (lock != null) {
synchronized (lock) {
if (lock.getLockType().equals(TYPE_CLUSTER) && serverId.equals(lock.getLockingServerId())) {
lock.setLastLockingServerId(lock.getLockingServerId());
lock.setLockingServerId(null);
lock.setLastLockTime(lock.getLockTime());
lock.setLockTime(null);
return true;
}
}
}
}
return false;
}
protected boolean unlockShared(final String action) {
if (isClusteringEnabled()) {
return sqlTemplate.update(getSql("releaseSharedLockSql"), new Object[] {
action, TYPE_SHARED }) == 1;
} else {
Lock lock = lockCache.get(action);
if (lock != null) {
synchronized (lock) {
if (lock.getLockType().equals(TYPE_SHARED)) {
lock.setLastLockTime(lock.getLockTime());
lock.setLastLockingServerId(lock.getLockingServerId());
if (lock.getSharedCount() == 1) {
lock.setSharedEnable(false);
lock.setLockingServerId(null);
lock.setLockTime(null);
}
if (lock.getSharedCount() > 1) {
lock.setSharedCount(lock.getSharedCount() - 1);
} else {
lock.setSharedCount(0);
}
return true;
}
}
}
}
return false;
}
protected boolean unlockExclusive(final String action) {
if (isClusteringEnabled()) {
return sqlTemplate.update(getSql("releaseExclusiveLockSql"), new Object[] {
action, TYPE_EXCLUSIVE }) == 1;
} else {
Lock lock = lockCache.get(action);
if (lock != null) {
synchronized (lock) {
if (lock.getLockType().equals(TYPE_EXCLUSIVE)) {
lock.setLastLockingServerId(lock.getLockingServerId());
lock.setLockingServerId(null);
lock.setLastLockTime(lock.getLockTime());
lock.setLockTime(null);
return true;
}
}
}
}
return false;
}
public boolean isClusteringEnabled() {
return parameterService.is(ParameterConstants.CLUSTER_LOCKING_ENABLED);
}
public boolean isInfiniteLocked(String action) {
Map<String, Lock> locks = findLocks();
Lock lock = locks.get(action);
if (lock != null && lock.getLockTime() != null && new Date().before(lock.getLockTime())
&& Lock.STOPPED.equals(lock.getLockingServerId())) {
return true;
} else {
return false;
}
}
public void aquireInfiniteLock(String action) {
if (isClusteringEnabled()) {
int tries = 600;
Date futureTime = DateUtils.addYears(new Date(), 100);
while (tries > 0) {
if (!lockCluster(action, new Date(), futureTime, Lock.STOPPED)) {
AppUtils.sleep(50);
tries--;
} else {
tries = 0;
}
}
}
}
public void clearInfiniteLock(String action) {
Map<String, Lock> all = findLocks();
Lock lock = all.get(action);
if (lock != null && Lock.STOPPED.equals(lock.getLockingServerId())) {
if (isClusteringEnabled()) {
sqlTemplate.update(getSql("resetClusterLockSql"), new Object[] { action, TYPE_CLUSTER, Lock.STOPPED});
} else if (lock.getLockType().equals(TYPE_CLUSTER) && Lock.STOPPED.equals(lock.getLockingServerId())) {
lock.setLastLockingServerId(null);
lock.setLockingServerId(null);
lock.setLastLockTime(null);
lock.setLockTime(null);
}
}
}
}