Search in sources :

Example 61 with StructuredRow

use of io.cdap.cdap.spi.data.StructuredRow in project cdap by cdapio.

the class SystemAppTestBaseTest method testTableOperations.

@Test
public void testTableOperations() throws Exception {
    StructuredTableAdmin tableAdmin = getStructuredTableAdmin();
    StructuredTableId id = new StructuredTableId("t0");
    Assert.assertFalse(tableAdmin.exists(id));
    String keyCol = "key";
    String valCol = "val";
    tableAdmin.create(new StructuredTableSpecification.Builder().withId(id).withFields(new FieldType(keyCol, FieldType.Type.STRING), new FieldType(valCol, FieldType.Type.STRING)).withPrimaryKeys(keyCol).build());
    try {
        TransactionRunner transactionRunner = getTransactionRunner();
        String key = "k0";
        String val = "v0";
        transactionRunner.run(context -> {
            StructuredTable table = context.getTable(id);
            List<Field<?>> fields = new ArrayList<>();
            fields.add(Fields.stringField(keyCol, key));
            Optional<StructuredRow> row = table.read(fields);
            Assert.assertFalse(row.isPresent());
            fields.add(Fields.stringField(valCol, val));
            table.upsert(fields);
        });
        transactionRunner.run(context -> {
            StructuredTable table = context.getTable(id);
            List<Field<?>> keyField = Collections.singletonList(Fields.stringField(keyCol, key));
            Optional<StructuredRow> row = table.read(keyField);
            Assert.assertTrue(row.isPresent());
            Assert.assertEquals(val, row.get().getString(valCol));
        });
    } finally {
        tableAdmin.drop(id);
    }
}
Also used : StructuredTable(io.cdap.cdap.spi.data.StructuredTable) StructuredTableAdmin(io.cdap.cdap.spi.data.StructuredTableAdmin) ArrayList(java.util.ArrayList) StructuredRow(io.cdap.cdap.spi.data.StructuredRow) FieldType(io.cdap.cdap.spi.data.table.field.FieldType) Field(io.cdap.cdap.spi.data.table.field.Field) TransactionRunner(io.cdap.cdap.spi.data.transaction.TransactionRunner) StructuredTableId(io.cdap.cdap.spi.data.table.StructuredTableId) StructuredTableSpecification(io.cdap.cdap.spi.data.table.StructuredTableSpecification) Test(org.junit.Test)

Example 62 with StructuredRow

use of io.cdap.cdap.spi.data.StructuredRow in project cdap by cdapio.

the class FileMetadataCleaner method scanFilesToDelete.

@Nullable
@SuppressWarnings("ConstantConditions")
private Range scanFilesToDelete(StructuredTable table, int fileCleanupBatchSize, long tillTime, List<DeletedEntry> toDelete, AtomicReference<Range> range) throws IOException {
    try (CloseableIterator<StructuredRow> iter = table.scan(range.get(), fileCleanupBatchSize)) {
        while (iter.hasNext()) {
            if (toDelete.size() >= fileCleanupBatchSize) {
                return null;
            }
            StructuredRow row = iter.next();
            long creationTime = row.getLong(StoreDefinition.LogFileMetaStore.CREATION_TIME_FIELD);
            if (creationTime <= tillTime) {
                // expired - can be deleted
                toDelete.add(new DeletedEntry(row.getString(StoreDefinition.LogFileMetaStore.LOGGING_CONTEXT_FIELD), row.getLong(StoreDefinition.LogFileMetaStore.EVENT_TIME_FIELD), row.getLong(StoreDefinition.LogFileMetaStore.CREATION_TIME_FIELD), row.getString(StoreDefinition.LogFileMetaStore.FILE_FIELD)));
            } else {
                // return range to skip this logging context and move to next one.
                return Range.from(ImmutableList.of(Fields.stringField(StoreDefinition.LogFileMetaStore.LOGGING_CONTEXT_FIELD, row.getString(StoreDefinition.LogFileMetaStore.LOGGING_CONTEXT_FIELD))), Range.Bound.EXCLUSIVE);
            }
        }
        // if there are no more files to delete, return next range as null.
        return null;
    }
}
Also used : StructuredRow(io.cdap.cdap.spi.data.StructuredRow) Nullable(javax.annotation.Nullable)

Example 63 with StructuredRow

use of io.cdap.cdap.spi.data.StructuredRow in project cdap by cdapio.

the class AppMetadataStore method getActiveRuns.

/**
 * Get active runs for the given programs. Active runs means program run with status STARTING, PENDING,
 * RUNNING or SUSPENDED.
 *
 * @param ids set of program ids to fetch for active run records
 * @return a map from {@link ProgramId} to a {@link Collection} of {@link RunRecordDetail}. It is guaranteed to have
 *         an entry for each of the given program id.
 * @throws IOException if failed to fetch the run records.
 */
