Search in sources :

Example 76 with StorageException

use of com.google.gerrit.exceptions.StorageException in project gerrit by GerritCodeReview.

the class ReceiveCommits method parseCreate.

private void parseCreate(ReceiveCommand cmd) throws PermissionBackendException, NoSuchProjectException, IOException {
    try (TraceTimer traceTimer = newTimer("parseCreate")) {
        if (repo.resolve(cmd.getRefName()) != null) {
            reject(cmd, String.format("Cannot create ref '%s' because it already exists.", cmd.getRefName()));
            return;
        }
        RevObject obj;
        try {
            obj = receivePack.getRevWalk().parseAny(cmd.getNewId());
        } catch (IOException e) {
            throw new StorageException(String.format("Invalid object %s for %s creation", cmd.getNewId().name(), cmd.getRefName()), e);
        }
        logger.atFine().log("Creating %s", cmd);
        if (isHead(cmd) && !isCommit(cmd)) {
            return;
        }
        BranchNameKey branch = BranchNameKey.create(project.getName(), cmd.getRefName());
        try {
            // Must pass explicit user instead of injecting a provider into CreateRefControl, since
            // Provider<CurrentUser> within ReceiveCommits will always return anonymous.
            createRefControl.checkCreateRef(Providers.of(user), receivePack.getRepository(), branch, obj);
        } catch (AuthException denied) {
            rejectProhibited(cmd, denied);
            return;
        } catch (ResourceConflictException denied) {
            reject(cmd, "prohibited by Gerrit: " + denied.getMessage());
            return;
        }
        if (validRefOperation(cmd)) {
            validateRegularPushCommits(BranchNameKey.create(project.getNameKey(), cmd.getRefName()), cmd);
        }
    }
}
Also used : ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) BranchNameKey(com.google.gerrit.entities.BranchNameKey) RevObject(org.eclipse.jgit.revwalk.RevObject) TraceTimer(com.google.gerrit.server.logging.TraceContext.TraceTimer) AuthException(com.google.gerrit.extensions.restapi.AuthException) IOException(java.io.IOException) StorageException(com.google.gerrit.exceptions.StorageException)

Example 77 with StorageException

use of com.google.gerrit.exceptions.StorageException in project gerrit by GerritCodeReview.

the class ReceiveCommits method processCommandsUnsafe.

// Process as many commands as possible, but may leave some commands in state NOT_ATTEMPTED.
private void processCommandsUnsafe(Collection<ReceiveCommand> commands, MultiProgressMonitor progress) {
    logger.atFine().log("Calling user: %s, commands: %d", user.getLoggableName(), commands.size());
    // If the list of groups is large, the log entry may get dropped, so separate out.
    logger.atFine().log("Groups: %s", lazy(() -> user.getEffectiveGroups().getKnownGroups()));
    if (!projectState.getProject().getState().permitsWrite()) {
        for (ReceiveCommand cmd : commands) {
            reject(cmd, "prohibited by Gerrit: project state does not permit write");
        }
        return;
    }
    List<ReceiveCommand> magicCommands = new ArrayList<>();
    List<ReceiveCommand> regularCommands = new ArrayList<>();
    for (ReceiveCommand cmd : commands) {
        if (MagicBranch.isMagicBranch(cmd.getRefName())) {
            magicCommands.add(cmd);
        } else {
            regularCommands.add(cmd);
        }
    }
    if (!magicCommands.isEmpty() && !regularCommands.isEmpty()) {
        rejectRemaining(commands, "cannot combine normal pushes and magic pushes");
        return;
    }
    try {
        if (!magicCommands.isEmpty()) {
            parseMagicBranch(Iterables.getLast(magicCommands));
            // Using the submit option submits the created change(s) immediately without checking labels
            // nor submit rules. Hence we shouldn't record such pushes as "magic" which implies that
            // code review is being done.
            String pushKind = magicBranch != null && magicBranch.submit ? "direct_submit" : "magic";
            metrics.pushCount.increment(pushKind, project.getName(), getUpdateType(magicCommands));
        }
        if (!regularCommands.isEmpty()) {
            metrics.pushCount.increment("direct", project.getName(), getUpdateType(regularCommands));
        }
        if (!regularCommands.isEmpty()) {
            handleRegularCommands(regularCommands, progress);
            return;
        }
        boolean first = true;
        for (ReceiveCommand cmd : magicCommands) {
            if (first) {
                first = false;
            } else {
                reject(cmd, "duplicate request");
            }
        }
    } catch (PermissionBackendException | NoSuchProjectException | IOException err) {
        logger.atSevere().withCause(err).log("Failed to process refs in %s", project.getName());
        return;
    }
    Task newProgress = progress.beginSubTask("new", UNKNOWN);
    Task replaceProgress = progress.beginSubTask("updated", UNKNOWN);
    ImmutableList<CreateRequest> newChanges = ImmutableList.of();
    try {
        if (magicBranch != null && magicBranch.cmd.getResult() == NOT_ATTEMPTED) {
            try {
                newChanges = selectNewAndReplacedChangesFromMagicBranch(newProgress);
            } catch (IOException e) {
                throw new StorageException("Failed to select new changes in " + project.getName(), e);
            }
        }
        // Commit validation has already happened, so any changes without Change-Id are for the
        // deprecated feature.
        warnAboutMissingChangeId(newChanges);
        preparePatchSetsForReplace(newChanges);
        insertChangesAndPatchSets(newChanges, replaceProgress);
    } finally {
        newProgress.end();
        replaceProgress.end();
    }
    queueSuccessMessages(newChanges);
    logger.atFine().log("Command results: %s", lazy(() -> commands.stream().map(ReceiveCommits::commandToString).collect(joining(","))));
}
Also used : ReceiveCommand(org.eclipse.jgit.transport.ReceiveCommand) Task(com.google.gerrit.server.git.MultiProgressMonitor.Task) NoSuchProjectException(com.google.gerrit.server.project.NoSuchProjectException) ArrayList(java.util.ArrayList) PermissionBackendException(com.google.gerrit.server.permissions.PermissionBackendException) IOException(java.io.IOException) StorageException(com.google.gerrit.exceptions.StorageException)

