Search in sources :

Example 1 with StorageException

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

the class BaseInit method run.

@Override
public int run() throws Exception {
    final SiteInit init = createSiteInit();
    if (beforeInit(init)) {
        return 0;
    }
    init.flags.autoStart = getAutoStart() && init.site.isNew;
    init.flags.dev = isDev() && init.site.isNew;
    init.flags.skipPlugins = skipPlugins();
    init.flags.deleteCaches = getDeleteCaches();
    init.flags.isNew = init.site.isNew;
    final SiteRun run;
    try {
        init.initializer.run();
        init.flags.deleteOnFailure = false;
        Injector sysInjector = createSysInjector(init);
        IndexManagerOnInit indexManager = sysInjector.getInstance(IndexManagerOnInit.class);
        try {
            indexManager.start();
            run = createSiteRun(init);
            try {
                run.upgradeSchema();
            } catch (StorageException e) {
                String msg = "Couldn't upgrade schema. Expected if slave and read-only database";
                System.err.println(msg);
                logger.atSevere().withCause(e).log("%s", msg);
            }
            init.initializer.postRun(sysInjector);
        } finally {
            indexManager.stop();
        }
    } catch (Exception | Error failure) {
        if (init.flags.deleteOnFailure) {
            recursiveDelete(getSitePath());
        }
        throw failure;
    }
    System.err.println("Initialized " + getSitePath().toRealPath().normalize());
    afterInit(run);
    return 0;
}
Also used : IndexManagerOnInit(com.google.gerrit.pgm.init.index.IndexManagerOnInit) Injector(com.google.inject.Injector) StorageException(com.google.gerrit.exceptions.StorageException) FileNotFoundException(java.io.FileNotFoundException) InvocationTargetException(java.lang.reflect.InvocationTargetException) StorageException(com.google.gerrit.exceptions.StorageException) IOException(java.io.IOException) CreationException(com.google.inject.CreationException)

Example 2 with StorageException

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

the class PostGpgKeys method tryStoreKeys.

private Void tryStoreKeys(AccountResource rsrc, List<PGPPublicKeyRing> keyRings, Collection<Fingerprint> toRemove) throws RestApiException, PGPException, IOException {
    try (PublicKeyStore store = storeProvider.get()) {
        List<String> addedKeys = new ArrayList<>();
        IdentifiedUser user = rsrc.getUser();
        for (PGPPublicKeyRing keyRing : keyRings) {
            PGPPublicKey key = keyRing.getPublicKey();
            // Don't check web of trust; admins can fill in certifications later.
            CheckResult result = checkerFactory.create(user, store).disableTrust().check(key);
            if (!result.isOk()) {
                throw new BadRequestException(String.format("Problems with public key %s:\n%s", keyToString(key), Joiner.on('\n').join(result.getProblems())));
            }
            addedKeys.add(PublicKeyStore.keyToString(key));
            store.add(keyRing);
        }
        for (Fingerprint fp : toRemove) {
            store.remove(fp.get());
        }
        CommitBuilder cb = new CommitBuilder();
        PersonIdent committer = serverIdent.get();
        cb.setAuthor(user.newCommitterIdent(committer));
        cb.setCommitter(committer);
        RefUpdate.Result saveResult = store.save(cb);
        switch(saveResult) {
            case NEW:
            case FAST_FORWARD:
            case FORCED:
                if (!addedKeys.isEmpty()) {
                    try {
                        addKeySenderFactory.create(user, addedKeys).send();
                    } catch (EmailException e) {
                        logger.atSevere().withCause(e).log("Cannot send GPG key added message to %s", rsrc.getUser().getAccount().preferredEmail());
                    }
                }
                if (!toRemove.isEmpty()) {
                    try {
                        deleteKeySenderFactory.create(user, toRemove.stream().map(Fingerprint::toString).collect(toList())).send();
                    } catch (EmailException e) {
                        logger.atSevere().withCause(e).log("Cannot send GPG key deleted message to %s", user.getAccount().preferredEmail());
                    }
                }
                break;
            case NO_CHANGE:
                break;
            case LOCK_FAILURE:
            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("Failed to save public keys: %s", saveResult));
        }
    }
    return null;
}
Also used : PGPPublicKeyRing(org.bouncycastle.openpgp.PGPPublicKeyRing) Fingerprint(com.google.gerrit.gpg.Fingerprint) ArrayList(java.util.ArrayList) PGPPublicKey(org.bouncycastle.openpgp.PGPPublicKey) CommitBuilder(org.eclipse.jgit.lib.CommitBuilder) PublicKeyStore.keyToString(com.google.gerrit.gpg.PublicKeyStore.keyToString) PublicKeyStore.keyIdToString(com.google.gerrit.gpg.PublicKeyStore.keyIdToString) IdentifiedUser(com.google.gerrit.server.IdentifiedUser) PersonIdent(org.eclipse.jgit.lib.PersonIdent) GerritPersonIdent(com.google.gerrit.server.GerritPersonIdent) CheckResult(com.google.gerrit.gpg.CheckResult) PublicKeyStore(com.google.gerrit.gpg.PublicKeyStore) EmailException(com.google.gerrit.exceptions.EmailException) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException) StorageException(com.google.gerrit.exceptions.StorageException) RefUpdate(org.eclipse.jgit.lib.RefUpdate)

