Search in sources :

Example 11 with ReviewDb

use of com.google.gerrit.reviewdb.server.ReviewDb in project gerrit by GerritCodeReview.

the class DbGroupMemberAuditListener method onAddAccountsToGroup.

@Override
public void onAddAccountsToGroup(Account.Id me, Collection<AccountGroupMember> added) {
    List<AccountGroupMemberAudit> auditInserts = new ArrayList<>();
    for (AccountGroupMember m : added) {
        AccountGroupMemberAudit audit = new AccountGroupMemberAudit(m, me, TimeUtil.nowTs());
        auditInserts.add(audit);
    }
    try (ReviewDb db = schema.open()) {
        db.accountGroupMembersAudit().insert(auditInserts);
    } catch (OrmException e) {
        logOrmExceptionForAccounts("Cannot log add accounts to group event performed by user", me, added, e);
    }
}
Also used : AccountGroupMember(com.google.gerrit.reviewdb.client.AccountGroupMember) OrmException(com.google.gwtorm.server.OrmException) AccountGroupMemberAudit(com.google.gerrit.reviewdb.client.AccountGroupMemberAudit) ArrayList(java.util.ArrayList) ReviewDb(com.google.gerrit.reviewdb.server.ReviewDb)

Example 12 with ReviewDb

use of com.google.gerrit.reviewdb.server.ReviewDb in project gerrit by GerritCodeReview.

the class ConflictsPredicate method predicates.

public static List<Predicate<ChangeData>> predicates(final Arguments args, String value, List<Change> changes) throws QueryParseException, OrmException {
    int indexTerms = 0;
    List<Predicate<ChangeData>> changePredicates = Lists.newArrayListWithCapacity(changes.size());
    final Provider<ReviewDb> db = args.db;
    for (final Change c : changes) {
        final ChangeDataCache changeDataCache = new ChangeDataCache(c, db, args.changeDataFactory, args.projectCache);
        List<String> files = listFiles(c, args, changeDataCache);
        indexTerms += 3 + files.size();
        if (indexTerms > args.indexConfig.maxTerms()) {
            // later on in the query parsing.
            throw new QueryParseException(TOO_MANY_FILES);
        }
        List<Predicate<ChangeData>> filePredicates = Lists.newArrayListWithCapacity(files.size());
        for (String file : files) {
            filePredicates.add(new EqualsPathPredicate(ChangeQueryBuilder.FIELD_PATH, file));
        }
        List<Predicate<ChangeData>> predicatesForOneChange = Lists.newArrayListWithCapacity(5);
        predicatesForOneChange.add(not(new LegacyChangeIdPredicate(c.getId())));
        predicatesForOneChange.add(new ProjectPredicate(c.getProject().get()));
        predicatesForOneChange.add(new RefPredicate(c.getDest().get()));
        predicatesForOneChange.add(or(or(filePredicates), new IsMergePredicate(args, value)));
        predicatesForOneChange.add(new ChangeOperatorPredicate(ChangeQueryBuilder.FIELD_CONFLICTS, value) {

            @Override
            public boolean match(ChangeData object) throws OrmException {
                Change otherChange = object.change();
                if (otherChange == null) {
                    return false;
                }
                if (!otherChange.getDest().equals(c.getDest())) {
                    return false;
                }
                SubmitTypeRecord str = object.submitTypeRecord();
                if (!str.isOk()) {
                    return false;
                }
                ObjectId other = ObjectId.fromString(object.currentPatchSet().getRevision().get());
                ConflictKey conflictsKey = new ConflictKey(changeDataCache.getTestAgainst(), other, str.type, changeDataCache.getProjectState().isUseContentMerge());
                Boolean conflicts = args.conflictsCache.getIfPresent(conflictsKey);
                if (conflicts != null) {
                    return conflicts;
                }
                try (Repository repo = args.repoManager.openRepository(otherChange.getProject());
                    CodeReviewRevWalk rw = CodeReviewCommit.newRevWalk(repo)) {
                    conflicts = !args.submitDryRun.run(str.type, repo, rw, otherChange.getDest(), changeDataCache.getTestAgainst(), other, getAlreadyAccepted(repo, rw));
                    args.conflictsCache.put(conflictsKey, conflicts);
                    return conflicts;
                } catch (IntegrationException | NoSuchProjectException | IOException e) {
                    throw new OrmException(e);
                }
            }

            @Override
            public int getCost() {
                return 5;
            }

            private Set<RevCommit> getAlreadyAccepted(Repository repo, RevWalk rw) throws IntegrationException {
                try {
                    Set<RevCommit> accepted = new HashSet<>();
                    SubmitDryRun.addCommits(changeDataCache.getAlreadyAccepted(repo), rw, accepted);
                    ObjectId tip = changeDataCache.getTestAgainst();
                    if (tip != null) {
                        accepted.add(rw.parseCommit(tip));
                    }
                    return accepted;
                } catch (OrmException | IOException e) {
                    throw new IntegrationException("Failed to determine already accepted commits.", e);
                }
            }
        });
        changePredicates.add(and(predicatesForOneChange));
    }
    return changePredicates;
}
Also used : HashSet(java.util.HashSet) Set(java.util.Set) OrPredicate(com.google.gerrit.server.query.OrPredicate) Predicate(com.google.gerrit.server.query.Predicate) OrmException(com.google.gwtorm.server.OrmException) ReviewDb(com.google.gerrit.reviewdb.server.ReviewDb) IntegrationException(com.google.gerrit.server.git.IntegrationException) ObjectId(org.eclipse.jgit.lib.ObjectId) CodeReviewRevWalk(com.google.gerrit.server.git.CodeReviewCommit.CodeReviewRevWalk) Change(com.google.gerrit.reviewdb.client.Change) CodeReviewRevWalk(com.google.gerrit.server.git.CodeReviewCommit.CodeReviewRevWalk) RevWalk(org.eclipse.jgit.revwalk.RevWalk) QueryParseException(com.google.gerrit.server.query.QueryParseException) Repository(org.eclipse.jgit.lib.Repository) SubmitTypeRecord(com.google.gerrit.common.data.SubmitTypeRecord)

