Package com.google.walkaround.util.server.appengine.CheckedDatastore

Examples of com.google.walkaround.util.server.appengine.CheckedDatastore.CheckedTransaction


  public Permissions getPermissions(final SlobId slobId) throws IOException {
    try {
      return new RetryHelper().run(
          new RetryHelper.Body<Permissions>() {
            @Override public Permissions run() throws RetryableFailure, PermanentFailure {
              CheckedTransaction tx = datastore.beginTransaction();
              try {
                ConvMetadata metadata = convMetadataStore.get(tx, slobId);
                if (metadata.hasImportMetadata()
                    && !metadata.getImportMetadata().getImportFinished()) {
                  log.info(slobId + " still importing; " + participantId + " may not access");
                  return new Permissions(false, false);
                }
                // Can't use SlobStore here, that would be a cyclic dependency.
                MutationLog mutationLog = convSlobFacilities.getMutationLogFactory()
                    .create(tx, slobId);
                StateAndVersion stateAndVersion = mutationLog.reconstruct(null);
                if (stateAndVersion.getVersion() == 0) {
                  log.info(slobId + " does not exist; " + participantId + " may not access");
                  return new Permissions(false, false);
                }
                // TODO(ohler): introduce generics to avoid the cast.
                ReadableWaveletObject wavelet = (ReadableWaveletObject) stateAndVersion.getState();
                if (wavelet.getParticipants().contains(participantId)) {
                  log.info(slobId + " exists and " + participantId + " is on the participant list");
                  return new Permissions(true, true);
                } else {
                  log.info(slobId + " exists but "
                      + participantId + " is not on the participant list");
                  return new Permissions(false, false);
                }
              } finally {
                tx.close();
              }
            }
          });
    } catch (PermanentFailure e) {
      throw new IOException("Failed to get permissions for " + slobId);
View Full Code Here


    try {
      newId = new RetryHelper().run(
          new RetryHelper.Body<SlobId>() {
            @Override public SlobId run() throws RetryableFailure, PermanentFailure {
              SlobId convId = getRandomObjectId();
              CheckedTransaction tx = datastore.beginTransaction();
              try {
                convStore.newObject(tx, convId, makeObsoleteConvMetadata(), history,
                    inhibitPreAndPostCommit);
                convMetadataStore.put(tx, convId,
                    convMetadata != null ? convMetadata : new ConvMetadataGsonImpl());
                tx.commit();
              } catch (SlobAlreadyExistsException e) {
                throw new RetryableFailure("Slob id collision, retrying: " + convId, e);
              } catch (AccessDeniedException e) {
                throw new RuntimeException(
                    "Unexpected AccessDeniedException creating conv " + convId, e);
              } finally {
                tx.close();
              }
              return convId;
            }
          });
    } catch (PermanentFailure e) {
View Full Code Here

    try {
      return new RetryHelper().run(
          new RetryHelper.Body<SlobId>() {
            @Override public SlobId run() throws RetryableFailure, PermanentFailure {
              SlobId udwId = getRandomObjectId();
              CheckedTransaction tx = datastore.beginTransaction();
              try {
                udwStore.newObject(tx, udwId, metadata, initialHistory, false);
                tx.commit();
              } catch (SlobAlreadyExistsException e) {
                throw new RetryableFailure("Slob id collision, retrying: " + udwId, e);
              } catch (AccessDeniedException e) {
                throw new RuntimeException(
                    "Unexpected AccessDeniedException creating udw " + udwId, e);
              } finally {
                tx.close();
              }
              return udwId;
            }
          });
    } catch (PermanentFailure e) {
View Full Code Here

    }
  }

  @Nullable public T getWithoutTx(I id) throws IOException {
    try {
      CheckedTransaction tx = datastore.beginTransaction();
      try {
        return get(tx, id);
      } finally {
        tx.rollback();
      }
    } catch (PermanentFailure e) {
      log.log(Level.SEVERE, "Failed to look up " + id, e);
      throw new IOException(e);
    } catch (RetryableFailure e) {
View Full Code Here

  public void putWithoutTx(final T newEntry) throws IOException {
    Preconditions.checkNotNull(newEntry, "Null newEntry");
    try {
      new RetryHelper().run(new RetryHelper.VoidBody() {
        @Override public void run() throws RetryableFailure, PermanentFailure {
          CheckedTransaction tx = datastore.beginTransaction();
          try {
            put(tx, newEntry);
            tx.commit();
            log.info("Committed " + tx);
          } finally {
            tx.close();
          }
        }
      });
    } catch (PermanentFailure e) {
      throw new IOException(e);
View Full Code Here

  Secret provideSecret(final CheckedDatastore datastore, final Random random)
      throws PermanentFailure {
    return new RetryHelper().run(
        new RetryHelper.Body<Secret>() {
          @Override public Secret run() throws RetryableFailure, PermanentFailure {
            CheckedTransaction tx = datastore.beginTransaction();
            try {
              {
                Entity e = tx.get(SECRET_KEY);
                if (e != null) {
                  log.info("Using stored secret");
                  return Secret.of(
                      DatastoreUtil.getExistingProperty(e, SECRET_PROPERTY, Blob.class).getBytes());
                }
              }
              Secret newSecret = Secret.generate(random);
              Entity e = new Entity(SECRET_KEY);
              DatastoreUtil.setNonNullUnindexedProperty(e, SECRET_PROPERTY,
                  new Blob(newSecret.getBytes()));
              tx.put(e);
              tx.commit();
              log.info("Generated new secret");
              return newSecret;
            } finally {
              tx.close();
            }
          }
        });
  }
View Full Code Here

    private void addToPerUserTableWithoutTx(final SlobId newId, final boolean isPrivate)
        throws PermanentFailure {
      new RetryHelper().run(
          new RetryHelper.VoidBody() {
            @Override public void run() throws RetryableFailure, PermanentFailure {
              CheckedTransaction tx = datastore.beginTransaction();
              try {
                addToPerUserTable(tx, newId, isPrivate);
                tx.commit();
              } finally {
                tx.close();
              }
            }
          });
    }
View Full Code Here

    private void ensureParticipant(final SlobId convId) throws PermanentFailure {
      new RetryHelper().run(
          new RetryHelper.VoidBody() {
            @Override public void run() throws RetryableFailure, PermanentFailure {
              CheckedTransaction tx = datastore.beginTransaction();
              try {
                ConvMetadata metadata = convMetadataStore.get(tx, convId);
                Assert.check(metadata.hasImportMetadata(), "%s: Metadata has no import: %s",
                    convId, metadata);
                Assert.check(metadata.getImportMetadata().getImportFinished(),
                    "%s: still importing: %s", convId, metadata);
                MutationLog l = convSlobFacilities.getMutationLogFactory().create(tx, convId);
                StateAndVersion stateAndVersion = l.reconstruct(null);
                Assert.check(stateAndVersion.getVersion() > 0, "%s at version 0: %s",
                    convId, stateAndVersion);
                // TODO(ohler): use generics to avoid the cast
                ReadableWaveletObject state = (ReadableWaveletObject) stateAndVersion.getState();
                if (state.getParticipants().contains(importingUser)) {
                  log.info(importingUser + " is a participant at version "
                      + stateAndVersion.getVersion());
                  return;
                }
                WaveletOperation op =
                    HistorySynthesizer.newAddParticipant(importingUser.getAddress(),
                        // We preserve last modified time to avoid re-ordering people's inboxes
                        // just because another participant imported.
                        state.getLastModifiedMillis(),
                        importingUser.getAddress());
                log.info(importingUser + " is not a participant at version "
                    + stateAndVersion.getVersion() + ", adding " + op);
                MutationLog.Appender appender = l.prepareAppender().getAppender();
                try {
                  appender.append(
                      new ChangeData<String>(getFakeClientId(), SERIALIZER.serializeDelta(op)));
                } catch (ChangeRejected e) {
                  throw new RuntimeException("Appender rejected AddParticipant: " + op);
                }
                // TODO(ohler): Share more code with LocalMutationProcessor; having to call this
                // stuff here rather than just commit() is error-prone.
                convSlobFacilities.getLocalMutationProcessor().runPreCommit(tx, convId, appender);
                appender.finish();
                convSlobFacilities.getLocalMutationProcessor().schedulePostCommit(
                    tx, convId, appender);
                tx.commit();
              } finally {
                tx.close();
              }
            }
          });
    }
View Full Code Here

      }
      // Look up if already imported according to PerUserTable; if so, we have nothing to do.
      boolean alreadyImportedForThisUser = new RetryHelper().run(
          new RetryHelper.Body<Boolean>() {
            @Override public Boolean run() throws RetryableFailure, PermanentFailure {
              CheckedTransaction tx = datastore.beginTransaction();
              try {
                @Nullable RemoteConvWavelet entry =
                    perUserTable.getWavelet(tx, userId, instance, waveletName);
                if (isPrivate) {
                  if (entry != null && entry.getPrivateLocalId() != null
                      && !(task.hasExistingSlobIdToIgnore()
                          && new SlobId(task.getExistingSlobIdToIgnore()).equals(
                              entry.getPrivateLocalId()))) {
                    log.info("Private import already exists, aborting: " + entry);
                    return true;
                  } else {
                    return false;
                  }
                } else {
                  if (entry != null && entry.getSharedLocalId() != null
                      && !(task.hasExistingSlobIdToIgnore()
                          && new SlobId(task.getExistingSlobIdToIgnore()).equals(
                              entry.getSharedLocalId()))) {
                    log.info("Shared import already exists, aborting: " + entry);
                    return true;
                  } else {
                    return false;
                  }
                }
              } finally {
                tx.close();
              }
            }
          });
      if (alreadyImportedForThisUser) {
        throw TaskCompleted.noFollowup();
      }
      if (!isPrivate) {
        @Nullable SlobId existingSharedImport =
              sharedImportTable.lookupWithoutTx(instance, waveletName);
        if (existingSharedImport != null
            && !(task.hasExistingSlobIdToIgnore()
                && new SlobId(task.getExistingSlobIdToIgnore()).equals(existingSharedImport))) {
          log.info("Found existing shared import " + existingSharedImport + ", re-using");
          ensureParticipant(existingSharedImport);
          addToPerUserTableWithoutTx(existingSharedImport, isPrivate);
          throw TaskCompleted.noFollowup();
        }
      }
      Map<String, AttachmentId> attachmentMapping = getAttachmentsAndMapping(snapshot);
      List<WaveletOperation> participantFixup = Lists.newArrayList();
      if (isPrivate) {
        for (String participant : ImmutableList.copyOf(wavelet.getParticipantList())) {
          participantFixup.add(
              HistorySynthesizer.newRemoveParticipant(importingUser.getAddress(),
                  wavelet.getLastModifiedTimeMillis(), participant));
        }
        participantFixup.add(
            HistorySynthesizer.newAddParticipant(importingUser.getAddress(),
                wavelet.getLastModifiedTimeMillis(), importingUser.getAddress()));
      } else {
        if (!wavelet.getParticipantList().contains(importingUser.getAddress())) {
          log.info(
              importingUser + " is not a participant, adding: " + wavelet.getParticipantList());
          participantFixup.add(
              HistorySynthesizer.newAddParticipant(importingUser.getAddress(),
                  wavelet.getLastModifiedTimeMillis(), importingUser.getAddress()));
        }
      }
      log.info("participantFixup=" + participantFixup);
      boolean preserveHistory = !task.getSettings().getSynthesizeHistory();
      log.info("preserveHistory=" + preserveHistory);
      ImportMetadata importMetadata = new ImportMetadataGsonImpl();
      importMetadata.setImportBeginTimeMillis(System.currentTimeMillis());
      importMetadata.setImportFinished(false);
      importMetadata.setOriginalImporter(userId.getId());
      importMetadata.setSourceInstance(instance.serialize());
      importMetadata.setRemoteWaveId(waveletName.waveId.serialise());
      importMetadata.setRemoteWaveletId(waveletName.waveletId.serialise());
      importMetadata.setRemoteHistoryCopied(preserveHistory);
      importMetadata.setRemoteVersionImported(snapshot.getFirst().getVersion());
      ConvMetadataGsonImpl convMetadata = new ConvMetadataGsonImpl();
      convMetadata.setImportMetadata(importMetadata);
      final SlobId newId;
      if (!preserveHistory) {
        List<WaveletOperation> history = Lists.newArrayList();
        WaveletHistoryConverter converter = new WaveletHistoryConverter(
            getConvNindoConverter(attachmentMapping));
        for (WaveletOperation op :
            new HistorySynthesizer().synthesizeHistory(wavelet, snapshot.getSecond())) {
          history.add(converter.convertAndApply(convertGooglewaveToGmail(op)));
        }
        history.addAll(participantFixup);
        newId = waveletCreator.newConvWithGeneratedId(
            ImmutableList.<WaveletOperation>of(), convMetadata, true);
        ConvHistoryWriter historyWriter = new ConvHistoryWriter(newId);
        try {
          for (WaveletOperation op : history) {
            historyWriter.append(op);
          }
          historyWriter.finish();
        } catch (ChangeRejected e) {
          log.warning("Synthesized history rejected: " + history);
          throw new RuntimeException("Synthesized history rejected", e);
        }
      } else {
        long version = 0;
        newId = waveletCreator.newConvWithGeneratedId(
            ImmutableList.<WaveletOperation>of(), convMetadata, true);
        ConvHistoryWriter historyWriter = new ConvHistoryWriter(newId);
        WaveletHistoryConverter converter =
            new WaveletHistoryConverter(getConvNindoConverter(attachmentMapping));
        try {
          // NOTE(ohler): We have to stop at snapshot.getFirst().getVersion() even if
          // getRawDeltas gives us more, since otherwise, participantFixup may be out-of-date.
          while (version < snapshot.getFirst().getVersion()) {
            log.info("converter state: " + converter);
            List<ProtocolAppliedWaveletDelta> rawDeltas =
                robotApi.getRawDeltas(waveletName, version);
            for (ProtocolAppliedWaveletDelta rawDelta : rawDeltas) {
              WaveletDelta delta = CoreWaveletOperationSerializer.deserialize(
                  ProtocolWaveletDelta.parseFrom(rawDelta.getSignedOriginalDelta().getDelta()));
              for (WaveletOperation badOp : delta) {
                Preconditions.checkState(badOp.getContext().getTimestamp() == -1,
                    "Unexpected timestamp: %s in delta %s", badOp, delta);
                // TODO(ohler): Rename
                // CoreWaveletOperationSerializer.deserialize() to
                // deserializeWithNoTimestamp() or something.
                WaveletOperation withTimestamp = WaveletOperation.cloneOp(badOp,
                    new WaveletOperationContext(badOp.getContext().getCreator(),
                        rawDelta.getApplicationTimestamp(),
                        badOp.getContext().getVersionIncrement()));
                WaveletOperation converted =
                    converter.convertAndApply(convertGooglewaveToGmail(withTimestamp));
                //log.info(version + ": " + op + " -> " + converted);
                historyWriter.append(converted);
                version++;
              }
            }
          }
          historyWriter.append(participantFixup);
          historyWriter.finish();
        } catch (ChangeRejected e) {
          log.log(Level.SEVERE, "Change rejected somewhere at or before version " + version
              + ", re-importing without history", e);
          ImportSettings settings = task.getSettings();
          settings.setSynthesizeHistory(true);
          task.setSettings(settings);
          throw TaskCompleted.withFollowup(task);
        }
      }
      log.info("Imported wavelet " + waveletName + " as local id " + newId);
      boolean abandonAndRetry = new RetryHelper().run(
          new RetryHelper.Body<Boolean>() {
            @Override public Boolean run() throws RetryableFailure, PermanentFailure {
              CheckedTransaction tx = datastore.beginTransactionXG();
              try {
                if (!isPrivate) {
                  @Nullable SlobId existingSharedImport =
                      sharedImportTable.lookup(tx, instance, waveletName);
                  if (existingSharedImport != null
                      && !(task.hasExistingSlobIdToIgnore()
                          && new SlobId(task.getExistingSlobIdToIgnore()).equals(
                              existingSharedImport))) {
                    log.warning("Found existing shared import " + existingSharedImport
                        + ", abandoning import and retrying");
                    return true;
                  }
                  sharedImportTable.put(tx, instance, waveletName, newId);
                }
                if (!unlockWavelet(tx, newId)) {
                  // Already unlocked, which means this transaction is a spurious retry.
                  // Nothing to do.
                  return false;
                }
                addToPerUserTable(tx, newId, isPrivate);
                // We don't want to run the immediate post-commit actions in this task
                // since we don't want this task to fail if they crash.  So we
                // just schedule a task unconditionally.
                //
                // TODO(ohler): Decide what to do about pre-commit actions.  Maybe we should
                // run them here?
                convSlobFacilities.getPostCommitActionScheduler()
                    .unconditionallyScheduleTask(tx, newId);
                tx.commit();
                return false;
              } finally {
                tx.close();
              }
            }
          });
      if (abandonAndRetry) {
        throw TaskCompleted.withFollowup(task);
View Full Code Here

      version = cachedVersion.getValue();
      log.info("Version number from cache: " + version);
      snapshot = null;
    } else {
      try {
        CheckedTransaction tx = datastore.beginTransaction();
        try {
          MutationLog mutationLog = mutationLogFactory.create(tx, slobId);
          if (withSnapshot) {
            StateAndVersion x = mutationLog.reconstruct(null);
            version = x.getVersion();
            snapshot = x.getState().snapshot();
          } else {
            version = mutationLog.getVersion();
            snapshot = null;
          }
          if (version == 0) {
            throw new SlobNotFoundException(
                "Slob " + slobId + " (" + rootEntityKind + ") not found");
          }
        } finally {
          tx.rollback();
        }
      } catch (PermanentFailure e) {
        throw new IOException(e);
      } catch (RetryableFailure e) {
        throw new IOException(e);
View Full Code Here

TOP

Related Classes of com.google.walkaround.util.server.appengine.CheckedDatastore.CheckedTransaction

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.