Search in sources :

Example 36 with ReviewDb

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

the class ProtobufImport method run.

@Override
public int run() throws Exception {
    mustHaveValidSite();
    Injector dbInjector = createDbInjector(SINGLE_USER);
    manager.add(dbInjector);
    manager.start();
    RuntimeShutdown.add(manager::stop);
    dbInjector.injectMembers(this);
    ProgressMonitor progress = new TextProgressMonitor();
    progress.beginTask("Importing entities", ProgressMonitor.UNKNOWN);
    try (ReviewDb db = schemaFactory.open()) {
        for (RelationModel model : new JavaSchemaModel(ReviewDb.class).getRelations()) {
            relations.put(model.getRelationID(), Relation.create(model, db));
        }
        Parser<UnknownFieldSet> parser = UnknownFieldSet.getDefaultInstance().getParserForType();
        try (InputStream in = new BufferedInputStream(Files.newInputStream(file.toPath()))) {
            UnknownFieldSet msg;
            while ((msg = parser.parseDelimitedFrom(in)) != null) {
                Map.Entry<Integer, UnknownFieldSet.Field> e = Iterables.getOnlyElement(msg.asMap().entrySet());
                Relation rel = checkNotNull(relations.get(e.getKey()), "unknown relation ID %s in message: %s", e.getKey(), msg);
                List<ByteString> values = e.getValue().getLengthDelimitedList();
                checkState(values.size() == 1, "expected one string field in message: %s", msg);
                upsert(rel, values.get(0));
                progress.update(1);
            }
        }
        progress.endTask();
    }
    return 0;
}
Also used : BufferedInputStream(java.io.BufferedInputStream) InputStream(java.io.InputStream) ByteString(com.google.protobuf.ByteString) TextProgressMonitor(org.eclipse.jgit.lib.TextProgressMonitor) ProgressMonitor(org.eclipse.jgit.lib.ProgressMonitor) TextProgressMonitor(org.eclipse.jgit.lib.TextProgressMonitor) BufferedInputStream(java.io.BufferedInputStream) Injector(com.google.inject.Injector) RelationModel(com.google.gwtorm.schema.RelationModel) UnknownFieldSet(com.google.protobuf.UnknownFieldSet) HashMap(java.util.HashMap) Map(java.util.Map) ReviewDb(com.google.gerrit.reviewdb.server.ReviewDb) JavaSchemaModel(com.google.gwtorm.schema.java.JavaSchemaModel)

Example 37 with ReviewDb

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

the class AccountResolver method findAllByNameOrEmail.

/**
   * Locate exactly one account matching the name or name/email string.
   *
   * @param db open database handle.
   * @param nameOrEmail a string of the format "Full Name &lt;email@example&gt;", just the email
   *     address ("email@example"), a full name ("Full Name").
   * @return the accounts that match, empty collection if none. Never null.
   */
public Set<Account.Id> findAllByNameOrEmail(ReviewDb db, String nameOrEmail) throws OrmException {
    int lt = nameOrEmail.indexOf('<');
    int gt = nameOrEmail.indexOf('>');
    if (lt >= 0 && gt > lt && nameOrEmail.contains("@")) {
        Set<Account.Id> ids = byEmail.get(nameOrEmail.substring(lt + 1, gt));
        if (ids.isEmpty() || ids.size() == 1) {
            return ids;
        }
        // more than one match, try to return the best one
        String name = nameOrEmail.substring(0, lt - 1);
        Set<Account.Id> nameMatches = new HashSet<>();
        for (Account.Id id : ids) {
            Account a = byId.get(id).getAccount();
            if (name.equals(a.getFullName())) {
                nameMatches.add(id);
            }
        }
        return nameMatches.isEmpty() ? ids : nameMatches;
    }
    if (nameOrEmail.contains("@")) {
        return byEmail.get(nameOrEmail);
    }
    Account.Id id = realm.lookup(nameOrEmail);
    if (id != null) {
        return Collections.singleton(id);
    }
    List<AccountState> m = accountQueryProvider.get().byFullName(nameOrEmail);
    if (m.size() == 1) {
        return Collections.singleton(m.get(0).getAccount().getId());
    }
    // and pray we come up with a reasonable result list.
    return accountQueryProvider.get().byDefault(nameOrEmail).stream().map(a -> a.getAccount().getId()).collect(toSet());
}
Also used : ReviewDb(com.google.gerrit.reviewdb.server.ReviewDb) OrmException(com.google.gwtorm.server.OrmException) InternalAccountQuery(com.google.gerrit.server.query.account.InternalAccountQuery) Inject(com.google.inject.Inject) Set(java.util.Set) HashSet(java.util.HashSet) Provider(com.google.inject.Provider) List(java.util.List) Matcher(java.util.regex.Matcher) Account(com.google.gerrit.reviewdb.client.Account) Pattern(java.util.regex.Pattern) Collections(java.util.Collections) Collectors.toSet(java.util.stream.Collectors.toSet) Singleton(com.google.inject.Singleton) Account(com.google.gerrit.reviewdb.client.Account) HashSet(java.util.HashSet)

Example 38 with ReviewDb

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

the class InitAdminUser method postRun.

