/**
  * Abort txn.
  *
  * @param txnId the id of the transaction
  * @throws js.co.uk.tuplespace.store.TransactionException the transaction exception
  */
 public synchronized Collection<TimeoutEntry<V>> abortTxn(final TransactionID txnId)
     throws TransactionException {
   final Transaction<V> txn = idToTxnMap.remove(txnId);
   final Collection<TimeoutEntry<V>> items = txn.abort();
   txnTimeoutQueue.remove(txn);
   return items;
 }
Ejemplo n.º 2
0
 /**
  * Get value of data item
  *
  * @param t
  * @param dataItem
  * @return Value of data item
  * @throws Exception
  * @author Deepti Verma
  */
 private Integer readDataItem(Transaction t, String dataItem) throws Exception {
   Site availableSite =
       getAvailableSiteToReadFrom(dataItem); // Get sites where the dataitem is present
   if (availableSite == null) {
     t.isWaiting =
         true; // There are no sites up having that dataitem then transaction needs to wait until
               // the site is up
     transactionWaitingList.add(t);
     return null;
   }
   // Read only data items do not need locks
   if (t.readonlyTransaction) {
     return availableSite.readOnlyDataItem(dataItem, t.transactionStartTimestamp);
   } else {
     // Obtain read-only lock and read data item value
     if (t.getLock(availableSite, dataItem, Site.lockType.READ_LOCK)) {
       return availableSite.readDataItem(dataItem);
     } else {
       // if we are unable to obtain read only lock add transaction to waiting list
       t.isWaiting = true;
       transactionWaitingList.add(t);
       for (Transaction t1 :
           transactionList) { // check if transaction should be executed according to wait die
                              // protocol
         if (t1.isRunning
             && !t1.transactionName.equalsIgnoreCase(t.transactionName)
             && t1.lockOnDataItems.contains(dataItem)) {
           if (t1.transactionStartTimestamp < t.transactionStartTimestamp) {
             t.abort(
                 "Transaction "
                     + t1.transactionName
                     + " is older than "
                     + t.transactionName
                     + " and "
                     + t1.transactionName
                     + " holds lock on "
                     + dataItem);
           } else {
             t.isWaiting = true;
             transactionWaitingList.add(t);
             anyTransactionsWaiting = true;
           }
           // break;
         }
       }
       return null;
     }
   }
 }
Ejemplo n.º 3
0
 /**
  * End transaction
  *
  * @param t - transaction to be ended
  * @throws Exception
  * @author Shashank
  */
 private void endTransaction(Transaction t) throws Exception {
   if (t != null) {
     if (t.isRunning) {
       if (t.isWaiting) { // Abort Transaction if not all sites have been up since it accessed
                          // dataitems
         t.abort("Operations still waiting");
         // System.out.println("Aborting transaction "+t.transactionName);
       } else {
         t.commit(currentTimeStamp);
         // System.out.println("Commiting transaction "+t.transactionName);
       }
     }
   }
   transactionList.remove(t); // Remove transaction from transaction list when the end is complete
 }
Ejemplo n.º 4
0
  @Test
  public void testReserveCursorRollback() {
    byte[] key = new byte[] {1, 1, 1};
    byte[] val = new byte[] {3, 3, 3};

    Transaction tx = env.createWriteTransaction();
    Cursor cursor = db.openCursor(tx);
    DirectBuffer keyBuf = new DirectBuffer(ByteBuffer.allocateDirect(key.length));
    keyBuf.putBytes(0, key);
    DirectBuffer valBuf = cursor.reserve(keyBuf, val.length);
    valBuf.putBytes(0, val);
    tx.abort();

    byte[] result = db.get(key);
    assertNull(result);
  }