Example 3 with StorageException

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

the class AccountManager method update.

private void update(AuthRequest who, ExternalId extId) throws IOException, ConfigInvalidException, AccountException {
    IdentifiedUser user = userFactory.create(extId.accountId());
    List<Consumer<AccountDelta.Builder>> accountUpdates = new ArrayList<>();
    // If the email address was modified by the authentication provider,
    // update our records to match the changed email.
    // 
    String newEmail = who.getEmailAddress();
    String oldEmail = extId.email();
    if (newEmail != null && !newEmail.equals(oldEmail)) {
        ExternalId extIdWithNewEmail = externalIdFactory.create(extId.key(), extId.accountId(), newEmail, extId.password());
        checkEmailNotUsed(extId.accountId(), extIdWithNewEmail);
        accountUpdates.add(u -> u.replaceExternalId(extId, extIdWithNewEmail));
        if (oldEmail != null && oldEmail.equals(user.getAccount().preferredEmail())) {
            accountUpdates.add(u -> u.setPreferredEmail(newEmail));
        }
    }
    if (!Strings.isNullOrEmpty(who.getDisplayName()) && !Objects.equals(user.getAccount().fullName(), who.getDisplayName())) {
        accountUpdates.add(a -> a.setFullName(who.getDisplayName()));
    }
    if (!realm.allowsEdit(AccountFieldName.USER_NAME) && who.getUserName().isPresent() && !who.getUserName().equals(user.getUserName())) {
        if (user.getUserName().isPresent()) {
            logger.atWarning().log("Not changing already set username %s to %s", user.getUserName().get(), who.getUserName().get());
        } else {
            logger.atWarning().log("Not setting username to %s", who.getUserName().get());
        }
    }
    if (!accountUpdates.isEmpty()) {
        Optional<AccountState> updatedAccount = accountsUpdateProvider.get().update("Update Account on Login", user.getAccountId(), AccountsUpdate.joinConsumers(accountUpdates));
        if (!updatedAccount.isPresent()) {
            throw new StorageException("Account " + user.getAccountId() + " has been deleted");
        }
    }
}
Also used : Consumer(java.util.function.Consumer) ExternalId(com.google.gerrit.server.account.externalids.ExternalId) ArrayList(java.util.ArrayList) IdentifiedUser(com.google.gerrit.server.IdentifiedUser) StorageException(com.google.gerrit.exceptions.StorageException)

Example 4 with StorageException

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

the class PublishCommentsOp method postUpdate.

@Override
public void postUpdate(PostUpdateContext ctx) {
    if (Strings.isNullOrEmpty(mailMessage) || comments.isEmpty()) {
        return;
    }
    ChangeNotes changeNotes = changeNotesFactory.createChecked(projectNameKey, psId.changeId());
    PatchSet ps = psUtil.get(changeNotes, psId);
    NotifyResolver.Result notify = ctx.getNotify(changeNotes.getChangeId());
    if (notify.shouldNotify()) {
        RepoView repoView;
        try {
            repoView = ctx.getRepoView();
        } catch (IOException ex) {
            throw new StorageException(String.format("Repository %s not found", ctx.getProject().get()), ex);
        }
        email.create(notify, changeNotes, ps, user, mailMessage, ctx.getWhen(), comments, null, labelDelta, repoView).sendAsync();
    }
    commentAdded.fire(ctx.getChangeData(changeNotes), ps, ctx.getAccount(), mailMessage, ImmutableMap.of(), ImmutableMap.of(), ctx.getWhen());
}
Also used : NotifyResolver(com.google.gerrit.server.change.NotifyResolver) PatchSet(com.google.gerrit.entities.PatchSet) ChangeNotes(com.google.gerrit.server.notedb.ChangeNotes) IOException(java.io.IOException) StorageException(com.google.gerrit.exceptions.StorageException) RepoView(com.google.gerrit.server.update.RepoView)

Example 5 with StorageException

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

the class StarredChangesUtil method deleteRef.

private void deleteRef(Repository repo, String refName, ObjectId oldObjectId) throws IOException {
    if (ObjectId.zeroId().equals(oldObjectId)) {
        // ref doesn't exist
        return;
    }
    try (TraceTimer traceTimer = TraceContext.newTimer("Delete star labels", Metadata.builder().noteDbRefName(refName).build())) {
        RefUpdate u = repo.updateRef(refName);
        u.setForceUpdate(true);
        u.setExpectedOldObjectId(oldObjectId);
        u.setRefLogIdent(serverIdent.get());
        u.setRefLogMessage("Unstar change", true);
        RefUpdate.Result result = u.delete();
        switch(result) {
            case FORCED:
                gitRefUpdated.fire(allUsers, u, null);
                return;
            case LOCK_FAILURE:
                throw new LockFailureException(String.format("Delete star ref %s failed", refName), u);
            case NEW:
            case NO_CHANGE:
            case FAST_FORWARD:
            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("Delete star ref %s failed: %s", refName, result.name()));
        }
    }
}
Also used : TraceTimer(com.google.gerrit.server.logging.TraceContext.TraceTimer) 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