@Override
public void postRun() throws Exception {
    AuthType authType = flags.cfg.getEnum(AuthType.values(), "auth", null, "type", null);
    if (authType != AuthType.DEVELOPMENT_BECOME_ANY_ACCOUNT) {
        return;
    }
    try (ReviewDb db = dbFactory.open()) {
        if (db.accounts().anyAccounts().toList().isEmpty()) {
            ui.header("Gerrit Administrator");
            if (ui.yesno(true, "Create administrator user")) {
                Account.Id id = new Account.Id(db.nextAccountId());
                String username = ui.readString("admin", "username");
                String name = ui.readString("Administrator", "name");
                String httpPassword = ui.readString("secret", "HTTP password");
                AccountSshKey sshKey = readSshKey(id);
                String email = readEmail(sshKey);
                List<ExternalId> extIds = new ArrayList<>(2);
                extIds.add(ExternalId.createUsername(username, id, httpPassword));
                if (email != null) {
                    extIds.add(ExternalId.createEmail(id, email));
                }
                externalIds.insert("Add external IDs for initial admin user", extIds);
                Account a = new Account(id, TimeUtil.nowTs());
                a.setFullName(name);
                a.setPreferredEmail(email);
                accounts.insert(db, a);
                AccountGroupName adminGroupName = db.accountGroupNames().get(new AccountGroup.NameKey("Administrators"));
                AccountGroupMember m = new AccountGroupMember(new AccountGroupMember.Key(id, adminGroupName.getId()));
                db.accountGroupMembers().insert(Collections.singleton(m));
                if (sshKey != null) {
                    VersionedAuthorizedKeysOnInit authorizedKeys = authorizedKeysFactory.create(id).load();
                    authorizedKeys.addKey(sshKey.getSshPublicKey());
                    authorizedKeys.save("Add SSH key for initial admin user\n");
                }
                AccountGroup adminGroup = db.accountGroups().get(adminGroupName.getId());
                AccountState as = new AccountState(a, Collections.singleton(adminGroup.getGroupUUID()), extIds, new HashMap<>());
                for (AccountIndex accountIndex : indexCollection.getWriteIndexes()) {
                    accountIndex.replace(as);
                }
            }
        }
    }
}
Also used : Account(com.google.gerrit.reviewdb.client.Account) AccountGroupName(com.google.gerrit.reviewdb.client.AccountGroupName) AccountGroupMember(com.google.gerrit.reviewdb.client.AccountGroupMember) AccountIndex(com.google.gerrit.server.index.account.AccountIndex) AccountSshKey(com.google.gerrit.reviewdb.client.AccountSshKey) ExternalId(com.google.gerrit.server.account.externalids.ExternalId) ArrayList(java.util.ArrayList) AccountState(com.google.gerrit.server.account.AccountState) AccountGroup(com.google.gerrit.reviewdb.client.AccountGroup) AuthType(com.google.gerrit.extensions.client.AuthType) ExternalId(com.google.gerrit.server.account.externalids.ExternalId) ReviewDb(com.google.gerrit.reviewdb.server.ReviewDb)

Example 39 with ReviewDb

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

the class DeleteReviewerOp method approvals.

private Iterable<PatchSetApproval> approvals(ChangeContext ctx, Account.Id accountId) throws OrmException {
    Change.Id changeId = ctx.getNotes().getChangeId();
    Iterable<PatchSetApproval> approvals;
    PrimaryStorage r = PrimaryStorage.of(ctx.getChange());
    if (migration.readChanges() && r == PrimaryStorage.REVIEW_DB) {
        // Because NoteDb and ReviewDb have different semantics for zero-value
        // approvals, we must fall back to ReviewDb as the source of truth here.
        ReviewDb db = ctx.getDb();
        if (db instanceof BatchUpdateReviewDb) {
            db = ((BatchUpdateReviewDb) db).unsafeGetDelegate();
        }
        db = ReviewDbUtil.unwrapDb(db);
        approvals = db.patchSetApprovals().byChange(changeId);
    } else {
        approvals = approvalsUtil.byChange(ctx.getDb(), ctx.getNotes()).values();
    }
    return Iterables.filter(approvals, psa -> accountId.equals(psa.getAccountId()));
}
Also used : PrimaryStorage(com.google.gerrit.server.notedb.NoteDbChangeState.PrimaryStorage) BatchUpdateReviewDb(com.google.gerrit.server.update.BatchUpdateReviewDb) Change(com.google.gerrit.reviewdb.client.Change) PatchSetApproval(com.google.gerrit.reviewdb.client.PatchSetApproval) ReviewDb(com.google.gerrit.reviewdb.server.ReviewDb) BatchUpdateReviewDb(com.google.gerrit.server.update.BatchUpdateReviewDb)

Example 40 with ReviewDb

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

the class GetRevisionActions method getETag.

@Override
public String getETag(RevisionResource rsrc) {
    Hasher h = Hashing.md5().newHasher();
    CurrentUser user = rsrc.getControl().getUser();
    try {
        rsrc.getChangeResource().prepareETag(h, user);
        h.putBoolean(Submit.wholeTopicEnabled(config));
        ReviewDb db = dbProvider.get();
        ChangeSet cs = mergeSuperSet.get().completeChangeSet(db, rsrc.getChange(), user);
        for (ChangeData cd : cs.changes()) {
            changeResourceFactory.create(cd.changeControl()).prepareETag(h, user);
        }
        h.putBoolean(cs.furtherHiddenChanges());
    } catch (IOException | OrmException e) {
        throw new OrmRuntimeException(e);
    }
    return h.hash().toString();
}
Also used : Hasher(com.google.common.hash.Hasher) OrmRuntimeException(com.google.gwtorm.server.OrmRuntimeException) CurrentUser(com.google.gerrit.server.CurrentUser) OrmException(com.google.gwtorm.server.OrmException) IOException(java.io.IOException) ChangeSet(com.google.gerrit.server.git.ChangeSet) ChangeData(com.google.gerrit.server.query.change.ChangeData) 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