Example 13 with ReviewDb

use of com.google.gerrit.reviewdb.server.ReviewDb in project gerrit by GerritCodeReview.

the class SchemaUpdater method update.

public void update(final UpdateUI ui) throws OrmException {
    try (ReviewDb db = ReviewDbUtil.unwrapDb(schema.open())) {
        final SchemaVersion u = updater.get();
        final CurrentSchemaVersion version = getSchemaVersion(db);
        if (version == null) {
            try {
                creator.create(db);
            } catch (IOException | ConfigInvalidException e) {
                throw new OrmException("Cannot initialize schema", e);
            }
        } else {
            try {
                u.check(ui, version, db);
            } catch (SQLException e) {
                throw new OrmException("Cannot upgrade schema", e);
            }
            updateSystemConfig(db);
        }
    }
}
Also used : CurrentSchemaVersion(com.google.gerrit.reviewdb.client.CurrentSchemaVersion) CurrentSchemaVersion(com.google.gerrit.reviewdb.client.CurrentSchemaVersion) ConfigInvalidException(org.eclipse.jgit.errors.ConfigInvalidException) OrmException(com.google.gwtorm.server.OrmException) SQLException(java.sql.SQLException) IOException(java.io.IOException) ReviewDb(com.google.gerrit.reviewdb.server.ReviewDb)

Example 14 with ReviewDb

use of com.google.gerrit.reviewdb.server.ReviewDb in project gerrit by GerritCodeReview.

the class ChangeRebuilderIT method rebuilderRespectsReadOnlyInNoteDbChangeState.

@Test
public void rebuilderRespectsReadOnlyInNoteDbChangeState() throws Exception {
    TestTimeUtil.resetWithClockStep(1, SECONDS);
    PushOneCommit.Result r = createChange();
    PatchSet.Id psId1 = r.getPatchSetId();
    Change.Id id = psId1.getParentKey();
    checker.rebuildAndCheckChanges(id);
    setNotesMigration(true, true);
    ReviewDb db = getUnwrappedDb();
    Change c = db.changes().get(id);
    NoteDbChangeState state = NoteDbChangeState.parse(c);
    Timestamp until = new Timestamp(TimeUtil.nowMs() + MILLISECONDS.convert(1, DAYS));
    state = state.withReadOnlyUntil(until);
    c.setNoteDbState(state.toString());
    db.changes().update(Collections.singleton(c));
    try {
        rebuilderWrapper.rebuild(db, id);
        assert_().fail("expected rebuild to fail");
    } catch (OrmRuntimeException e) {
        assertThat(e.getMessage()).contains("read-only until");
    }
    TestTimeUtil.setClock(new Timestamp(until.getTime() + MILLISECONDS.convert(1, SECONDS)));
    rebuilderWrapper.rebuild(db, id);
}
Also used : OrmRuntimeException(com.google.gwtorm.server.OrmRuntimeException) PatchSet(com.google.gerrit.reviewdb.client.PatchSet) Change(com.google.gerrit.reviewdb.client.Change) Timestamp(java.sql.Timestamp) PushOneCommit(com.google.gerrit.acceptance.PushOneCommit) ReviewDb(com.google.gerrit.reviewdb.server.ReviewDb) NoteDbChangeState(com.google.gerrit.server.notedb.NoteDbChangeState) AbstractDaemonTest(com.google.gerrit.acceptance.AbstractDaemonTest) Test(org.junit.Test)

