Search in sources :

Example 6 with LockFailureException

use of com.google.gerrit.git.LockFailureException in project gerrit by GerritCodeReview.

the class IntBlobTest method storeWrongOldId.

@Test
public void storeWrongOldId() throws Exception {
    String refName = "refs/foo";
    LockFailureException thrown = assertThrows(LockFailureException.class, () -> IntBlob.store(repo, rw, projectName, refName, ObjectId.fromString("deadbeefdeadbeefdeadbeefdeadbeefdeadbeef"), 123, GitReferenceUpdated.DISABLED));
    assertThat(thrown.getFailedRefs()).containsExactly("refs/foo");
    assertThat(IntBlob.parse(repo, refName)).isEmpty();
}
Also used : LockFailureException(com.google.gerrit.git.LockFailureException) Test(org.junit.Test)

Example 7 with LockFailureException

use of com.google.gerrit.git.LockFailureException in project gerrit by GerritCodeReview.

the class ChangeEditUtil method deleteRef.

private static void deleteRef(Repository repo, ChangeEdit edit) throws IOException {
    String refName = edit.getRefName();
    RefUpdate ru = repo.updateRef(refName, true);
    ru.setExpectedOldObjectId(edit.getEditCommit());
    ru.setForceUpdate(true);
    RefUpdate.Result result = ru.delete();
    switch(result) {
        case FORCED:
        case NEW:
        case NO_CHANGE:
            break;
        case LOCK_FAILURE:
            throw new LockFailureException(String.format("Failed to delete ref %s", refName), ru);
        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 IOException(String.format("Failed to delete ref %s: %s", refName, result));
    }
}
Also used : IOException(java.io.IOException) LockFailureException(com.google.gerrit.git.LockFailureException) RefUpdate(org.eclipse.jgit.lib.RefUpdate)

Example 8 with LockFailureException

use of com.google.gerrit.git.LockFailureException 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)

Example 9 with LockFailureException

use of com.google.gerrit.git.LockFailureException in project gerrit by GerritCodeReview.

the class PublicKeyStore method save.

/**
 * Save pending keys to the store.
 *
 * <p>One commit is created and the ref updated. The pending list is cleared if and only if the
 * ref update succeeds, which allows for easy retries in case of lock failure.
 *
 * @param cb commit builder with at least author and identity populated; tree and parent are
 *     ignored.
 * @return result of the ref update.
 */
public RefUpdate.Result save(CommitBuilder cb) throws PGPException, IOException {
    if (toAdd.isEmpty() && toRemove.isEmpty()) {
        return RefUpdate.Result.NO_CHANGE;
    }
    if (reader == null) {
        load();
    }
    if (notes == null) {
        notes = NoteMap.newEmptyMap();
    }
    ObjectId newTip;
    try (ObjectInserter ins = repo.newObjectInserter()) {
        for (PGPPublicKeyRing keyRing : toAdd.values()) {
            saveToNotes(ins, keyRing);
        }
        for (Fingerprint fp : toRemove) {
            deleteFromNotes(ins, fp);
        }
        cb.setTreeId(notes.writeTree(ins));
        if (cb.getTreeId().equals(tip != null ? tip.getTree() : EMPTY_TREE_ID)) {
            return RefUpdate.Result.NO_CHANGE;
        }
        if (tip != null) {
            cb.setParentId(tip);
        }
        if (cb.getMessage() == null) {
            int n = toAdd.size() + toRemove.size();
            cb.setMessage(String.format("Update %d public key%s", n, n != 1 ? "s" : ""));
        }
        newTip = ins.insert(cb);
        ins.flush();
    }
    RefUpdate ru = repo.updateRef(PublicKeyStore.REFS_GPG_KEYS);
    ru.setExpectedOldObjectId(tip);
    ru.setNewObjectId(newTip);
    ru.setRefLogIdent(cb.getCommitter());
    ru.setRefLogMessage("Store public keys", true);
    RefUpdate.Result result = ru.update();
    reset();
    switch(result) {
        case FAST_FORWARD:
        case NEW:
        case NO_CHANGE:
            toAdd.clear();
            toRemove.clear();
            break;
        case LOCK_FAILURE:
            throw new LockFailureException("Failed to store public keys", ru);
        case FORCED:
        case IO_FAILURE:
        case NOT_ATTEMPTED:
        case REJECTED:
        case REJECTED_CURRENT_BRANCH:
        case RENAMED:
        case REJECTED_MISSING_OBJECT:
        case REJECTED_OTHER_REASON:
        default:
            break;
    }
    return result;
}
Also used : PGPPublicKeyRing(org.bouncycastle.openpgp.PGPPublicKeyRing) ObjectInserter(org.eclipse.jgit.lib.ObjectInserter) ObjectId(org.eclipse.jgit.lib.ObjectId) LockFailureException(com.google.gerrit.git.LockFailureException) RefUpdate(org.eclipse.jgit.lib.RefUpdate)

Example 10 with LockFailureException

use of com.google.gerrit.git.LockFailureException in project gerrit by GerritCodeReview.

the class CreateBranch method apply.

