Search in sources :

Example 81 with StorageException

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

the class AccountManager method authenticate.

/**
 * Authenticate the user, potentially creating a new account if they are new.
 *
 * @param who identity of the user, with any details we received about them.
 * @return the result of authenticating the user.
 * @throws AccountException the account does not exist, and cannot be created, or exists, but
 *     cannot be located, is unable to be activated or deactivated, or is inactive, or cannot be
 *     added to the admin group (only for the first account).
 */
public AuthResult authenticate(AuthRequest who) throws AccountException, IOException {
    try {
        who = realm.authenticate(who);
    } catch (NoSuchUserException e) {
        deactivateAccountIfItExists(who);
        throw e;
    }
    try {
        Optional<ExternalId> optionalExtId = externalIds.get(who.getExternalIdKey());
        if (!optionalExtId.isPresent()) {
            logger.atFine().log("External ID for account %s not found. A new account will be automatically created.", who.getUserName());
            return create(who);
        }
        ExternalId extId = optionalExtId.get();
        Optional<AccountState> accountState = byIdCache.get(extId.accountId());
        if (!accountState.isPresent()) {
            logger.atSevere().log("Authentication with external ID %s failed. Account %s doesn't exist.", extId.key().get(), extId.accountId().get());
            throw new AccountException("Authentication error, account not found");
        }
        // Account exists
        Optional<Account> act = updateAccountActiveStatus(who, accountState.get().account());
        if (!act.isPresent()) {
            // since we don't support deletion of accounts.
            throw new AccountException("Authentication error, account not found");
        }
        if (!act.get().isActive()) {
            throw new AccountException("Authentication error, account inactive");
        }
        // return the identity to the caller.
        update(who, extId);
        return new AuthResult(extId.accountId(), who.getExternalIdKey(), false);
    } catch (StorageException | ConfigInvalidException e) {
        throw new AccountException("Authentication error", e);
    }
}
Also used : Account(com.google.gerrit.entities.Account) ConfigInvalidException(org.eclipse.jgit.errors.ConfigInvalidException) NoSuchUserException(com.google.gerrit.server.auth.NoSuchUserException) ExternalId(com.google.gerrit.server.account.externalids.ExternalId) StorageException(com.google.gerrit.exceptions.StorageException)

Example 82 with StorageException

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

the class ConsistencyChecker method insertMergedPatchSet.

private void insertMergedPatchSet(final RevCommit commit, @Nullable PatchSet.Id psIdToDelete, boolean reuseOldPsId) {
    ProblemInfo notFound = problem("No patch set found for merged commit " + commit.name());
    if (!user.get().isIdentifiedUser()) {
        notFound.status = Status.FIX_FAILED;
        notFound.outcome = "Must be called by an identified user to insert new patch set";
        return;
    }
    ProblemInfo insertPatchSetProblem;
    ProblemInfo deleteOldPatchSetProblem;
    if (psIdToDelete == null) {
        insertPatchSetProblem = problem(String.format("Expected merged commit %s has no associated patch set", commit.name()));
        deleteOldPatchSetProblem = null;
    } else {
        String msg = String.format("Expected merge commit %s corresponds to patch set %s," + " not the current patch set %s", commit.name(), psIdToDelete.get(), change().currentPatchSetId().get());
        // Maybe an identical problem, but different fix.
        deleteOldPatchSetProblem = reuseOldPsId ? null : problem(msg);
        insertPatchSetProblem = problem(msg);
    }
    List<ProblemInfo> currProblems = new ArrayList<>(3);
    currProblems.add(notFound);
    if (deleteOldPatchSetProblem != null) {
        currProblems.add(deleteOldPatchSetProblem);
    }
    currProblems.add(insertPatchSetProblem);
    try {
        PatchSet.Id psId = (psIdToDelete != null && reuseOldPsId) ? psIdToDelete : ChangeUtil.nextPatchSetId(repo, change().currentPatchSetId());
        PatchSetInserter inserter = patchSetInserterFactory.create(notes, psId, commit);
        try (BatchUpdate bu = newBatchUpdate()) {
            bu.setRepository(repo, rw, oi);
            if (psIdToDelete != null) {
                // Delete the given patch set ref. If reuseOldPsId is true,
                // PatchSetInserter will reinsert the same ref, making it a no-op.
                bu.addOp(notes.getChangeId(), new BatchUpdateOp() {

                    @Override
                    public void updateRepo(RepoContext ctx) throws IOException {
                        ctx.addRefUpdate(commit, ObjectId.zeroId(), psIdToDelete.toRefName());
                    }
                });
                if (!reuseOldPsId) {
                    bu.addOp(notes.getChangeId(), new DeletePatchSetFromDbOp(requireNonNull(deleteOldPatchSetProblem), psIdToDelete));
                }
            }
            bu.setNotify(NotifyResolver.Result.none());
            bu.addOp(notes.getChangeId(), inserter.setValidate(false).setFireRevisionCreated(false).setAllowClosed(true).setMessage("Patch set for merged commit inserted by consistency checker"));
            bu.addOp(notes.getChangeId(), new FixMergedOp(notFound));
            bu.execute();
        }
        notes = notesFactory.createChecked(inserter.getChange());
        insertPatchSetProblem.status = Status.FIXED;
        insertPatchSetProblem.outcome = "Inserted as patch set " + psId.get();
    } catch (StorageException | IOException | UpdateException | RestApiException e) {
        logger.atWarning().withCause(e).log("Error in consistency check of change %s", notes.getChangeId());
        for (ProblemInfo pi : currProblems) {
            pi.status = Status.FIX_FAILED;
            pi.outcome = "Error inserting merged patch set";
        }
        return;
    }
}
Also used : RepoContext(com.google.gerrit.server.update.RepoContext) ProblemInfo(com.google.gerrit.extensions.common.ProblemInfo) ArrayList(java.util.ArrayList) PatchSet(com.google.gerrit.entities.PatchSet) IOException(java.io.IOException) BatchUpdate(com.google.gerrit.server.update.BatchUpdate) UpdateException(com.google.gerrit.server.update.UpdateException) RestApiException(com.google.gerrit.extensions.restapi.RestApiException) StorageException(com.google.gerrit.exceptions.StorageException) BatchUpdateOp(com.google.gerrit.server.update.BatchUpdateOp)

