Search in sources :

Example 6 with FieldBundle

use of com.google.gerrit.index.query.FieldBundle in project gerrit by GerritCodeReview.

the class StalenessChecker method check.

/**
 * Returns a {@link StalenessCheckResult} with structured information about staleness of the
 * provided {@link com.google.gerrit.entities.Project.NameKey}.
 */
public StalenessCheckResult check(Project.NameKey project) {
    ProjectData projectData = projectCache.get(project).orElseThrow(illegalState(project)).toProjectData();
    ProjectIndex i = indexes.getSearchIndex();
    if (i == null) {
        return StalenessCheckResult.notStale();
    }
    Optional<FieldBundle> result = i.getRaw(project, QueryOptions.create(indexConfig, 0, 1, FIELDS));
    if (!result.isPresent()) {
        return StalenessCheckResult.stale("Document %s missing from index", project);
    }
    SetMultimap<Project.NameKey, RefState> indexedRefStates = RefState.parseStates(result.get().getValue(ProjectField.REF_STATE));
    SetMultimap<Project.NameKey, RefState> currentRefStates = MultimapBuilder.hashKeys().hashSetValues().build();
    projectData.tree().stream().filter(p -> p.getProject().getConfigRefState() != null).forEach(p -> currentRefStates.put(p.getProject().getNameKey(), RefState.create(RefNames.REFS_CONFIG, p.getProject().getConfigRefState())));
    if (currentRefStates.equals(indexedRefStates)) {
        return StalenessCheckResult.notStale();
    }
    return StalenessCheckResult.stale("Document has unexpected ref states (%s != %s)", currentRefStates, indexedRefStates);
}
Also used : RefState(com.google.gerrit.index.RefState) ProjectCache.illegalState(com.google.gerrit.server.project.ProjectCache.illegalState) ImmutableSet(com.google.common.collect.ImmutableSet) IndexConfig(com.google.gerrit.index.IndexConfig) ProjectCache(com.google.gerrit.server.project.ProjectCache) MultimapBuilder(com.google.common.collect.MultimapBuilder) ProjectField(com.google.gerrit.index.project.ProjectField) Inject(com.google.inject.Inject) QueryOptions(com.google.gerrit.index.QueryOptions) ProjectData(com.google.gerrit.index.project.ProjectData) SetMultimap(com.google.common.collect.SetMultimap) StalenessCheckResult(com.google.gerrit.server.index.StalenessCheckResult) ProjectIndex(com.google.gerrit.index.project.ProjectIndex) ProjectIndexCollection(com.google.gerrit.index.project.ProjectIndexCollection) Project(com.google.gerrit.entities.Project) RefNames(com.google.gerrit.entities.RefNames) FieldBundle(com.google.gerrit.index.query.FieldBundle) Optional(java.util.Optional) RefState(com.google.gerrit.index.RefState) FieldBundle(com.google.gerrit.index.query.FieldBundle) ProjectIndex(com.google.gerrit.index.project.ProjectIndex) ProjectData(com.google.gerrit.index.project.ProjectData)

Example 7 with FieldBundle

use of com.google.gerrit.index.query.FieldBundle in project gerrit by GerritCodeReview.

the class ReviewersUtil method suggestAccounts.