Example 15 with ReviewDb

use of com.google.gerrit.reviewdb.server.ReviewDb in project gerrit by GerritCodeReview.

the class RebuildNoteDb method run.

@Override
public int run() throws Exception {
    mustHaveValidSite();
    dbInjector = createDbInjector(MULTI_USER);
    threads = ThreadLimiter.limitThreads(dbInjector, threads);
    LifecycleManager dbManager = new LifecycleManager();
    dbManager.add(dbInjector);
    dbManager.start();
    sysInjector = createSysInjector();
    sysInjector.injectMembers(this);
    if (!notesMigration.enabled()) {
        throw die("NoteDb is not enabled.");
    }
    LifecycleManager sysManager = new LifecycleManager();
    sysManager.add(sysInjector);
    sysManager.start();
    ListeningExecutorService executor = newExecutor();
    System.out.println("Rebuilding the NoteDb");
    ImmutableListMultimap<Project.NameKey, Change.Id> changesByProject = getChangesByProject();
    boolean ok;
    Stopwatch sw = Stopwatch.createStarted();
    try (Repository allUsersRepo = repoManager.openRepository(allUsersName)) {
        deleteRefs(RefNames.REFS_DRAFT_COMMENTS, allUsersRepo);
        List<ListenableFuture<Boolean>> futures = new ArrayList<>();
        List<Project.NameKey> projectNames = Ordering.usingToString().sortedCopy(changesByProject.keySet());
        for (Project.NameKey project : projectNames) {
            ListenableFuture<Boolean> future = executor.submit(() -> {
                try (ReviewDb db = unwrapDb(schemaFactory.open())) {
                    return rebuildProject(db, changesByProject, project, allUsersRepo);
                } catch (Exception e) {
                    log.error("Error rebuilding project " + project, e);
                    return false;
                }
            });
            futures.add(future);
        }
        try {
            ok = Iterables.all(Futures.allAsList(futures).get(), Predicates.equalTo(true));
        } catch (InterruptedException | ExecutionException e) {
            log.error("Error rebuilding projects", e);
            ok = false;
        }
    }
    double t = sw.elapsed(TimeUnit.MILLISECONDS) / 1000d;
    System.out.format("Rebuild %d changes in %.01fs (%.01f/s)\n", changesByProject.size(), t, changesByProject.size() / t);
    return ok ? 0 : 1;
}
Also used : LifecycleManager(com.google.gerrit.lifecycle.LifecycleManager) Stopwatch(com.google.common.base.Stopwatch) ArrayList(java.util.ArrayList) OrmException(com.google.gwtorm.server.OrmException) NoPatchSetsException(com.google.gerrit.server.notedb.rebuild.ChangeRebuilder.NoPatchSetsException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) Project(com.google.gerrit.reviewdb.client.Project) Repository(org.eclipse.jgit.lib.Repository) ListenableFuture(com.google.common.util.concurrent.ListenableFuture) ListeningExecutorService(com.google.common.util.concurrent.ListeningExecutorService) ObjectId(org.eclipse.jgit.lib.ObjectId) ExecutionException(java.util.concurrent.ExecutionException) ReviewDb(com.google.gerrit.reviewdb.server.ReviewDb)

Aggregations

ReviewDb (com.google.gerrit.reviewdb.server.ReviewDb)63 OrmException (com.google.gwtorm.server.OrmException)25 Change (com.google.gerrit.reviewdb.client.Change)21 Account (com.google.gerrit.reviewdb.client.Account)17 ArrayList (java.util.ArrayList)14 IOException (java.io.IOException)12 GitRepositoryManager (com.google.gerrit.server.git.GitRepositoryManager)10 Repository (org.eclipse.jgit.lib.Repository)9 Project (com.google.gerrit.reviewdb.client.Project)8 GerritPersonIdent (com.google.gerrit.server.GerritPersonIdent)8 Provider (com.google.inject.Provider)8 PatchSet (com.google.gerrit.reviewdb.client.PatchSet)7 Inject (com.google.inject.Inject)7 AllUsersName (com.google.gerrit.server.config.AllUsersName)6 ChangeControl (com.google.gerrit.server.project.ChangeControl)6 PersonIdent (org.eclipse.jgit.lib.PersonIdent)6 ResourceConflictException (com.google.gerrit.extensions.restapi.ResourceConflictException)5 AccountGroupMember (com.google.gerrit.reviewdb.client.AccountGroupMember)5 GerritServerConfig (com.google.gerrit.server.config.GerritServerConfig)5 GitReferenceUpdated (com.google.gerrit.server.extensions.events.GitReferenceUpdated)5