Example 83 with StorageException

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

the class CommentContextCacheImpl method getAll.

@Override
public ImmutableMap<CommentContextKey, CommentContext> getAll(Iterable<CommentContextKey> inputKeys) {
    ImmutableMap.Builder<CommentContextKey, CommentContext> result = ImmutableMap.builder();
    // We do two transformations to the input keys: first we adjust the max context padding, and
    // second we hash the file path. The transformed keys are used to request context from the
    // cache. Keeping a map of the original inputKeys to the transformed keys
    Map<CommentContextKey, CommentContextKey> inputKeysToCacheKeys = Streams.stream(inputKeys).collect(Collectors.toMap(Function.identity(), k -> adjustMaxContextPadding(k).toBuilder().path(Loader.hashPath(k.path())).build()));
    try {
        ImmutableMap<CommentContextKey, CommentContext> allContext = contextCache.getAll(inputKeysToCacheKeys.values());
        for (CommentContextKey inputKey : inputKeys) {
            CommentContextKey cacheKey = inputKeysToCacheKeys.get(inputKey);
            result.put(inputKey, allContext.get(cacheKey));
        }
        return result.build();
    } catch (ExecutionException e) {
        throw new StorageException("Failed to retrieve comments' context", e);
    }
}
Also used : Module(com.google.inject.Module) Iterables(com.google.common.collect.Iterables) LoadingCache(com.google.common.cache.LoadingCache) Inject(com.google.inject.Inject) Comment(com.google.gerrit.entities.Comment) HumanComment(com.google.gerrit.entities.HumanComment) CommentsUtil(com.google.gerrit.server.CommentsUtil) Hashing(com.google.common.hash.Hashing) HashMap(java.util.HashMap) Function(java.util.function.Function) ImmutableList(com.google.common.collect.ImmutableList) Map(java.util.Map) Change(com.google.gerrit.entities.Change) Weigher(com.google.common.cache.Weigher) AllCommentContextProto(com.google.gerrit.server.cache.proto.Cache.AllCommentContextProto) ImmutableMap(com.google.common.collect.ImmutableMap) UTF_8(java.nio.charset.StandardCharsets.UTF_8) StorageException(com.google.gerrit.exceptions.StorageException) ContextInput(com.google.gerrit.server.comment.CommentContextLoader.ContextInput) ChangeNotes(com.google.gerrit.server.notedb.ChangeNotes) IOException(java.io.IOException) Streams(com.google.common.collect.Streams) CommentContext(com.google.gerrit.entities.CommentContext) Collectors(java.util.stream.Collectors) CacheModule(com.google.gerrit.server.cache.CacheModule) CacheLoader(com.google.common.cache.CacheLoader) ExecutionException(java.util.concurrent.ExecutionException) Protos(com.google.gerrit.proto.Protos) CacheSerializer(com.google.gerrit.server.cache.serialize.CacheSerializer) List(java.util.List) CommentContextProto(com.google.gerrit.server.cache.proto.Cache.AllCommentContextProto.CommentContextProto) Project(com.google.gerrit.entities.Project) Named(com.google.inject.name.Named) VisibleForTesting(com.google.common.annotations.VisibleForTesting) FluentLogger(com.google.common.flogger.FluentLogger) CommentContext(com.google.gerrit.entities.CommentContext) ExecutionException(java.util.concurrent.ExecutionException) StorageException(com.google.gerrit.exceptions.StorageException) ImmutableMap(com.google.common.collect.ImmutableMap)