Example 78 with StorageException

use of com.google.gerrit.exceptions.StorageException in project gerrit by GerritCodeReview.

the class DeleteGpgKey method apply.

@Override
public Response<?> apply(GpgKey rsrc, Input input) throws RestApiException, PGPException, IOException, ConfigInvalidException {
    PGPPublicKey key = rsrc.getKeyRing().getPublicKey();
    String fingerprint = BaseEncoding.base16().encode(key.getFingerprint());
    Optional<ExternalId> extId = externalIds.get(externalIdKeyFactory.create(SCHEME_GPGKEY, fingerprint));
    if (!extId.isPresent()) {
        throw new ResourceNotFoundException(fingerprint);
    }
    accountsUpdateProvider.get().update("Delete GPG Key via API", rsrc.getUser().getAccountId(), u -> u.deleteExternalId(extId.get()));
    try (PublicKeyStore store = storeProvider.get()) {
        store.remove(rsrc.getKeyRing().getPublicKey().getFingerprint());
        CommitBuilder cb = new CommitBuilder();
        PersonIdent committer = serverIdent.get();
        cb.setAuthor(rsrc.getUser().newCommitterIdent(committer));
        cb.setCommitter(committer);
        cb.setMessage("Delete public key " + keyIdToString(key.getKeyID()));
        RefUpdate.Result saveResult = store.save(cb);
        switch(saveResult) {
            case NO_CHANGE:
            case FAST_FORWARD:
                try {
                    deleteKeySenderFactory.create(rsrc.getUser(), ImmutableList.of(PublicKeyStore.keyToString(key))).send();
                } catch (EmailException e) {
                    logger.atSevere().withCause(e).log("Cannot send GPG key deletion message to %s", rsrc.getUser().getAccount().preferredEmail());
                }
                break;
            case LOCK_FAILURE:
            case FORCED:
            case IO_FAILURE:
            case NEW:
            case NOT_ATTEMPTED:
            case REJECTED:
            case REJECTED_CURRENT_BRANCH:
            case RENAMED:
            case REJECTED_MISSING_OBJECT:
            case REJECTED_OTHER_REASON:
            default:
                throw new StorageException(String.format("Failed to delete public key: %s", saveResult));
        }
    }
    return Response.none();
}
Also used : PersonIdent(org.eclipse.jgit.lib.PersonIdent) GerritPersonIdent(com.google.gerrit.server.GerritPersonIdent) ExternalId(com.google.gerrit.server.account.externalids.ExternalId) PublicKeyStore(com.google.gerrit.gpg.PublicKeyStore) EmailException(com.google.gerrit.exceptions.EmailException) PGPPublicKey(org.bouncycastle.openpgp.PGPPublicKey) CommitBuilder(org.eclipse.jgit.lib.CommitBuilder) PublicKeyStore.keyIdToString(com.google.gerrit.gpg.PublicKeyStore.keyIdToString) ResourceNotFoundException(com.google.gerrit.extensions.restapi.ResourceNotFoundException) StorageException(com.google.gerrit.exceptions.StorageException) RefUpdate(org.eclipse.jgit.lib.RefUpdate)

Example 79 with StorageException

use of com.google.gerrit.exceptions.StorageException in project gerrit by GerritCodeReview.

the class AccountCacheImpl method get.