@Override
public Response<BranchInfo> apply(ProjectResource rsrc, IdString id, BranchInput input) throws BadRequestException, AuthException, ResourceConflictException, IOException, PermissionBackendException, NoSuchProjectException {
    String ref = id.get();
    if (input == null) {
        input = new BranchInput();
    }
    if (input.ref != null && !ref.equals(input.ref)) {
        throw new BadRequestException("ref must match URL");
    }
    if (input.revision != null) {
        input.revision = input.revision.trim();
    }
    if (Strings.isNullOrEmpty(input.revision)) {
        input.revision = Constants.HEAD;
    }
    while (ref.startsWith("/")) {
        ref = ref.substring(1);
    }
    ref = RefNames.fullName(ref);
    if (!Repository.isValidRefName(ref)) {
        throw new BadRequestException("invalid branch name \"" + ref + "\"");
    }
    if (MagicBranch.isMagicBranch(ref)) {
        throw new BadRequestException("not allowed to create branches under \"" + MagicBranch.getMagicRefNamePrefix(ref) + "\"");
    }
    if (!isBranchAllowed(ref)) {
        throw new BadRequestException("Cannot create a branch with name \"" + ref + "\". Not allowed to create branches under Gerrit internal or tags refs.");
    }
    BranchNameKey name = BranchNameKey.create(rsrc.getNameKey(), ref);
    try (Repository repo = repoManager.openRepository(rsrc.getNameKey())) {
        ObjectId revid = RefUtil.parseBaseRevision(repo, rsrc.getNameKey(), input.revision);
        RevWalk rw = RefUtil.verifyConnected(repo, revid);
        RevObject object = rw.parseAny(revid);
        if (ref.startsWith(Constants.R_HEADS)) {
            // Ensure that what we start the branch from is a commit. If we
            // were given a tag, dereference to the commit instead.
            // 
            object = rw.parseCommit(object);
        }
        createRefControl.checkCreateRef(identifiedUser, repo, name, object);
        RefUpdate u = repo.updateRef(ref);
        u.setExpectedOldObjectId(ObjectId.zeroId());
        u.setNewObjectId(object.copy());
        u.setRefLogIdent(identifiedUser.get().newRefLogIdent());
        u.setRefLogMessage("created via REST from " + input.revision, false);
        refCreationValidator.validateRefOperation(rsrc.getName(), identifiedUser.get(), u, getValidateOptionsAsMultimap(input.validationOptions));
        RefUpdate.Result result = u.update(rw);
        switch(result) {
            case FAST_FORWARD:
            case NEW:
            case NO_CHANGE:
                referenceUpdated.fire(name.project(), u, ReceiveCommand.Type.CREATE, identifiedUser.get().state());
                break;
            case LOCK_FAILURE:
                if (repo.getRefDatabase().exactRef(ref) != null) {
                    throw new ResourceConflictException("branch \"" + ref + "\" already exists");
                }
                String refPrefix = RefUtil.getRefPrefix(ref);
                while (!Constants.R_HEADS.equals(refPrefix)) {
                    if (repo.getRefDatabase().exactRef(refPrefix) != null) {
                        throw new ResourceConflictException("Cannot create branch \"" + ref + "\" since it conflicts with branch \"" + refPrefix + "\".");
                    }
                    refPrefix = RefUtil.getRefPrefix(refPrefix);
                }
                throw new LockFailureException(String.format("Failed to create %s", ref), u);
            case FORCED:
            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 IOException(String.format("Failed to create %s: %s", ref, result.name()));
        }
        BranchInfo info = new BranchInfo();
        info.ref = ref;
        info.revision = revid.getName();
        if (isConfigRef(name.branch())) {
            // Never allow to delete the meta config branch.
            info.canDelete = null;
        } else {
            info.canDelete = permissionBackend.currentUser().ref(name).testOrFalse(RefPermission.DELETE) && rsrc.getProjectState().statePermitsWrite() ? true : null;
        }
        return Response.created(info);
    } catch (RefUtil.InvalidRevisionException e) {
        throw new BadRequestException("invalid revision \"" + input.revision + "\"", e);
    }
}
Also used : BranchInfo(com.google.gerrit.extensions.api.projects.BranchInfo) ObjectId(org.eclipse.jgit.lib.ObjectId) RevObject(org.eclipse.jgit.revwalk.RevObject) IdString(com.google.gerrit.extensions.restapi.IdString) IOException(java.io.IOException) RefUtil(com.google.gerrit.server.project.RefUtil) RevWalk(org.eclipse.jgit.revwalk.RevWalk) LockFailureException(com.google.gerrit.git.LockFailureException) Repository(org.eclipse.jgit.lib.Repository) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) BranchNameKey(com.google.gerrit.entities.BranchNameKey) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException) BranchInput(com.google.gerrit.extensions.api.projects.BranchInput) RefUpdate(org.eclipse.jgit.lib.RefUpdate)

Aggregations

LockFailureException (com.google.gerrit.git.LockFailureException)13 RefUpdate (org.eclipse.jgit.lib.RefUpdate)10 IOException (java.io.IOException)7 BatchRefUpdate (org.eclipse.jgit.lib.BatchRefUpdate)5 ObjectId (org.eclipse.jgit.lib.ObjectId)5 Repository (org.eclipse.jgit.lib.Repository)5 StorageException (com.google.gerrit.exceptions.StorageException)4 RevWalk (org.eclipse.jgit.revwalk.RevWalk)4 ResourceConflictException (com.google.gerrit.extensions.restapi.ResourceConflictException)3 ObjectInserter (org.eclipse.jgit.lib.ObjectInserter)3 BranchNameKey (com.google.gerrit.entities.BranchNameKey)2 ConfigInvalidException (org.eclipse.jgit.errors.ConfigInvalidException)2 Ref (org.eclipse.jgit.lib.Ref)2 RevCommit (org.eclipse.jgit.revwalk.RevCommit)2 Attempt (com.github.rholder.retry.Attempt)1 RetryListener (com.github.rholder.retry.RetryListener)1 AutoValue (com.google.auto.value.AutoValue)1 Joiner (com.google.common.base.Joiner)1 MoreObjects.firstNonNull (com.google.common.base.MoreObjects.firstNonNull)1 Preconditions.checkArgument (com.google.common.base.Preconditions.checkArgument)1