Esempio n. 1
0
 private void lock() throws IOException {
   if (lockFile == null) {
     File lockFileName = new File(directory, "lock");
     lockFile = new LockFile(lockFileName, true);
     if (failIfDatabaseIsLocked) {
       lockFile.lock();
     } else {
       while (true) {
         try {
           lockFile.lock();
           break;
         } catch (IOException e) {
           LOG.info(
               "Database "
                   + lockFileName
                   + " is locked... waiting "
                   + (DATABASE_LOCKED_WAIT_DELAY / 1000)
                   + " seconds for the database to be unlocked. Reason: "
                   + e);
           try {
             Thread.sleep(DATABASE_LOCKED_WAIT_DELAY);
           } catch (InterruptedException e1) {
           }
         }
       }
     }
   }
 }
  /** Attempts to aquire a cooperative lock condition on the database files */
  void acquireLock(String path) throws HsqlException {

    boolean locked;
    String msg;

    if (lf != null) {
      return;
    }

    try {
      lf = LockFile.newLockFile(path + ".lck");
    } catch (Exception e) {
      throw Trace.error(Trace.FILE_IO_ERROR, e.toString());
    }

    locked = false;
    msg = "";

    try {
      locked = lf.tryLock();
    } catch (Exception e) {

      // e.printStackTrace();
      msg = e.toString();
    }

    if (!locked) {
      throw Trace.error(Trace.DATABASE_ALREADY_IN_USE, lf + ": " + msg);
    }
  }
Esempio n. 3
0
 /**
  * Create the <code>pack-*.keep</code> file, with the given message.
  *
  * @param msg message to store in the file.
  * @return true if the keep file was successfully written; false otherwise.
  * @throws IOException the keep file could not be written.
  */
 public boolean lock(String msg) throws IOException {
   if (msg == null) return false;
   if (!msg.endsWith("\n")) msg += "\n";
   final LockFile lf = new LockFile(keepFile);
   if (!lf.lock()) return false;
   lf.write(Constants.encode(msg));
   return lf.commit();
 }
Esempio n. 4
0
  @Test
  public void whileRefLockedRefNotPackedNoError() throws Exception {
    RevBlob a = tr.blob("a");
    tr.lightweightTag("t1", a);
    tr.lightweightTag("t2", a);
    LockFile refLock = new LockFile(new File(repo.getDirectory(), "refs/tags/t1"));
    try {
      refLock.lock();
      gc.packRefs();
    } finally {
      refLock.unlock();
    }

    assertSame(repo.exactRef("refs/tags/t1").getStorage(), Storage.LOOSE);
    assertSame(repo.exactRef("refs/tags/t2").getStorage(), Storage.PACKED);
  }
  /** Attempts to aquire a cooperative lock condition on the database files */
  public void acquireLock(String path) throws HsqlException {

    if (lockFile != null) {
      return;
    }

    lockFile = LockFile.newLockFileLock(path);
  }
  @Test
  public void testDeleteOnUnlockIfLocked() throws Exception {

    File lockFile = new File(IOHelper.getDefaultDataDirectory(), "lockToTest2");
    IOHelper.mkdirs(lockFile.getParentFile());
    lockFile.createNewFile();

    LockFile underTest = new LockFile(lockFile, true);

    underTest.lock();

    assertTrue("valid", underTest.keepAlive());

    underTest.unlock();

    assertFalse("file deleted on unlock", lockFile.exists());
  }
  private void checkFilesLocked(FileObject[] files) throws KettleException {

    for (int i = 0; i < files.length && !oneFileLocked; i++) {
      FileObject file = files[i];
      String filename = KettleVFS.getFilename(file);
      LockFile locked = new LockFile(filename);
      if (locked.isLocked()) {
        oneFileLocked = true;
        logError(BaseMessages.getString(PKG, "JobCheckFilesLocked.Log.FileLocked", filename));
      } else {
        if (isDetailed()) {
          logDetailed(
              BaseMessages.getString(PKG, "JobCheckFilesLocked.Log.FileNotLocked", filename));
        }
      }
    }
  }
  public void releaseLock() {

    try {
      if (lockFile != null) {
        lockFile.tryRelease();
      }
    } catch (Exception e) {
    }

    lockFile = null;
  }
Esempio n. 9
0
  /**
   * Adds a set of refs to the set of packed-refs. Only non-symbolic refs are added. If a ref with
   * the given name already existed in packed-refs it is updated with the new value. Each loose ref
   * which was added to the packed-ref file is deleted. If a given ref can't be locked it will not
   * be added to the pack file.
   *
   * @param refs the refs to be added. Must be fully qualified.
   * @throws IOException
   */
  public void pack(List<String> refs) throws IOException {
    if (refs.size() == 0) return;
    FS fs = parent.getFS();

    // Lock the packed refs file and read the content
    LockFile lck = new LockFile(packedRefsFile);
    if (!lck.lock())
      throw new IOException(MessageFormat.format(JGitText.get().cannotLock, packedRefsFile));

    try {
      final PackedRefList packed = getPackedRefs();
      RefList<Ref> cur = readPackedRefs();

      // Iterate over all refs to be packed
      for (String refName : refs) {
        Ref ref = readRef(refName, cur);
        if (ref.isSymbolic()) continue; // can't pack symbolic refs
        // Add/Update it to packed-refs
        int idx = cur.find(refName);
        if (idx >= 0) cur = cur.set(idx, peeledPackedRef(ref));
        else cur = cur.add(idx, peeledPackedRef(ref));
      }

      // The new content for packed-refs is collected. Persist it.
      commitPackedRefs(lck, cur, packed);

      // Now delete the loose refs which are now packed
      for (String refName : refs) {
        // Lock the loose ref
        File refFile = fileFor(refName);
        if (!fs.exists(refFile)) continue;
        LockFile rLck = new LockFile(refFile);
        if (!rLck.lock()) continue;
        try {
          LooseRef currentLooseRef = scanRef(null, refName);
          if (currentLooseRef == null || currentLooseRef.isSymbolic()) continue;
          Ref packedRef = cur.get(refName);
          ObjectId clr_oid = currentLooseRef.getObjectId();
          if (clr_oid != null && clr_oid.equals(packedRef.getObjectId())) {
            RefList<LooseRef> curLoose, newLoose;
            do {
              curLoose = looseRefs.get();
              int idx = curLoose.find(refName);
              if (idx < 0) break;
              newLoose = curLoose.remove(idx);
            } while (!looseRefs.compareAndSet(curLoose, newLoose));
            int levels = levelsIn(refName) - 2;
            delete(refFile, levels, rLck);
          }
        } finally {
          rLck.unlock();
        }
      }
      // Don't fire refsChanged. The refs have not change, only their
      // storage.
    } finally {
      lck.unlock();
    }
  }