private List<Account.Id> suggestAccounts(SuggestReviewers suggestReviewers) throws BadRequestException {
    try (Timer0.Context ctx = metrics.queryAccountsLatency.start()) {
        // For performance reasons we don't use AccountQueryProvider as it would always load the
        // complete account from the cache (or worse, from NoteDb) even though we only need the ID
        // which we can directly get from the returned results.
        Predicate<AccountState> pred = Predicate.and(AccountPredicates.isActive(), accountQueryBuilder.defaultQuery(suggestReviewers.getQuery()));
        logger.atFine().log("accounts index query: %s", pred);
        accountIndexRewriter.validateMaxTermsInQuery(pred);
        boolean useLegacyNumericFields = accountIndexes.getSearchIndex().getSchema().useLegacyNumericFields();
        FieldDef<AccountState, ?> idField = useLegacyNumericFields ? AccountField.ID : AccountField.ID_STR;
        ResultSet<FieldBundle> result = accountIndexes.getSearchIndex().getSource(pred, QueryOptions.create(indexConfig, 0, suggestReviewers.getLimit(), ImmutableSet.of(idField.getName()))).readRaw();
        List<Account.Id> matches = result.toList().stream().map(f -> fromIdField(f, useLegacyNumericFields)).collect(toList());
        logger.atFine().log("Matches: %s", matches);
        return matches;
    } catch (TooManyTermsInQueryException e) {
        throw new BadRequestException(e.getMessage());
    } catch (QueryParseException e) {
        logger.atWarning().withCause(e).log("Suggesting accounts failed, return empty result.");
        return ImmutableList.of();
    } catch (StorageException e) {
        if (e.getCause() instanceof TooManyTermsInQueryException) {
            throw new BadRequestException(e.getMessage());
        }
        if (e.getCause() instanceof QueryParseException) {
            return ImmutableList.of();
        }
        throw e;
    }
}
Also used : GroupBackend(com.google.gerrit.server.account.GroupBackend) Inject(com.google.inject.Inject) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException) ReviewerModifier(com.google.gerrit.server.change.ReviewerModifier) EnumSet(java.util.EnumSet) FieldDef(com.google.gerrit.index.FieldDef) ImmutableSet(com.google.common.collect.ImmutableSet) GroupBaseInfo(com.google.gerrit.extensions.common.GroupBaseInfo) Timer0(com.google.gerrit.metrics.Timer0) Account(com.google.gerrit.entities.Account) FillOptions(com.google.gerrit.server.account.AccountDirectory.FillOptions) AccountQueryBuilder(com.google.gerrit.server.query.account.AccountQueryBuilder) Set(java.util.Set) AccountIndexCollection(com.google.gerrit.server.index.account.AccountIndexCollection) Sets(com.google.common.collect.Sets) GroupReference(com.google.gerrit.entities.GroupReference) Objects(java.util.Objects) TooManyTermsInQueryException(com.google.gerrit.index.query.TooManyTermsInQueryException) List(java.util.List) Nullable(com.google.gerrit.common.Nullable) Url(com.google.gerrit.extensions.restapi.Url) MetricMaker(com.google.gerrit.metrics.MetricMaker) LazyArgs.lazy(com.google.common.flogger.LazyArgs.lazy) FluentLogger(com.google.common.flogger.FluentLogger) Singleton(com.google.inject.Singleton) AccountLoader(com.google.gerrit.server.account.AccountLoader) PermissionBackendException(com.google.gerrit.server.permissions.PermissionBackendException) IndexConfig(com.google.gerrit.index.IndexConfig) ConfigInvalidException(org.eclipse.jgit.errors.ConfigInvalidException) ReviewerState(com.google.gerrit.extensions.client.ReviewerState) ResultSet(com.google.gerrit.index.query.ResultSet) AccountPredicates(com.google.gerrit.server.query.account.AccountPredicates) GroupMembers(com.google.gerrit.server.account.GroupMembers) ArrayList(java.util.ArrayList) Strings(com.google.common.base.Strings) ImmutableList(com.google.common.collect.ImmutableList) QueryParseException(com.google.gerrit.index.query.QueryParseException) Description(com.google.gerrit.metrics.Description) FieldBundle(com.google.gerrit.index.query.FieldBundle) AccountIndexRewriter(com.google.gerrit.server.index.account.AccountIndexRewriter) Predicate(com.google.gerrit.index.query.Predicate) SuggestedReviewerInfo(com.google.gerrit.extensions.common.SuggestedReviewerInfo) AccountControl(com.google.gerrit.server.account.AccountControl) CurrentUser(com.google.gerrit.server.CurrentUser) AccountField(com.google.gerrit.server.index.account.AccountField) StorageException(com.google.gerrit.exceptions.StorageException) Units(com.google.gerrit.metrics.Description.Units) ProjectState(com.google.gerrit.server.project.ProjectState) QueryOptions(com.google.gerrit.index.QueryOptions) NoSuchProjectException(com.google.gerrit.server.project.NoSuchProjectException) ChangeNotes(com.google.gerrit.server.notedb.ChangeNotes) IOException(java.io.IOException) Collectors.toList(java.util.stream.Collectors.toList) Provider(com.google.inject.Provider) Project(com.google.gerrit.entities.Project) AccountState(com.google.gerrit.server.account.AccountState) ServiceUserClassifier(com.google.gerrit.server.account.ServiceUserClassifier) Collections(java.util.Collections) TooManyTermsInQueryException(com.google.gerrit.index.query.TooManyTermsInQueryException) FieldBundle(com.google.gerrit.index.query.FieldBundle) AccountState(com.google.gerrit.server.account.AccountState) QueryParseException(com.google.gerrit.index.query.QueryParseException) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException) Timer0(com.google.gerrit.metrics.Timer0) StorageException(com.google.gerrit.exceptions.StorageException)

Example 8 with FieldBundle

use of com.google.gerrit.index.query.FieldBundle in project gerrit by GerritCodeReview.

the class Index method getRaw.

/**
 * Get a single raw document from the index.
 *
 * @param key document key.
 * @param opts query options. Options that do not make sense in the context of a single document,
 *     such as start, will be ignored.
 * @return an abstraction of a raw index document to retrieve fields from.
 */
default Optional<FieldBundle> getRaw(K key, QueryOptions opts) {
    opts = opts.withStart(0).withLimit(2);
    ImmutableList<FieldBundle> results;
    try {
        results = getSource(keyPredicate(key), opts).readRaw().toList();
    } catch (QueryParseException e) {
        throw new StorageException("Unexpected QueryParseException during get()", e);
    }
    if (results.size() > 1) {
        throw new StorageException("Multiple results found in index for key " + key + ": " + results);
    }
    return results.stream().findFirst();
}
Also used : FieldBundle(com.google.gerrit.index.query.FieldBundle) StorageException(com.google.gerrit.exceptions.StorageException) QueryParseException(com.google.gerrit.index.query.QueryParseException)