Ejemplo n.º 5
0
  public List<WebURL> get(int max) throws DatabaseException {
    synchronized (mutex) {
      int matches = 0;
      List<WebURL> results = new ArrayList<WebURL>(max);

      Cursor cursor = null;
      OperationStatus result;
      DatabaseEntry key = new DatabaseEntry();
      DatabaseEntry value = new DatabaseEntry();
      Transaction txn;
      if (resumable) {
        txn = env.beginTransaction(null, null);
      } else {
        txn = null;
      }
      try {
        cursor = urlsDB.openCursor(txn, null);
        result = cursor.getFirst(key, value, null);

        while (matches < max && result == OperationStatus.SUCCESS) {
          if (value.getData().length > 0) {
            results.add(webURLBinding.entryToObject(value));
            matches++;
          }
          result = cursor.getNext(key, value, null);
        }
      } catch (DatabaseException e) {
        if (txn != null) {
          txn.abort();
          txn = null;
        }
        throw e;
      } finally {
        if (cursor != null) {
          cursor.close();
        }
        if (txn != null) {
          txn.commit();
        }
      }
      return results;
    }
  }
Ejemplo n.º 6
0
  public void delete(int count) throws DatabaseException {
    synchronized (mutex) {
      int matches = 0;

      Cursor cursor = null;
      OperationStatus result;
      DatabaseEntry key = new DatabaseEntry();
      DatabaseEntry value = new DatabaseEntry();
      Transaction txn;
      if (resumable) {
        txn = env.beginTransaction(null, null);
      } else {
        txn = null;
      }
      try {
        cursor = urlsDB.openCursor(txn, null);
        result = cursor.getFirst(key, value, null);

        while (matches < count && result == OperationStatus.SUCCESS) {
          cursor.delete();
          matches++;
          result = cursor.getNext(key, value, null);
        }
      } catch (DatabaseException e) {
        if (txn != null) {
          txn.abort();
          txn = null;
        }
        throw e;
      } finally {
        if (cursor != null) {
          cursor.close();
        }
        if (txn != null) {
          txn.commit();
        }
      }
    }
  }