Esempio n. 10
0
  @Test
  public void testNoDeleteOnUnlockIfNotLocked() throws Exception {

    File lockFile = new File(IOHelper.getDefaultDataDirectory(), "lockToTest1");
    IOHelper.mkdirs(lockFile.getParentFile());
    lockFile.createNewFile();

    LockFile underTest = new LockFile(lockFile, true);

    underTest.lock();

    lockFile.delete();

    assertFalse("no longer valid", underTest.keepAlive());

    // a slave gets in
    lockFile.createNewFile();

    underTest.unlock();

    assertTrue("file still exists after unlock when not locked", lockFile.exists());
  }
Esempio n. 11
0
  void delete(RefDirectoryUpdate update) throws IOException {
    Ref dst = update.getRef();
    String name = dst.getName();

    // Write the packed-refs file using an atomic update. We might
    // wind up reading it twice, before and after the lock, to ensure
    // we don't miss an edit made externally.
    final PackedRefList packed = getPackedRefs();
    if (packed.contains(name)) {
      LockFile lck = new LockFile(packedRefsFile);
      if (!lck.lock()) throw new LockFailedException(packedRefsFile);
      try {
        PackedRefList cur = readPackedRefs();
        int idx = cur.find(name);
        if (0 <= idx) commitPackedRefs(lck, cur.remove(idx), packed);
      } finally {
        lck.unlock();
      }
    }

    RefList<LooseRef> curLoose, newLoose;
    do {
      curLoose = looseRefs.get();
      int idx = curLoose.find(name);
      if (idx < 0) break;
      newLoose = curLoose.remove(idx);
    } while (!looseRefs.compareAndSet(curLoose, newLoose));

    int levels = levelsIn(name) - 2;
    delete(logWriter.logFor(name), levels);
    if (dst.getStorage().isLoose()) {
      update.unlock();
      delete(fileFor(name), levels);
    }

    modCnt.incrementAndGet();
    fireRefsChanged();
  }
Esempio n. 12
0
  void releaseLock() {

    try {
      if (lf != null) {
        lf.tryRelease();
      }
    } catch (Exception e) {
      if (Trace.TRACE) {
        Trace.printSystemOut(e.toString());
      }
    }

    lf = null;
  }
Esempio n. 13
0
  /** Simple test where two locks attempt to lock same file. */
  @Test
  public void twoLocks() throws Exception {
    final File lockFile = util.createTempFile();

    final LockFile lf1 = new LockFile(lockFile, "lf1".getBytes());
    final LockFile lf2 = new LockFile(lockFile, "lf2".getBytes());

    try {
      // lf1 will obtain lock, lf2 should fail
      assertThat(lf1.lock(), is(true));
      assertThat(lf2.lock(), is(false));

      // repeating same step should be idempotent
      assertThat(lf1.lock(), is(true));
      assertThat(lf2.lock(), is(false));

      // verify who holds the lock
      assertThat(lf1.readBytes(), equalTo(lf1.getPayload()));
    } finally {
      // cleanup
      lf1.release();
      lf2.release();
    }
  }
Esempio n. 14
0
 @Override
 public Integer call() throws Exception {
   for (int i = 0; i < attempts; i++) {
     barrier.await(); // start together
     try {
       if (lockFile.lock()) {
         locked++;
         // verify that content of the file equals to our payload, as we own the lock
         assertThat(lockFile.readBytes(), equalTo(lockFile.getPayload()));
       }
       barrier
           .await(); // wait for others to attempt, and the one won should hold the lock during
                     // that
     } catch (Exception e) {
       // If an exception gets thrown, hang on to it so that it can be reported by the test
       // Unconventional, but it seems the cyclic barrier rules out normal approach of getting
       // the exception from Future.get()
       this.caughtException = e;
     } finally {
       lockFile.release(); // the one locked should release for next attempt
     }
   }
   return locked;
 }
Esempio n. 15
0
  private static void delete(final File file, final int depth, LockFile rLck) throws IOException {
    if (!file.delete() && file.isFile()) {
      throw new IOException(MessageFormat.format(JGitText.get().fileCannotBeDeleted, file));
    }

    if (rLck != null) {
      rLck.unlock(); // otherwise cannot delete dir below
    }
    File dir = file.getParentFile();
    for (int i = 0; i < depth; ++i) {
      if (!dir.delete()) {
        break; // ignore problem here
      }
      dir = dir.getParentFile();
    }
  }