mirror of https://github.com/OpenIdentityPlatform/OpenDJ.git

ludovicp
28.04.2010 e74242ccd53b5525ab7337c9e289a1af196b7b18
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
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License, Version 1.0 only
 * (the "License").  You may not use this file except in compliance
 * with the License.
 *
 * You can obtain a copy of the license at
 * trunk/opends/resource/legal-notices/OpenDS.LICENSE
 * or https://OpenDS.dev.java.net/OpenDS.LICENSE.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at
 * trunk/opends/resource/legal-notices/OpenDS.LICENSE.  If applicable,
 * add the following below this CDDL HEADER, with the fields enclosed
 * by brackets "[]" replaced with your own identifying information:
 *      Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 *
 *
 *      Copyright 2006-2008 Sun Microsystems, Inc.
 */
package org.opends.server.core;
 
 
 
import java.io.File;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.util.HashMap;
 
import org.opends.server.api.Backend;
import org.opends.server.loggers.debug.DebugTracer;
import org.opends.server.types.DebugLogLevel;
 
import static org.opends.messages.CoreMessages.*;
import static org.opends.server.loggers.debug.DebugLogger.*;
import static org.opends.server.util.ServerConstants.*;
import static org.opends.server.util.StaticUtils.*;
 
 
 
/**
 * This class provides a mechanism for allowing the Directory Server to utilize
 * file locks as provided by the underlying OS.  File locks may be exclusive or
 * shared, and will be visible between different processes on the same system.
 */
public class LockFileManager
{
  /**
   * The tracer object for the debug logger.
   */
  private static final DebugTracer TRACER = getTracer();
 
 
 
 
  // A map between the filenames and the lock files for exclusive locks.
  private static HashMap<String,FileLock> exclusiveLocks =
       new HashMap<String,FileLock>();
 
  // A map between the filenames and the lock files for shared locks.
  private static HashMap<String,FileLock> sharedLocks =
       new HashMap<String,FileLock>();
 
  // A map between the filenames and reference counts for shared locks.
  private static HashMap<String,Integer> sharedLockReferences =
       new HashMap<String,Integer>();
 
  // The lock providing threadsafe access to the lock map data.
  private static Object mapLock = new Object();
 
 
 
  /**
   * Attempts to acquire a shared lock on the specified file.
   *
   * @param  lockFile       The file for which to obtain the shared lock.
   * @param  failureReason  A buffer that can be used to hold a reason that the
   *                        lock could not be acquired.
   *
   * @return  <CODE>true</CODE> if the lock was obtained successfully, or
   *          <CODE>false</CODE> if it could not be obtained.
   */
  public static boolean acquireSharedLock(String lockFile,
                                          StringBuilder failureReason)
  {
    synchronized (mapLock)
    {
      // Check to see if there's already an exclusive lock on the file.  If so,
      // then we can't get a shared lock on it.
      if (exclusiveLocks.containsKey(lockFile))
      {
 
        failureReason.append(
                ERR_FILELOCKER_LOCK_SHARED_REJECTED_BY_EXCLUSIVE.get(lockFile));
        return false;
      }
 
 
      // Check to see if we already hold a shared lock on the file.  If so, then
      // increase its refcount and return true.
      FileLock sharedLock = sharedLocks.get(lockFile);
      if (sharedLock != null)
      {
        int numReferences = sharedLockReferences.get(lockFile);
        numReferences++;
        sharedLockReferences.put(lockFile, numReferences);
        return true;
      }
 
 
      // We don't hold a lock on the file so we need to create it.  First,
      // create the file only if it doesn't already exist.
      File f = getFileForPath(lockFile);
      try
      {
        if (! f.exists())
        {
          f.createNewFile();
        }
      }
      catch (Exception e)
      {
        if (debugEnabled())
        {
          TRACER.debugCaught(DebugLogLevel.ERROR, e);
        }
 
        failureReason.append(
                ERR_FILELOCKER_LOCK_SHARED_FAILED_CREATE.get(lockFile,
                                        getExceptionMessage(e)));
        return false;
      }
 
 
      // Open the file for reading and get the corresponding file channel.
      FileChannel channel = null;
      RandomAccessFile raf = null;
      try
      {
        raf = new RandomAccessFile(lockFile, "r");
        channel = raf.getChannel();
      }
      catch (Exception e)
      {
        if (debugEnabled())
        {
          TRACER.debugCaught(DebugLogLevel.ERROR, e);
        }
 
        failureReason.append(ERR_FILELOCKER_LOCK_SHARED_FAILED_OPEN.get(
                lockFile, getExceptionMessage(e)));
 
        if (raf != null)
        {
          try
          {
            raf.close();
          }
          catch (Throwable t)
          {
          }
        }
        return false;
      }
 
 
      // Try to obtain a shared lock on the file channel.
      FileLock fileLock;
      try
      {
        fileLock = channel.tryLock(0L, Long.MAX_VALUE, true);
      }
      catch (Exception e)
      {
        if (debugEnabled())
        {
          TRACER.debugCaught(DebugLogLevel.ERROR, e);
        }
 
        failureReason.append(
                ERR_FILELOCKER_LOCK_SHARED_FAILED_LOCK.get(
                        lockFile, getExceptionMessage(e)));
        if (channel != null)
        {
          try
          {
            channel.close();
          }
          catch (Throwable t)
          {
          }
        }
        if (raf != null)
        {
          try
          {
            raf.close();
          }
          catch (Throwable t)
          {
          }
        }
        return false;
      }
 
 
      // If we could not get the lock, then return false.  Otherwise, put it in
      // the shared lock table with a reference count of 1 and return true.
      if (fileLock == null)
      {
        failureReason.append(
                ERR_FILELOCKER_LOCK_SHARED_NOT_GRANTED.get(lockFile));
        if (channel != null)
        {
          try
          {
            channel.close();
          }
          catch (Throwable t)
          {
          }
        }
        if (raf != null)
        {
          try
          {
            raf.close();
          }
          catch (Throwable t)
          {
          }
        }
        return false;
      }
      else
      {
        sharedLocks.put(lockFile, fileLock);
        sharedLockReferences.put(lockFile, 1);
        return true;
      }
    }
  }
 
 
 