public Map<ProgramId, Collection<RunRecordDetail>> getActiveRuns(Collection<ProgramId> ids) throws IOException {
    Collection<Range> ranges = new ArrayList<>();
    Map<ProgramId, Collection<RunRecordDetail>> result = new LinkedHashMap<>();
    for (ProgramId programId : ids) {
        ranges.add(Range.singleton(getRunRecordProgramPrefix(TYPE_RUN_RECORD_ACTIVE, programId)));
        result.put(programId, new LinkedHashSet<>());
    }
    try (CloseableIterator<StructuredRow> iterator = getRunRecordsTable().multiScan(ranges, Integer.MAX_VALUE)) {
        while (iterator.hasNext()) {
            StructuredRow row = iterator.next();
            RunRecordDetail meta = deserializeRunRecordMeta(row);
            result.get(meta.getProgramRunId().getParent()).add(meta);
        }
    }
    return result;
}
Also used : ArrayList(java.util.ArrayList) StructuredRow(io.cdap.cdap.spi.data.StructuredRow) Collection(java.util.Collection) Range(io.cdap.cdap.spi.data.table.field.Range) ProgramId(io.cdap.cdap.proto.id.ProgramId) LinkedHashMap(java.util.LinkedHashMap)

Example 64 with StructuredRow

use of io.cdap.cdap.spi.data.StructuredRow in project cdap by cdapio.

the class AppMetadataStore method scanActiveRuns.

/**
 * Scans active runs, starting from the given cursor.
 *
 * @param cursor the cursor to start the scan. A cursor can be obtained
 *               from the call to the given {@link BiConsumer} for some previous scan, or use
 *               {@link Cursor#EMPTY} to start a scan at the beginning.
 * @param limit maximum number of records to scan
 * @param consumer a {@link BiConsumer} to consume the scan result
 * @throws IOException if failed to query the storage
 */
public void scanActiveRuns(Cursor cursor, int limit, BiConsumer<Cursor, RunRecordDetail> consumer) throws IOException {
    Collection<Field<?>> begin = cursor.fields;
    if (begin.isEmpty()) {
        begin = getRunRecordStatusPrefix(TYPE_RUN_RECORD_ACTIVE);
    }
    Range range = Range.create(begin, cursor.bound, getRunRecordStatusPrefix(TYPE_RUN_RECORD_ACTIVE), Range.Bound.INCLUSIVE);
    StructuredTable table = getRunRecordsTable();
    try (CloseableIterator<StructuredRow> iterator = table.scan(range, limit)) {
        while (iterator.hasNext()) {
            StructuredRow row = iterator.next();
            consumer.accept(new Cursor(row.getPrimaryKeys(), Range.Bound.EXCLUSIVE), deserializeRunRecordMeta(row));
        }
    }
}
Also used : Field(io.cdap.cdap.spi.data.table.field.Field) StructuredTable(io.cdap.cdap.spi.data.StructuredTable) StructuredRow(io.cdap.cdap.spi.data.StructuredRow) Range(io.cdap.cdap.spi.data.table.field.Range)

Example 65 with StructuredRow

use of io.cdap.cdap.spi.data.StructuredRow in project cdap by cdapio.

the class AppMetadataStore method getProgramRunCounts.

/**
 * Get the run counts of the given program collections.
 *
 * @param programIds the collection of program ids to get the program
 * @return the map of the program id to its run count
 */