Ejemplo n.º 7
0
 /**
  * Execute write to all sites for a data item by a transaction
  *
  * @param t: transaction that issued the write command
  * @param dataItem : data item whose new value is to be written
  * @param value: new value of the data item
  * @param operation : write command
  * @throws Exception
  * @author Deepti Verma
  */
 private void writeToAllSites(Transaction t, String dataItem, int value, String operation)
     throws Exception {
   /*if(t.lockOnDataItems.contains(dataItem)){
   	for(Site s:SiteManager.siteList){
   		s.writeDataItem(dataItem, value,currentTimeStamp);
   	}
   }else{*/
   boolean gettingLockSuccessful =
       t.getLock(dataItem, Site.lockType.WRITE_LOCK); // obtain lock on data item
   if (gettingLockSuccessful) { // if a lock is obtained successfully, write on each site
     ArrayList<Site> sites =
         getSitesContainingDataitem(dataItem); // Get all sites containing the data item
     if (sites.isEmpty()) { // No sites are up to get a lock
       t.isWaiting = true;
       transactionWaitingList.add(t); // Add transactions to the waiting list
       t.operationWaiting =
           operation; // After the transaction is set to waiting it cannot accept anymore
                      // operations so just set the filed operation waiting to the operation
       anyTransactionsWaiting = true; // Indicate that the transactions are waiting
     } else {
       t.isWaiting = false; // If getting lock was successful then the transaction need not wait
       for (Site s : sites) {
         s.writeDataItem(
             dataItem,
             value,
             currentTimeStamp); // Write on all sites (written first to buffer and then to
                                // secondary storage at commit time)
       }
     }
   } else { // If getting locks on the data item was unsuccessful then check for transactions
            // holding locks on that data item
     // Else, check for transactions older than this transaction and decide if abort has to be
     // executed according to wait-die protocol
     for (Transaction t1 :
         transactionList) { // Loop through every transaction in the transaction list which has a
                            // lock on that data item
       if (t1.isRunning
           && !t1.transactionName.equalsIgnoreCase(t.transactionName)
           && t1.lockOnDataItems.contains(dataItem)) {
         // If the transaction in transaction list having lock on the data item is older than the
         // transaction trying to wrtie then abort the transaction
         if (t1.transactionStartTimestamp < t.transactionStartTimestamp) {
           t.abort(
               "because of wait-die. Transaction "
                   + t1.transactionName
                   + " is older than "
                   + t.transactionName
                   + " and "
                   + t1.transactionName
                   + " holds lock on "
                   + dataItem);
         } else { // put transaction in waiting if there is no older transaction holding a lock on
                  // the data item
           // t1.abort("Transaction "+t.transactionName+" is older than "+t1.transactionName);
           t.isWaiting =
               true; // Transaction needs to wait as it is older than the transaction holding the
                     // lock on the data item
           transactionWaitingList.add(t); // Add transactions to the waiting list
           t.operationWaiting =
               operation; // After the transaction is set to waiting it cannot accept anymore
                          // operations so just set the filed operation waiting to the operation
           anyTransactionsWaiting = true; // Indicate that the transactions are waiting
           // writeToAllSites(t,dataItem,value);
         }
         // break;
       }
     }
   }
 }
  /** Test open and close of an environment. */
  public void testCacheStats() throws DatabaseException {

    EnvironmentConfig envConfig = TestUtils.initEnvConfig();
    envConfig.setTransactional(true);
    envConfig.setConfigParam(EnvironmentParams.NODE_MAX.getName(), "6");
    envConfig.setAllowCreate(true);
    env = new Environment(envHome, envConfig);
    EnvironmentStats stat = env.getStats(TestUtils.FAST_STATS);
    env.close();
    env = null;
    assertEquals(0, stat.getNCacheMiss());
    assertEquals(0, stat.getNNotResident());

    // Try to open and close again, now that the environment exists
    envConfig.setAllowCreate(false);
    envConfig.setConfigParam(EnvironmentParams.JE_LOGGING_LEVEL.getName(), "CONFIG");
    env = new Environment(envHome, envConfig);
    DatabaseConfig dbConfig = new DatabaseConfig();
    dbConfig.setTransactional(true);
    dbConfig.setAllowCreate(true);
    Database db = env.openDatabase(null, "foo", dbConfig);
    db.put(null, new DatabaseEntry(new byte[0]), new DatabaseEntry(new byte[0]));
    Transaction txn = env.beginTransaction(null, null);
    db.put(txn, new DatabaseEntry(new byte[0]), new DatabaseEntry(new byte[0]));
    stat = env.getStats(TestUtils.FAST_STATS);
    MemoryBudget mb = DbInternal.envGetEnvironmentImpl(env).getMemoryBudget();

    assertEquals(mb.getCacheMemoryUsage(), stat.getCacheTotalBytes());
    assertEquals(mb.getLogBufferBudget(), stat.getBufferBytes());
    assertEquals(mb.getTreeMemoryUsage() + mb.getTreeAdminMemoryUsage(), stat.getDataBytes());
    assertEquals(mb.getLockMemoryUsage(), stat.getLockBytes());
    assertEquals(mb.getAdminMemoryUsage(), stat.getAdminBytes());

    assertTrue(stat.getBufferBytes() > 0);
    assertTrue(stat.getDataBytes() > 0);
    assertTrue(stat.getLockBytes() > 0);
    assertTrue(stat.getAdminBytes() > 0);

    assertEquals(
        stat.getCacheTotalBytes(),
        stat.getBufferBytes() + stat.getDataBytes() + stat.getLockBytes() + stat.getAdminBytes());

    assertEquals(12, stat.getNCacheMiss());
    assertEquals(12, stat.getNNotResident());

    /* Test deprecated getCacheDataBytes method. */
    final EnvironmentStats finalStat = stat;
    final long expectCacheDataBytes = mb.getCacheMemoryUsage() - mb.getLogBufferBudget();
    (new Runnable() {
          @Deprecated
          public void run() {
            assertEquals(expectCacheDataBytes, finalStat.getCacheDataBytes());
          }
        })
        .run();

    txn.abort();
    db.close();
    env.close();
    env = null;
  }