  /**
   * Attempts to acquire an exclusive lock on the specified file.
   *
   * @param  lockFile       The file for which to obtain the exclusive lock.
   * @param  failureReason  A buffer that can be used to hold a reason that the
   *                        lock could not be acquired.
   *
   * @return  <CODE>true</CODE> if the lock was obtained successfully, or
   *          <CODE>false</CODE> if it could not be obtained.
   */
  public static boolean acquireExclusiveLock(String lockFile,
                                             StringBuilder failureReason)
  {
    synchronized (mapLock)
    {
      // Check to see if there's already an exclusive lock on the file.  If so,
      // then we can't get another exclusive lock on it.
      if (exclusiveLocks.containsKey(lockFile))
      {
        failureReason.append(
                ERR_FILELOCKER_LOCK_EXCLUSIVE_REJECTED_BY_EXCLUSIVE.get(
                        lockFile));
        return false;
      }
 
 
      // Check to see if we already hold a shared lock on the file.  If so, then
      // we can't get an exclusive lock on it.
      if (sharedLocks.containsKey(lockFile))
      {
        failureReason.append(
                ERR_FILELOCKER_LOCK_EXCLUSIVE_REJECTED_BY_SHARED.get(lockFile));
        return false;
      }
 
 
      // We don't hold a lock on the file so we need to create it.  First,
      // create the file only if it doesn't already exist.
      File f = getFileForPath(lockFile);
      try
      {
        if (! f.exists())
        {
          f.createNewFile();
        }
      }
      catch (Exception e)
      {
        if (debugEnabled())
        {
          TRACER.debugCaught(DebugLogLevel.ERROR, e);
        }
        failureReason.append(
                ERR_FILELOCKER_LOCK_EXCLUSIVE_FAILED_CREATE.get(lockFile,
                                        getExceptionMessage(e)));
        return false;
      }
 
 
      // Open the file read+write and get the corresponding file channel.
      FileChannel channel = null;
      RandomAccessFile raf = null;
      try
      {
        raf = new RandomAccessFile(lockFile, "rw");
        channel = raf.getChannel();
      }
      catch (Exception e)
      {
        if (debugEnabled())
        {
          TRACER.debugCaught(DebugLogLevel.ERROR, e);
        }
 
        failureReason.append(ERR_FILELOCKER_LOCK_EXCLUSIVE_FAILED_OPEN.get(
                lockFile, getExceptionMessage(e)));
        if (raf != null)
        {
          try
          {
            raf.close();
          }
          catch (Throwable t)
          {
          }
        }
        return false;
      }
 
 
      // Try to obtain an exclusive lock on the file channel.
      FileLock fileLock;
      try
      {
        fileLock = channel.tryLock(0L, Long.MAX_VALUE, false);
      }
      catch (Exception e)
      {
        if (debugEnabled())
        {
          TRACER.debugCaught(DebugLogLevel.ERROR, e);
        }
 
        failureReason.append(
                ERR_FILELOCKER_LOCK_EXCLUSIVE_FAILED_LOCK.get(lockFile,
                                        getExceptionMessage(e)));
        if (channel != null)
        {
          try
          {
            channel.close();
          }
          catch (Throwable t)
          {
          }
        }
        if (raf != null)
        {
          try
          {
            raf.close();
          }
          catch (Throwable t)
          {
          }
        }
 
        return false;
      }
 
 
      // If we could not get the lock, then return false.  Otherwise, put it in
      // the exclusive lock table and return true.
      if (fileLock == null)
      {
        failureReason.append(
                ERR_FILELOCKER_LOCK_EXCLUSIVE_NOT_GRANTED.get(lockFile));
        if (channel != null)
        {
          try
          {
            channel.close();
          }
          catch (Throwable t)
          {
          }
        }
        if (raf != null)
        {
          try
          {
            raf.close();
          }
          catch (Throwable t)
          {
          }
        }
        return false;
      }
      else
      {
        exclusiveLocks.put(lockFile, fileLock);
        return true;
      }
    }
  }
 
 
 