public Map<ProgramId, Long> getProgramRunCounts(Collection<ProgramId> programIds) throws BadRequestException, IOException {
    if (programIds.size() > 100) {
        throw new BadRequestException(String.format("%d programs found, the maximum number supported is 100", programIds.size()));
    }
    Map<ProgramId, Long> result = programIds.stream().collect(Collectors.toMap(id -> id, id -> 0L, (v1, v2) -> 0L, LinkedHashMap::new));
    List<List<Field<?>>> multiKeys = programIds.stream().map(id -> getProgramCountPrimaryKeys(TYPE_COUNT, id)).collect(Collectors.toList());
    for (StructuredRow row : getProgramCountsTable().multiRead(multiKeys)) {
        ProgramId programId = getApplicationIdFromRow(row).program(ProgramType.valueOf(row.getString(StoreDefinition.AppMetadataStore.PROGRAM_TYPE_FIELD)), row.getString(StoreDefinition.AppMetadataStore.PROGRAM_FIELD));
        result.put(programId, row.getLong(StoreDefinition.AppMetadataStore.COUNTS));
    }
    return result;
}
Also used : Arrays(java.util.Arrays) NamespaceId(io.cdap.cdap.proto.id.NamespaceId) StructuredRow(io.cdap.cdap.spi.data.StructuredRow) BiFunction(java.util.function.BiFunction) LoggerFactory(org.slf4j.LoggerFactory) Bytes(io.cdap.cdap.api.common.Bytes) Fields(io.cdap.cdap.spi.data.table.field.Fields) GsonBuilder(com.google.gson.GsonBuilder) ProgramRunCluster(io.cdap.cdap.proto.ProgramRunCluster) ScanApplicationsRequest(io.cdap.cdap.app.store.ScanApplicationsRequest) DatasetId(io.cdap.cdap.proto.id.DatasetId) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Gson(com.google.gson.Gson) Map(java.util.Map) Field(io.cdap.cdap.spi.data.table.field.Field) RunId(org.apache.twill.api.RunId) BasicWorkflowToken(io.cdap.cdap.internal.app.runtime.workflow.BasicWorkflowToken) SortOrder(io.cdap.cdap.spi.data.SortOrder) BasicThrowable(io.cdap.cdap.proto.BasicThrowable) StoreDefinition(io.cdap.cdap.store.StoreDefinition) ImmutableMap(com.google.common.collect.ImmutableMap) Predicate(java.util.function.Predicate) Collection(java.util.Collection) ApplicationSpecification(io.cdap.cdap.api.app.ApplicationSpecification) Set(java.util.Set) ProgramRunStatus(io.cdap.cdap.proto.ProgramRunStatus) StructuredTableContext(io.cdap.cdap.spi.data.StructuredTableContext) Collectors(java.util.stream.Collectors) Sets(com.google.common.collect.Sets) ApplicationSpecificationAdapter(io.cdap.cdap.internal.app.ApplicationSpecificationAdapter) Objects(java.util.Objects) AbstractCloseableIterator(io.cdap.cdap.api.dataset.lib.AbstractCloseableIterator) List(java.util.List) Type(java.lang.reflect.Type) Optional(java.util.Optional) Constants(io.cdap.cdap.common.conf.Constants) ProfileId(io.cdap.cdap.proto.id.ProfileId) ProgramOptionConstants(io.cdap.cdap.internal.app.runtime.ProgramOptionConstants) ApplicationId(io.cdap.cdap.proto.id.ApplicationId) HashMap(java.util.HashMap) TypeToken(com.google.common.reflect.TypeToken) ProgramType(io.cdap.cdap.proto.ProgramType) Function(java.util.function.Function) JsonReader(com.google.gson.stream.JsonReader) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) LinkedHashMap(java.util.LinkedHashMap) WorkflowToken(io.cdap.cdap.api.workflow.WorkflowToken) ProgramRunId(io.cdap.cdap.proto.id.ProgramRunId) ImmutableList(com.google.common.collect.ImmutableList) BiConsumer(java.util.function.BiConsumer) SystemArguments(io.cdap.cdap.internal.app.runtime.SystemArguments) LinkedHashSet(java.util.LinkedHashSet) Nullable(javax.annotation.Nullable) WorkflowNodeStateDetail(io.cdap.cdap.proto.WorkflowNodeStateDetail) Logger(org.slf4j.Logger) RunIds(io.cdap.cdap.common.app.RunIds) ApplicationFilter(io.cdap.cdap.app.store.ApplicationFilter) ProgramId(io.cdap.cdap.proto.id.ProgramId) IOException(java.io.IOException) BadRequestException(io.cdap.cdap.common.BadRequestException) CloseableIterator(io.cdap.cdap.api.dataset.lib.CloseableIterator) ProgramRunClusterStatus(io.cdap.cdap.proto.ProgramRunClusterStatus) TableNotFoundException(io.cdap.cdap.spi.data.TableNotFoundException) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) JsonToken(com.google.gson.stream.JsonToken) StringReader(java.io.StringReader) StructuredTable(io.cdap.cdap.spi.data.StructuredTable) Range(io.cdap.cdap.spi.data.table.field.Range) Preconditions(com.google.common.base.Preconditions) VisibleForTesting(com.google.common.annotations.VisibleForTesting) Collections(java.util.Collections) ArtifactId(io.cdap.cdap.api.artifact.ArtifactId) StructuredRow(io.cdap.cdap.spi.data.StructuredRow) BadRequestException(io.cdap.cdap.common.BadRequestException) List(java.util.List) ArrayList(java.util.ArrayList) ImmutableList(com.google.common.collect.ImmutableList) ProgramId(io.cdap.cdap.proto.id.ProgramId)

Aggregations

StructuredRow (io.cdap.cdap.spi.data.StructuredRow)142 StructuredTable (io.cdap.cdap.spi.data.StructuredTable)68 Field (io.cdap.cdap.spi.data.table.field.Field)66 ArrayList (java.util.ArrayList)54 Range (io.cdap.cdap.spi.data.table.field.Range)36 HashSet (java.util.HashSet)28 IOException (java.io.IOException)22 HashMap (java.util.HashMap)22 LinkedHashSet (java.util.LinkedHashSet)22 List (java.util.List)20 LinkedHashMap (java.util.LinkedHashMap)18 Map (java.util.Map)18 ArtifactNotFoundException (io.cdap.cdap.common.ArtifactNotFoundException)16 Collection (java.util.Collection)16 Set (java.util.Set)16 Nullable (javax.annotation.Nullable)16 ImmutableList (com.google.common.collect.ImmutableList)14 CloseableIterator (io.cdap.cdap.api.dataset.lib.CloseableIterator)14 TableNotFoundException (io.cdap.cdap.spi.data.TableNotFoundException)14 Fields (io.cdap.cdap.spi.data.table.field.Fields)14