Example 84 with StorageException

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

the class GroupIndexerImpl method index.

@Override
public void index(AccountGroup.UUID uuid) {
    // Evict the cache to get an up-to-date value for sure.
    groupCache.evict(uuid);
    Optional<InternalGroup> internalGroup = groupCache.get(uuid);
    if (internalGroup.isPresent()) {
        logger.atFine().log("Replace group %s in index", uuid.get());
    } else {
        logger.atFine().log("Delete group %s from index", uuid.get());
    }
    for (Index<AccountGroup.UUID, InternalGroup> i : getWriteIndexes()) {
        if (internalGroup.isPresent()) {
            try (TraceTimer traceTimer = TraceContext.newTimer("Replacing group", Metadata.builder().groupUuid(uuid.get()).indexVersion(i.getSchema().getVersion()).build())) {
                i.replace(internalGroup.get());
            } catch (RuntimeException e) {
                throw new StorageException(String.format("Failed to replace group %s in index version %d", uuid.get(), i.getSchema().getVersion()), e);
            }
        } else {
            try (TraceTimer traceTimer = TraceContext.newTimer("Deleting group", Metadata.builder().groupUuid(uuid.get()).indexVersion(i.getSchema().getVersion()).build())) {
                i.delete(uuid);
            } catch (RuntimeException e) {
                throw new StorageException(String.format("Failed to delete group %s from index version %d", uuid.get(), i.getSchema().getVersion()), e);
            }
        }
    }
    fireGroupIndexedEvent(uuid.get());
}
Also used : TraceTimer(com.google.gerrit.server.logging.TraceContext.TraceTimer) StorageException(com.google.gerrit.exceptions.StorageException) InternalGroup(com.google.gerrit.entities.InternalGroup)

Example 85 with StorageException

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

the class ProjectIndexerImpl method index.

@Override
public void index(Project.NameKey nameKey) {
    Optional<ProjectState> projectState = projectCache.get(nameKey);
    if (projectState.isPresent()) {
        logger.atFine().log("Replace project %s in index", nameKey.get());
        ProjectData projectData = projectState.get().toProjectData();
        for (ProjectIndex i : getWriteIndexes()) {
            try (TraceTimer traceTimer = TraceContext.newTimer("Replacing project", Metadata.builder().projectName(nameKey.get()).indexVersion(i.getSchema().getVersion()).build())) {
                i.replace(projectData);
            } catch (RuntimeException e) {
                throw new StorageException(String.format("Failed to replace project %s in index version %d", nameKey.get(), i.getSchema().getVersion()), e);
            }
        }
        fireProjectIndexedEvent(nameKey.get());
    } else {
        logger.atFine().log("Delete project %s from index", nameKey.get());
        for (ProjectIndex i : getWriteIndexes()) {
            try (TraceTimer traceTimer = TraceContext.newTimer("Deleting project", Metadata.builder().projectName(nameKey.get()).indexVersion(i.getSchema().getVersion()).build())) {
                i.delete(nameKey);
            } catch (RuntimeException e) {
                throw new StorageException(String.format("Failed to delete project %s from index version %d", nameKey.get(), i.getSchema().getVersion()), e);
            }
        }
    }
}
Also used : TraceTimer(com.google.gerrit.server.logging.TraceContext.TraceTimer) ProjectState(com.google.gerrit.server.project.ProjectState) ProjectIndex(com.google.gerrit.index.project.ProjectIndex) StorageException(com.google.gerrit.exceptions.StorageException) ProjectData(com.google.gerrit.index.project.ProjectData)

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