  /**
   * Attempts to release the lock on the specified file.  If an exclusive lock
   * is held, then it will be released.  If a shared lock is held, then its
   * reference count will be reduced, and the lock will be released if the
   * resulting reference count is zero.  If we don't know anything about the
   * requested file, then don't do anything.
   *
   * @param  lockFile       The file for which to release the associated lock.
   * @param  failureReason  A buffer that can be used to hold information about
   *                        a problem that occurred preventing the successful
   *                        release.
   *
   * @return  <CODE>true</CODE> if the lock was found and released successfully,
   *          or <CODE>false</CODE> if a problem occurred that might have
   *          prevented the lock from being released.
   */
  public static boolean releaseLock(String lockFile,
                                    StringBuilder failureReason)
  {
    synchronized (mapLock)
    {
      // See if we hold an exclusive lock on the file.  If so, then release it
      // and get remove it from the lock table.
      FileLock lock = exclusiveLocks.remove(lockFile);
      if (lock != null)
      {
        try
        {
          lock.release();
        }
        catch (Exception e)
        {
          if (debugEnabled())
          {
            TRACER.debugCaught(DebugLogLevel.ERROR, e);
          }
 
          failureReason.append(
                  ERR_FILELOCKER_UNLOCK_EXCLUSIVE_FAILED_RELEASE.get(lockFile,
                                          getExceptionMessage(e)));
          return false;
        }
 
        try
        {
          lock.channel().close();
        }
        catch (Exception e)
        {
          if (debugEnabled())
          {
            TRACER.debugCaught(DebugLogLevel.ERROR, e);
          }
 
          // Even though we couldn't close the channel for some reason, this
          // should still be OK because we released the lock above.
        }
 
        return true;
      }
 
 
      // See if we hold a shared lock on the file.  If so, then reduce its
      // refcount and release only if the resulting count is zero.
      lock = sharedLocks.get(lockFile);
      if (lock != null)
      {
        int refCount = sharedLockReferences.get(lockFile);
        refCount--;
        if (refCount <= 0)
        {
          sharedLocks.remove(lockFile);
          sharedLockReferences.remove(lockFile);
 
          try
          {
            lock.release();
          }
          catch (Exception e)
          {
            if (debugEnabled())
            {
              TRACER.debugCaught(DebugLogLevel.ERROR, e);
            }
 
            failureReason.append(ERR_FILELOCKER_UNLOCK_SHARED_FAILED_RELEASE
                    .get(lockFile, getExceptionMessage(e)));
            return false;
          }
 
          try
          {
            lock.channel().close();
          }
          catch (Exception e)
          {
            if (debugEnabled())
            {
              TRACER.debugCaught(DebugLogLevel.ERROR, e);
            }
 
            // Even though we couldn't close the channel for some reason, this
            // should still be OK because we released the lock above.
          }
        }
        else
        {
          sharedLockReferences.put(lockFile, refCount);
        }
 
        return true;
      }
 
 
      // We didn't find a reference to the file.  We'll have to return false
      // since either we lost the reference or we're trying to release a lock
      // we never had.  Both of them are bad.
      failureReason.append(ERR_FILELOCKER_UNLOCK_UNKNOWN_FILE.get(lockFile));
      return false;
    }
  }
 
 
 
  /**
   * Retrieves the path to the directory that should be used to hold the lock
   * files.
   *
   * @return  The path to the directory that should be used to hold the lock
   *          files.
   */
  public static String getLockDirectoryPath()
  {
    File lockDirectory =
              DirectoryServer.getEnvironmentConfig().getLockDirectory();
    return lockDirectory.getAbsolutePath();
  }
 
 
 
  /**
   * Retrieves the filename that should be used for the lock file for the
   * Directory Server instance.
   *
   * @return  The filename that should be used for the lock file for the
   *          Directory Server instance.
   */
  public static String getServerLockFileName()
  {
    StringBuilder buffer = new StringBuilder();
    buffer.append(getLockDirectoryPath());
    buffer.append(File.separator);
    buffer.append(SERVER_LOCK_FILE_NAME);
    buffer.append(LOCK_FILE_SUFFIX);
 
    return buffer.toString();
  }
 
 
 
  /**
   * Retrieves the filename that should be used for the lock file for the
   * specified backend.
   *
   * @param  backend  The backend for which to retrieve the filename for the
   *                  lock file.
   *
   * @return  The filename that should be used for the lock file for the
   *          specified backend.
   */
  public static String getBackendLockFileName(Backend backend)
  {
    StringBuilder buffer = new StringBuilder();
    buffer.append(getLockDirectoryPath());
    buffer.append(File.separator);
    buffer.append(BACKEND_LOCK_FILE_PREFIX);
    buffer.append(backend.getBackendID());
    buffer.append(LOCK_FILE_SUFFIX);
 
    return buffer.toString();
  }
}