Ejemplo n.º 9
0
    //
    // XXX Figure out the appropriate way to pick out IDs.
    //
    int txn() {
      Cursor acurs = null;
      Cursor bcurs = null;
      Cursor hcurs = null;
      Cursor tcurs = null;
      Transaction t = null;

      Defrec rec = new Defrec();
      Histrec hrec = new Histrec();
      int account, branch, teller;

      DatabaseEntry d_dbt = new DatabaseEntry();
      DatabaseEntry d_histdbt = new DatabaseEntry();
      DatabaseEntry k_dbt = new DatabaseEntry();
      DatabaseEntry k_histdbt = new DatabaseEntry();

      account = TpcbExample.this.random_id(TpcbExample.ACCOUNT);
      branch = TpcbExample.this.random_id(TpcbExample.BRANCH);
      teller = TpcbExample.this.random_id(TpcbExample.TELLER);

      // The history key will not actually be retrieved,
      // but it does need to be set to something.
      byte[] hist_key = new byte[4];
      k_histdbt.setData(hist_key);
      k_histdbt.setSize(4 /* == sizeof(int)*/);

      byte[] key_bytes = new byte[4];
      k_dbt.setData(key_bytes);
      k_dbt.setSize(4 /* == sizeof(int)*/);

      d_dbt.setData(rec.data);
      d_dbt.setUserBuffer(rec.length(), true);

      hrec.set_aid(account);
      hrec.set_bid(branch);
      hrec.set_tid(teller);
      hrec.set_amount(10);
      // Request 0 bytes since we're just positioning.
      d_histdbt.setPartial(0, 0, true);

      // START PER-TRANSACTION TIMING.
      //
      // Technically, TPCB requires a limit on response time, you only
      // get to count transactions that complete within 2 seconds.
      // That's not an issue for this sample application -- regardless,
      // here's where the transaction begins.
      try {
        t = dbenv.beginTransaction(null, null);

        acurs = adb.openCursor(t, null);
        bcurs = bdb.openCursor(t, null);
        tcurs = tdb.openCursor(t, null);
        hcurs = hdb.openCursor(t, null);

        // Account record
        k_dbt.setRecordNumber(account);
        if (acurs.getSearchKey(k_dbt, d_dbt, null) != OperationStatus.SUCCESS)
          throw new Exception("acurs get failed");
        rec.set_balance(rec.get_balance() + 10);
        acurs.putCurrent(d_dbt);

        // Branch record
        k_dbt.setRecordNumber(branch);
        if (bcurs.getSearchKey(k_dbt, d_dbt, null) != OperationStatus.SUCCESS)
          throw new Exception("bcurs get failed");
        rec.set_balance(rec.get_balance() + 10);
        bcurs.putCurrent(d_dbt);

        // Teller record
        k_dbt.setRecordNumber(teller);
        if (tcurs.getSearchKey(k_dbt, d_dbt, null) != OperationStatus.SUCCESS)
          throw new Exception("ccurs get failed");
        rec.set_balance(rec.get_balance() + 10);
        tcurs.putCurrent(d_dbt);

        // History record
        d_histdbt.setPartial(0, 0, false);
        d_histdbt.setData(hrec.data);
        d_histdbt.setUserBuffer(hrec.length(), true);
        if (hdb.append(t, k_histdbt, d_histdbt) != OperationStatus.SUCCESS)
          throw new DatabaseException("put failed");

        acurs.close();
        acurs = null;
        bcurs.close();
        bcurs = null;
        tcurs.close();
        tcurs = null;
        hcurs.close();
        hcurs = null;

        // null out t in advance; if the commit fails,
        // we don't want to abort it in the catch clause.
        Transaction tmptxn = t;
        t = null;
        tmptxn.commit();

        // END TIMING
        return (0);
      } catch (Exception e) {
        try {
          if (acurs != null) acurs.close();
          if (bcurs != null) bcurs.close();
          if (tcurs != null) tcurs.close();
          if (hcurs != null) hcurs.close();
          if (t != null) t.abort();
        } catch (DatabaseException dbe) {
          // not much we can do here.
        }

        if (TpcbExample.this.verbose) {
          System.out.println(
              "Transaction A="
                  + String.valueOf(account)
                  + " B="
                  + String.valueOf(branch)
                  + " T="
                  + String.valueOf(teller)
                  + " failed");
          System.out.println("Reason: " + e.toString());
        }
        return (-1);
      }
    }