@Override
public Map<Account.Id, AccountState> get(Set<Account.Id> accountIds) {
    try {
        try (Repository allUsers = repoManager.openRepository(allUsersName)) {
            // Get the default preferences for this Gerrit host
            Ref ref = allUsers.exactRef(RefNames.REFS_USERS_DEFAULT);
            CachedPreferences defaultPreferences = ref != null ? defaultPreferenceCache.get(ref.getObjectId()) : DefaultPreferencesCache.EMPTY;
            Set<CachedAccountDetails.Key> keys = Sets.newLinkedHashSetWithExpectedSize(accountIds.size());
            for (Account.Id id : accountIds) {
                Ref userRef = allUsers.exactRef(RefNames.refsUsers(id));
                if (userRef == null) {
                    continue;
                }
                keys.add(CachedAccountDetails.Key.create(id, userRef.getObjectId()));
            }
            ImmutableMap.Builder<Account.Id, AccountState> result = ImmutableMap.builder();
            for (Map.Entry<CachedAccountDetails.Key, CachedAccountDetails> account : accountDetailsCache.getAll(keys).entrySet()) {
                result.put(account.getKey().accountId(), AccountState.forCachedAccount(account.getValue(), defaultPreferences, externalIds));
            }
            return result.build();
        }
    } catch (IOException | ExecutionException e) {
        throw new StorageException(e);
    }
}
Also used : Account(com.google.gerrit.entities.Account) IOException(java.io.IOException) ImmutableMap(com.google.common.collect.ImmutableMap) Repository(org.eclipse.jgit.lib.Repository) Ref(org.eclipse.jgit.lib.Ref) ExecutionException(java.util.concurrent.ExecutionException) Map(java.util.Map) ImmutableMap(com.google.common.collect.ImmutableMap) StorageException(com.google.gerrit.exceptions.StorageException) CachedPreferences(com.google.gerrit.server.config.CachedPreferences)

Example 80 with StorageException

use of com.google.gerrit.exceptions.StorageException in project gerrit by GerritCodeReview.

the class StarredChangesUtil method updateLabels.

private void updateLabels(Repository repo, String refName, ObjectId oldObjectId, Collection<String> labels) throws IOException, InvalidLabelsException {
    try (TraceTimer traceTimer = TraceContext.newTimer("Update star labels", Metadata.builder().noteDbRefName(refName).resourceCount(labels.size()).build());
        RevWalk rw = new RevWalk(repo)) {
        RefUpdate u = repo.updateRef(refName);
        u.setExpectedOldObjectId(oldObjectId);
        u.setForceUpdate(true);
        u.setNewObjectId(writeLabels(repo, labels));
        u.setRefLogIdent(serverIdent.get());
        u.setRefLogMessage("Update star labels", true);
        RefUpdate.Result result = u.update(rw);
        switch(result) {
            case NEW:
            case FORCED:
            case NO_CHANGE:
            case FAST_FORWARD:
                gitRefUpdated.fire(allUsers, u, null);
                return;
            case LOCK_FAILURE:
                throw new LockFailureException(String.format("Update star labels on ref %s failed", refName), u);
            case IO_FAILURE:
            case NOT_ATTEMPTED:
            case REJECTED:
            case REJECTED_CURRENT_BRANCH:
            case RENAMED:
            case REJECTED_MISSING_OBJECT:
            case REJECTED_OTHER_REASON:
            default:
                throw new StorageException(String.format("Update star labels on ref %s failed: %s", refName, result.name()));
        }
    }
}
Also used : TraceTimer(com.google.gerrit.server.logging.TraceContext.TraceTimer) RevWalk(org.eclipse.jgit.revwalk.RevWalk) StorageException(com.google.gerrit.exceptions.StorageException) LockFailureException(com.google.gerrit.git.LockFailureException) RefUpdate(org.eclipse.jgit.lib.RefUpdate) BatchRefUpdate(org.eclipse.jgit.lib.BatchRefUpdate)

Aggregations

StorageException (com.google.gerrit.exceptions.StorageException)153 IOException (java.io.IOException)68 Change (com.google.gerrit.entities.Change)47 ObjectId (org.eclipse.jgit.lib.ObjectId)37 Repository (org.eclipse.jgit.lib.Repository)33 ChangeNotes (com.google.gerrit.server.notedb.ChangeNotes)30 PatchSet (com.google.gerrit.entities.PatchSet)29 RevCommit (org.eclipse.jgit.revwalk.RevCommit)28 ArrayList (java.util.ArrayList)25 ConfigInvalidException (org.eclipse.jgit.errors.ConfigInvalidException)24 Project (com.google.gerrit.entities.Project)22 Ref (org.eclipse.jgit.lib.Ref)22 ChangeData (com.google.gerrit.server.query.change.ChangeData)21 RevWalk (org.eclipse.jgit.revwalk.RevWalk)21 Account (com.google.gerrit.entities.Account)20 Inject (com.google.inject.Inject)19 Map (java.util.Map)19 Test (org.junit.Test)19 List (java.util.List)18 BranchNameKey (com.google.gerrit.entities.BranchNameKey)17