Example 9 with FieldBundle

use of com.google.gerrit.index.query.FieldBundle in project gerrit by GerritCodeReview.

the class ProjectIndexerIT method indexProject_indexesRefStateOfProjectAndParents.

@Test
public void indexProject_indexesRefStateOfProjectAndParents() throws Exception {
    projectIndexer.index(project);
    ProjectIndex i = indexes.getSearchIndex();
    assertThat(i.getSchema().hasField(ProjectField.REF_STATE)).isTrue();
    Optional<FieldBundle> result = i.getRaw(project, QueryOptions.create(indexConfig, 0, 1, FIELDS));
    assertThat(result).isPresent();
    Iterable<byte[]> refState = result.get().getValue(ProjectField.REF_STATE);
    assertThat(refState).isNotEmpty();
    Map<Project.NameKey, Collection<RefState>> states = RefState.parseStates(refState).asMap();
    fetch(testRepo, "refs/meta/config:refs/meta/config");
    Ref projectConfigRef = testRepo.getRepository().exactRef("refs/meta/config");
    TestRepository<InMemoryRepository> allProjectsRepo = cloneProject(allProjects, admin);
    fetch(allProjectsRepo, "refs/meta/config:refs/meta/config");
    Ref allProjectConfigRef = allProjectsRepo.getRepository().exactRef("refs/meta/config");
    assertThat(states).containsExactly(project, ImmutableSet.of(RefState.of(projectConfigRef)), allProjects, ImmutableSet.of(RefState.of(allProjectConfigRef)));
}
Also used : Ref(org.eclipse.jgit.lib.Ref) InMemoryRepository(org.eclipse.jgit.internal.storage.dfs.InMemoryRepository) FieldBundle(com.google.gerrit.index.query.FieldBundle) Collection(java.util.Collection) ProjectIndexCollection(com.google.gerrit.index.project.ProjectIndexCollection) ProjectIndex(com.google.gerrit.index.project.ProjectIndex) Test(org.junit.Test) AbstractDaemonTest(com.google.gerrit.acceptance.AbstractDaemonTest)

Example 10 with FieldBundle

use of com.google.gerrit.index.query.FieldBundle in project gerrit by GerritCodeReview.

the class AbstractLuceneIndex method toFieldBundle.

protected FieldBundle toFieldBundle(Document doc) {
    Map<String, FieldDef<V, ?>> allFields = getSchema().getFields();
    ListMultimap<String, Object> rawFields = ArrayListMultimap.create();
    for (IndexableField field : doc.getFields()) {
        checkArgument(allFields.containsKey(field.name()), "Unrecognized field " + field.name());
        FieldType<?> type = allFields.get(field.name()).getType();
        if (type == FieldType.EXACT || type == FieldType.FULL_TEXT || type == FieldType.PREFIX) {
            rawFields.put(field.name(), field.stringValue());
        } else if (type == FieldType.INTEGER || type == FieldType.INTEGER_RANGE) {
            rawFields.put(field.name(), field.numericValue().intValue());
        } else if (type == FieldType.LONG) {
            rawFields.put(field.name(), field.numericValue().longValue());
        } else if (type == FieldType.TIMESTAMP) {
            rawFields.put(field.name(), new Timestamp(field.numericValue().longValue()));
        } else if (type == FieldType.STORED_ONLY) {
            rawFields.put(field.name(), field.binaryValue().bytes);
        } else {
            throw FieldType.badFieldType(type);
        }
    }
    return new FieldBundle(rawFields);
}
Also used : IndexableField(org.apache.lucene.index.IndexableField) FieldDef(com.google.gerrit.index.FieldDef) FieldBundle(com.google.gerrit.index.query.FieldBundle) Timestamp(java.sql.Timestamp)

Aggregations

FieldBundle (com.google.gerrit.index.query.FieldBundle)10 Project (com.google.gerrit.entities.Project)4 FieldDef (com.google.gerrit.index.FieldDef)3 QueryOptions (com.google.gerrit.index.QueryOptions)3 ProjectIndex (com.google.gerrit.index.project.ProjectIndex)3 ImmutableList (com.google.common.collect.ImmutableList)2 ImmutableSet (com.google.common.collect.ImmutableSet)2 Account (com.google.gerrit.entities.Account)2 AccountGroup (com.google.gerrit.entities.AccountGroup)2 StorageException (com.google.gerrit.exceptions.StorageException)2 IndexConfig (com.google.gerrit.index.IndexConfig)2 RefState (com.google.gerrit.index.RefState)2 ProjectData (com.google.gerrit.index.project.ProjectData)2 ProjectIndexCollection (com.google.gerrit.index.project.ProjectIndexCollection)2 Predicate (com.google.gerrit.index.query.Predicate)2 QueryParseException (com.google.gerrit.index.query.QueryParseException)2 ResultSet (com.google.gerrit.index.query.ResultSet)2 AccountState (com.google.gerrit.server.account.AccountState)2 ExternalId (com.google.gerrit.server.account.externalids.ExternalId)2 Inject (com.google.inject.Inject)2