Search in sources :

Example 1 with CloseableResource

use of alluxio.resource.CloseableResource in project alluxio by Alluxio.

the class DefaultFileSystemMaster method getRootMountInfo.

private static MountInfo getRootMountInfo(MasterUfsManager ufsManager) {
    try (CloseableResource<UnderFileSystem> resource = ufsManager.getRoot().acquireUfsResource()) {
        boolean shared = resource.get().isObjectStorage() && ServerConfiguration.getBoolean(PropertyKey.UNDERFS_OBJECT_STORE_MOUNT_SHARED_PUBLICLY);
        boolean readonly = ServerConfiguration.getBoolean(PropertyKey.MASTER_MOUNT_TABLE_ROOT_READONLY);
        String rootUfsUri = PathUtils.normalizePath(ServerConfiguration.getString(PropertyKey.MASTER_MOUNT_TABLE_ROOT_UFS), AlluxioURI.SEPARATOR);
        Map<String, String> rootUfsConf = ServerConfiguration.getNestedProperties(PropertyKey.MASTER_MOUNT_TABLE_ROOT_OPTION).entrySet().stream().filter(entry -> entry.getValue() != null).collect(Collectors.toMap(Map.Entry::getKey, entry -> String.valueOf(entry.getValue())));
        MountPOptions mountOptions = MountContext.mergeFrom(MountPOptions.newBuilder().setShared(shared).setReadOnly(readonly).putAllProperties(rootUfsConf)).getOptions().build();
        return new MountInfo(new AlluxioURI(MountTable.ROOT), new AlluxioURI(rootUfsUri), IdUtils.ROOT_MOUNT_ID, mountOptions);
    }
}
Also used : SystemClock(alluxio.clock.SystemClock) OK(alluxio.master.file.InodeSyncStream.SyncStatus.OK) Server(alluxio.Server) PropertyKey(alluxio.conf.PropertyKey) StringUtils(org.apache.commons.lang3.StringUtils) CloseableResource(alluxio.resource.CloseableResource) Map(java.util.Map) LockedInodePathList(alluxio.master.file.meta.LockedInodePathList) WorkerHeartbeatContext(alluxio.master.file.contexts.WorkerHeartbeatContext) InodeDirectory(alluxio.master.file.meta.InodeDirectory) ClientContext(alluxio.ClientContext) ReadOnlyInodeStore(alluxio.master.metastore.ReadOnlyInodeStore) UfsSyncPathCache(alluxio.master.file.meta.UfsSyncPathCache) ConnectionFailedException(alluxio.exception.ConnectionFailedException) ProtobufUtils(alluxio.master.ProtobufUtils) UpdateInodeFileEntry(alluxio.proto.journal.File.UpdateInodeFileEntry) Stream(java.util.stream.Stream) InodeTree(alluxio.master.file.meta.InodeTree) OperationContext(alluxio.master.file.contexts.OperationContext) SetAclAction(alluxio.grpc.SetAclAction) GetStatusPOptions(alluxio.grpc.GetStatusPOptions) InternalOperationContext(alluxio.master.file.contexts.InternalOperationContext) InodeFile(alluxio.master.file.meta.InodeFile) PersistConfig(alluxio.job.plan.persist.PersistConfig) AuthType(alluxio.security.authentication.AuthType) Supplier(java.util.function.Supplier) UnderFileSystemUtils(alluxio.util.UnderFileSystemUtils) LockedInodePath(alluxio.master.file.meta.LockedInodePath) GrpcUtils(alluxio.grpc.GrpcUtils) MountInfo(alluxio.master.file.meta.options.MountInfo) AlluxioURI(alluxio.AlluxioURI) MountPOptions(alluxio.grpc.MountPOptions) MetricsSystem(alluxio.metrics.MetricsSystem) UpdateInodeEntry(alluxio.proto.journal.File.UpdateInodeEntry) RetryPolicy(alluxio.retry.RetryPolicy) PersistFile(alluxio.wire.PersistFile) IdUtils(alluxio.util.IdUtils) PersistenceState(alluxio.master.file.meta.PersistenceState) IOException(java.io.IOException) UfsAbsentPathCache(alluxio.master.file.meta.UfsAbsentPathCache) TreeMap(java.util.TreeMap) UfsStatus(alluxio.underfs.UfsStatus) UfsFileStatus(alluxio.underfs.UfsFileStatus) Preconditions(com.google.common.base.Preconditions) FreeContext(alluxio.master.file.contexts.FreeContext) AclEntry(alluxio.security.authorization.AclEntry) Reconfigurable(alluxio.conf.Reconfigurable) MountTable(alluxio.master.file.meta.MountTable) CommonUtils(alluxio.util.CommonUtils) InodeLockManager(alluxio.master.file.meta.InodeLockManager) InodePathPair(alluxio.master.file.meta.InodePathPair) FailedPreconditionException(alluxio.exception.status.FailedPreconditionException) Fingerprint(alluxio.underfs.Fingerprint) AclEntryType(alluxio.security.authorization.AclEntryType) DeleteContext(alluxio.master.file.contexts.DeleteContext) LoadMetadataContext(alluxio.master.file.contexts.LoadMetadataContext) RenameEntry(alluxio.proto.journal.File.RenameEntry) HeartbeatThread(alluxio.heartbeat.HeartbeatThread) InvalidPathException(alluxio.exception.InvalidPathException) ListStatusContext(alluxio.master.file.contexts.ListStatusContext) MetricKey(alluxio.metrics.MetricKey) SyncPointInfo(alluxio.wire.SyncPointInfo) FileSystemMasterCommonPOptions(alluxio.grpc.FileSystemMasterCommonPOptions) Journaled(alluxio.master.journal.Journaled) ImmutableSet(com.google.common.collect.ImmutableSet) Collection(java.util.Collection) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) CheckpointName(alluxio.master.journal.checkpoint.CheckpointName) Collectors(java.util.stream.Collectors) MkdirsOptions(alluxio.underfs.options.MkdirsOptions) InodeStore(alluxio.master.metastore.InodeStore) SecurityUtils(alluxio.util.SecurityUtils) CoreMasterContext(alluxio.master.CoreMasterContext) CommandType(alluxio.wire.CommandType) SetAttributeContext(alluxio.master.file.contexts.SetAttributeContext) FileAlreadyCompletedException(alluxio.exception.FileAlreadyCompletedException) Function(java.util.function.Function) Stack(java.util.Stack) MetricInfo(alluxio.metrics.MetricInfo) ExistsContext(alluxio.master.file.contexts.ExistsContext) HashSet(java.util.HashSet) Constants(alluxio.Constants) FileSystemMasterView(alluxio.master.file.meta.FileSystemMasterView) NOT_NEEDED(alluxio.master.file.InodeSyncStream.SyncStatus.NOT_NEEDED) ExecutorService(java.util.concurrent.ExecutorService) AuthenticatedClientUser(alluxio.security.authentication.AuthenticatedClientUser) SetAclEntry(alluxio.proto.journal.File.SetAclEntry) Logger(org.slf4j.Logger) Pair(alluxio.collections.Pair) AsyncUserAccessAuditLogWriter(alluxio.master.audit.AsyncUserAccessAuditLogWriter) NotFoundException(alluxio.exception.status.NotFoundException) LockResource(alluxio.resource.LockResource) UnexpectedAlluxioException(alluxio.exception.UnexpectedAlluxioException) CallTracker(alluxio.master.file.contexts.CallTracker) UfsBlockLocationCache(alluxio.master.file.meta.UfsBlockLocationCache) CreateDirectoryContext(alluxio.master.file.contexts.CreateDirectoryContext) CreateFileContext(alluxio.master.file.contexts.CreateFileContext) Arrays(java.util.Arrays) BlockInfo(alluxio.wire.BlockInfo) PersistCommandOptions(alluxio.wire.PersistCommandOptions) GrpcService(alluxio.grpc.GrpcService) TimeSeries(alluxio.metrics.TimeSeries) WorkerInfo(alluxio.wire.WorkerInfo) DelegatingJournaled(alluxio.master.journal.DelegatingJournaled) PreconditionMessage(alluxio.exception.PreconditionMessage) AuditContext(alluxio.master.audit.AuditContext) DescendantType(alluxio.file.options.DescendantType) ActiveSyncManager(alluxio.master.file.activesync.ActiveSyncManager) Set(java.util.Set) AlluxioException(alluxio.exception.AlluxioException) GetStatusContext(alluxio.master.file.contexts.GetStatusContext) UnderFileSystem(alluxio.underfs.UnderFileSystem) JobInfo(alluxio.job.wire.JobInfo) ServiceType(alluxio.grpc.ServiceType) Iterables(com.google.common.collect.Iterables) CountingRetry(alluxio.retry.CountingRetry) UnderFileSystemConfiguration(alluxio.underfs.UnderFileSystemConfiguration) Callable(java.util.concurrent.Callable) InodeDirectoryView(alluxio.master.file.meta.InodeDirectoryView) Mode(alluxio.security.authorization.Mode) Metric(alluxio.metrics.Metric) ArrayList(java.util.ArrayList) ReconfigurableRegistry(alluxio.conf.ReconfigurableRegistry) BlockInfoException(alluxio.exception.BlockInfoException) InodeDirectoryIdGenerator(alluxio.master.file.meta.InodeDirectoryIdGenerator) Builder(alluxio.proto.journal.File.UpdateInodeFileEntry.Builder) Nullable(javax.annotation.Nullable) LoadDescendantPType(alluxio.grpc.LoadDescendantPType) MountContext(alluxio.master.file.contexts.MountContext) MetricRegistry(com.codahale.metrics.MetricRegistry) FileAlreadyExistsException(alluxio.exception.FileAlreadyExistsException) RenameContext(alluxio.master.file.contexts.RenameContext) FileSystemCommandOptions(alluxio.wire.FileSystemCommandOptions) JobMasterClientPool(alluxio.client.job.JobMasterClientPool) FileSystemCommand(alluxio.wire.FileSystemCommand) ExecutorServiceFactory(alluxio.util.executor.ExecutorServiceFactory) UfsInfo(alluxio.wire.UfsInfo) JournaledGroup(alluxio.master.journal.JournaledGroup) ExecutorServiceFactories(alluxio.util.executor.ExecutorServiceFactories) NotThreadSafe(javax.annotation.concurrent.NotThreadSafe) ServerInterceptors(io.grpc.ServerInterceptors) MasterUfsManager(alluxio.underfs.MasterUfsManager) ScheduleAsyncPersistenceContext(alluxio.master.file.contexts.ScheduleAsyncPersistenceContext) LoggerFactory(org.slf4j.LoggerFactory) FileBlockInfo(alluxio.wire.FileBlockInfo) NewBlockEntry(alluxio.proto.journal.File.NewBlockEntry) LogUtils(alluxio.util.LogUtils) ResourceExhaustedException(alluxio.exception.status.ResourceExhaustedException) Counter(com.codahale.metrics.Counter) JobMasterClient(alluxio.client.job.JobMasterClient) CheckConsistencyContext(alluxio.master.file.contexts.CheckConsistencyContext) InvalidArgumentException(alluxio.exception.status.InvalidArgumentException) LockPattern(alluxio.master.file.meta.InodeTree.LockPattern) TtlAction(alluxio.grpc.TtlAction) ServerConfiguration(alluxio.conf.ServerConfiguration) ImmutableMap(com.google.common.collect.ImmutableMap) CompleteFileContext(alluxio.master.file.contexts.CompleteFileContext) TimeSeriesStore(alluxio.master.metrics.TimeSeriesStore) PermissionDeniedException(alluxio.exception.status.PermissionDeniedException) LoadMetadataPOptions(alluxio.grpc.LoadMetadataPOptions) Streams(com.google.common.collect.Streams) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) Sets(com.google.common.collect.Sets) FileNotFoundException(java.io.FileNotFoundException) DelegatingReadOnlyInodeStore(alluxio.master.metastore.DelegatingReadOnlyInodeStore) AccessControlException(alluxio.exception.AccessControlException) File(alluxio.proto.journal.File) List(java.util.List) InvalidFileSizeException(alluxio.exception.InvalidFileSizeException) FileDoesNotExistException(alluxio.exception.FileDoesNotExistException) LoadMetadataPType(alluxio.grpc.LoadMetadataPType) ModeUtils(alluxio.util.ModeUtils) Gauge(com.codahale.metrics.Gauge) UFS_OP_SAVED_PREFIX(alluxio.metrics.MetricInfo.UFS_OP_SAVED_PREFIX) UfsManager(alluxio.underfs.UfsManager) JournalContext(alluxio.master.journal.JournalContext) SortedMap(java.util.SortedMap) UnavailableException(alluxio.exception.status.UnavailableException) MountPointInfo(alluxio.wire.MountPointInfo) JobMasterClientContext(alluxio.worker.job.JobMasterClientContext) ThreadPoolExecutor(java.util.concurrent.ThreadPoolExecutor) HashMap(java.util.HashMap) SetAttributePOptions(alluxio.grpc.SetAttributePOptions) BlockId(alluxio.master.block.BlockId) BlockMaster(alluxio.master.block.BlockMaster) CheckAccessContext(alluxio.master.file.contexts.CheckAccessContext) JournalEntry(alluxio.proto.journal.Journal.JournalEntry) DeletePOptions(alluxio.grpc.DeletePOptions) PathUtils(alluxio.util.io.PathUtils) DirectoryNotEmptyException(alluxio.exception.DirectoryNotEmptyException) ClientIpAddressInjector(alluxio.security.authentication.ClientIpAddressInjector) PrefixList(alluxio.collections.PrefixList) SetAclContext(alluxio.master.file.contexts.SetAclContext) CoreMaster(alluxio.master.CoreMaster) HeartbeatContext(alluxio.heartbeat.HeartbeatContext) Iterator(java.util.Iterator) ExceptionMessage(alluxio.exception.ExceptionMessage) ThreadFactoryUtils(alluxio.util.ThreadFactoryUtils) ProtoUtils(alluxio.util.proto.ProtoUtils) TimeUnit(java.util.concurrent.TimeUnit) BlockLocation(alluxio.wire.BlockLocation) FAILED(alluxio.master.file.InodeSyncStream.SyncStatus.FAILED) LockingScheme(alluxio.master.file.meta.LockingScheme) FileInfo(alluxio.wire.FileInfo) VisibleForTesting(com.google.common.annotations.VisibleForTesting) UfsMode(alluxio.underfs.UfsMode) Collections(java.util.Collections) Inode(alluxio.master.file.meta.Inode) MountPOptions(alluxio.grpc.MountPOptions) UnderFileSystem(alluxio.underfs.UnderFileSystem) MountInfo(alluxio.master.file.meta.options.MountInfo) Map(java.util.Map) TreeMap(java.util.TreeMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) ImmutableMap(com.google.common.collect.ImmutableMap) SortedMap(java.util.SortedMap) HashMap(java.util.HashMap) AlluxioURI(alluxio.AlluxioURI)

Example 2 with CloseableResource

use of alluxio.resource.CloseableResource in project alluxio by Alluxio.

the class FileSystemContext method acquireBlockWorkerClientInternal.

private CloseableResource<BlockWorkerClient> acquireBlockWorkerClientInternal(final WorkerNetAddress workerNetAddress, final ClientContext context, UserState userState) throws IOException {
    SocketAddress address = NetworkAddressUtils.getDataPortSocketAddress(workerNetAddress, context.getClusterConf());
    GrpcServerAddress serverAddress = GrpcServerAddress.create(workerNetAddress.getHost(), address);
    ClientPoolKey key = new ClientPoolKey(address, AuthenticationUserUtils.getImpersonationUser(userState.getSubject(), context.getClusterConf()));
    final ConcurrentHashMap<ClientPoolKey, BlockWorkerClientPool> poolMap = mBlockWorkerClientPoolMap;
    return new CloseableResource<BlockWorkerClient>(poolMap.computeIfAbsent(key, k -> new BlockWorkerClientPool(userState, serverAddress, context.getClusterConf().getInt(PropertyKey.USER_BLOCK_WORKER_CLIENT_POOL_MIN), context.getClusterConf().getInt(PropertyKey.USER_BLOCK_WORKER_CLIENT_POOL_MAX), context.getClusterConf())).acquire()) {

        // Save the reference to the original pool map.
        @Override
        public void closeResource() {
            releaseBlockWorkerClient(workerNetAddress, get(), context, poolMap);
        }
    };
}
Also used : CloseableResource(alluxio.resource.CloseableResource) BlockWorkerClientPool(alluxio.client.block.stream.BlockWorkerClientPool) SocketAddress(java.net.SocketAddress) InetSocketAddress(java.net.InetSocketAddress) GrpcServerAddress(alluxio.grpc.GrpcServerAddress)

Example 3 with CloseableResource

use of alluxio.resource.CloseableResource in project alluxio by Alluxio.

the class ActiveSyncManager method start.

/**
 * Start the polling threads.
 */
public void start() throws IOException {
    mStarted = true;
    // Initialize UFS states
    for (AlluxioURI syncPoint : mSyncPathList) {
        MountTable.Resolution resolution;
        try {
            resolution = mMountTable.resolve(syncPoint);
        } catch (InvalidPathException e) {
            LOG.info("Invalid Path encountered during start up of ActiveSyncManager, " + "path {}, exception {}", syncPoint, e);
            continue;
        }
        try (CloseableResource<UnderFileSystem> ufsResource = resolution.acquireUfsResource()) {
            if (!ufsResource.get().supportsActiveSync()) {
                throw new UnsupportedOperationException("Active Sync is not supported on this UFS type: " + ufsResource.get().getUnderFSType());
            }
            ufsResource.get().startSync(resolution.getUri());
        }
    }
    // therefore forces a sync
    for (Map.Entry<Long, List<AlluxioURI>> entry : mFilterMap.entrySet()) {
        long mountId = entry.getKey();
        long txId = mStartingTxIdMap.getOrDefault(mountId, SyncInfo.INVALID_TXID);
        if (!entry.getValue().isEmpty()) {
            launchPollingThread(mountId, txId);
        }
        try {
            if ((txId == SyncInfo.INVALID_TXID) && ServerConfiguration.getBoolean(PropertyKey.MASTER_UFS_ACTIVE_SYNC_INITIAL_SYNC_ENABLED)) {
                mExecutorService.submit(() -> entry.getValue().parallelStream().forEach(syncPoint -> {
                    MountTable.Resolution resolution;
                    try {
                        resolution = mMountTable.resolve(syncPoint);
                    } catch (InvalidPathException e) {
                        LOG.info("Invalid Path encountered during start up of ActiveSyncManager, " + "path {}, exception {}", syncPoint, e);
                        return;
                    }
                    startInitialFullSync(syncPoint, resolution);
                }));
            }
        } catch (Exception e) {
            LOG.warn("exception encountered during initial sync: {}", e.toString());
        }
    }
}
Also used : CloseableIterator(alluxio.resource.CloseableIterator) RemoveSyncPointEntry(alluxio.proto.journal.File.RemoveSyncPointEntry) LoggerFactory(org.slf4j.LoggerFactory) PropertyKey(alluxio.conf.PropertyKey) FileSystemMaster(alluxio.master.file.FileSystemMaster) HeartbeatThread(alluxio.heartbeat.HeartbeatThread) Future(java.util.concurrent.Future) InvalidPathException(alluxio.exception.InvalidPathException) CloseableResource(alluxio.resource.CloseableResource) SyncPointInfo(alluxio.wire.SyncPointInfo) Map(java.util.Map) Journaled(alluxio.master.journal.Journaled) ServerConfiguration(alluxio.conf.ServerConfiguration) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) CheckpointName(alluxio.master.journal.checkpoint.CheckpointName) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) AddSyncPointEntry(alluxio.proto.journal.File.AddSyncPointEntry) File(alluxio.proto.journal.File) List(java.util.List) UnderFileSystem(alluxio.underfs.UnderFileSystem) RpcContext(alluxio.master.file.RpcContext) Journal(alluxio.proto.journal.Journal) UfsManager(alluxio.underfs.UfsManager) JournalContext(alluxio.master.journal.JournalContext) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) ServerUserState(alluxio.security.user.ServerUserState) ThreadPoolExecutor(java.util.concurrent.ThreadPoolExecutor) Supplier(java.util.function.Supplier) Iterators(com.google.common.collect.Iterators) ArrayList(java.util.ArrayList) JournalEntry(alluxio.proto.journal.Journal.JournalEntry) HashSet(java.util.HashSet) PathUtils(alluxio.util.io.PathUtils) SyncInfo(alluxio.SyncInfo) MountInfo(alluxio.master.file.meta.options.MountInfo) AlluxioURI(alluxio.AlluxioURI) NoSuchElementException(java.util.NoSuchElementException) ExecutorService(java.util.concurrent.ExecutorService) ProcessUtils(alluxio.ProcessUtils) Logger(org.slf4j.Logger) HeartbeatContext(alluxio.heartbeat.HeartbeatContext) Iterator(java.util.Iterator) ReentrantLock(java.util.concurrent.locks.ReentrantLock) ExceptionMessage(alluxio.exception.ExceptionMessage) IOException(java.io.IOException) ThreadFactoryUtils(alluxio.util.ThreadFactoryUtils) LockResource(alluxio.resource.LockResource) RetryUtils(alluxio.retry.RetryUtils) TimeUnit(java.util.concurrent.TimeUnit) Lock(java.util.concurrent.locks.Lock) MountTable(alluxio.master.file.meta.MountTable) NotThreadSafe(javax.annotation.concurrent.NotThreadSafe) MountTable(alluxio.master.file.meta.MountTable) InvalidPathException(alluxio.exception.InvalidPathException) InvalidPathException(alluxio.exception.InvalidPathException) NoSuchElementException(java.util.NoSuchElementException) IOException(java.io.IOException) List(java.util.List) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) ArrayList(java.util.ArrayList) UnderFileSystem(alluxio.underfs.UnderFileSystem) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) AlluxioURI(alluxio.AlluxioURI)

Example 4 with CloseableResource

use of alluxio.resource.CloseableResource in project alluxio by Alluxio.

the class GetPinnedFileIdsBench method prepare.

@Override
public void prepare() throws Exception {
    // The task ID is different for local and cluster executions
    // So including that in the log can help associate the log to the run
    LOG.info("Task ID is {}", mBaseParameters.mId);
    // done once, so skip preparation when running in job worker
    if (mBaseParameters.mDistributed) {
        LOG.info("Skipping preparation in distributed execution");
        return;
    }
    AlluxioURI baseUri = new AlluxioURI(mParameters.mBasePath);
    try (CloseableResource<alluxio.client.file.FileSystemMasterClient> client = mFileSystemContext.acquireMasterClientResource()) {
        LOG.info("Creating temporary directory {} for benchmark", baseUri);
        client.get().createDirectory(baseUri, CreateDirectoryPOptions.newBuilder().setAllowExists(true).build());
    }
    int numFiles = mParameters.mNumFiles;
    int fileNameLength = (int) Math.ceil(Math.max(8, Math.log10(numFiles)));
    CompletableFuture<Void>[] futures = new CompletableFuture[numFiles];
    LOG.info("Generating {} pinned test files at the master", numFiles);
    for (int i = 0; i < numFiles; i++) {
        AlluxioURI fileUri = baseUri.join(CommonUtils.randomAlphaNumString(fileNameLength));
        CompletableFuture<Void> future = CompletableFuture.supplyAsync((Supplier<Void>) () -> {
            try (CloseableResource<FileSystemMasterClient> client = mFileSystemContext.acquireMasterClientResource()) {
                client.get().createFile(fileUri, CreateFilePOptions.newBuilder().setBlockSizeBytes(mConf.getBytes(PropertyKey.USER_BLOCK_SIZE_BYTES_DEFAULT)).build());
                client.get().setAttribute(fileUri, SetAttributePOptions.newBuilder().setPinned(true).build());
            } catch (AlluxioStatusException e) {
                LOG.warn("Exception during file creation of {}", fileUri, e);
            }
            return null;
        }, getPool());
        futures[i] = (future);
    }
    CompletableFuture.allOf(futures).join();
    LOG.info("Test files generated");
}
Also used : CompletableFuture(java.util.concurrent.CompletableFuture) CloseableResource(alluxio.resource.CloseableResource) FileSystemMasterClient(alluxio.client.file.FileSystemMasterClient) AlluxioStatusException(alluxio.exception.status.AlluxioStatusException) AlluxioURI(alluxio.AlluxioURI)

Example 5 with CloseableResource

use of alluxio.resource.CloseableResource in project alluxio by Alluxio.

the class HiveDatabase method getTable.

@Override
public UdbTable getTable(String tableName, UdbBypassSpec bypassSpec) throws IOException {
    try {
        Table table;
        List<Partition> partitions;
        List<ColumnStatisticsObj> columnStats;
        List<String> partitionColumns;
        Map<String, List<ColumnStatisticsInfo>> statsMap = new HashMap<>();
        // perform all the hive client operations, and release the client early.
        try (CloseableResource<IMetaStoreClient> client = mClientPool.acquireClientResource()) {
            table = client.get().getTable(mHiveDbName, tableName);
            // Potentially expensive call
            partitions = client.get().listPartitions(mHiveDbName, table.getTableName(), (short) -1);
            List<String> colNames = table.getSd().getCols().stream().map(FieldSchema::getName).collect(Collectors.toList());
            columnStats = client.get().getTableColumnStatistics(mHiveDbName, tableName, colNames);
            // construct the partition statistics
            List<String> dataColumns = table.getSd().getCols().stream().map(org.apache.hadoop.hive.metastore.api.FieldSchema::getName).collect(Collectors.toList());
            partitionColumns = table.getPartitionKeys().stream().map(org.apache.hadoop.hive.metastore.api.FieldSchema::getName).collect(Collectors.toList());
            List<String> partitionNames = partitions.stream().map(partition -> FileUtils.makePartName(partitionColumns, partition.getValues())).collect(Collectors.toList());
            for (List<String> partialPartitionNames : Lists.partition(partitionNames, MAX_PARTITION_COLUMN_STATISTICS)) {
                statsMap.putAll(client.get().getPartitionColumnStatistics(mHiveDbName, tableName, partialPartitionNames, dataColumns).entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue().stream().map(HiveUtils::toProto).collect(Collectors.toList()), (e1, e2) -> e2)));
            }
        }
        PathTranslator pathTranslator = mountAlluxioPaths(table, partitions, bypassSpec);
        List<ColumnStatisticsInfo> colStats = columnStats.stream().map(HiveUtils::toProto).collect(Collectors.toList());
        // construct table layout
        PartitionInfo partitionInfo = PartitionInfo.newBuilder().setDbName(getUdbContext().getDbName()).setTableName(tableName).addAllDataCols(HiveUtils.toProto(table.getSd().getCols())).setStorage(HiveUtils.toProto(table.getSd(), pathTranslator)).putAllParameters(table.getParameters()).build();
        Layout layout = Layout.newBuilder().setLayoutType(HiveLayout.TYPE).setLayoutData(partitionInfo.toByteString()).build();
        // create udb partitions info
        List<UdbPartition> udbPartitions = new ArrayList<>();
        if (partitionColumns.isEmpty()) {
            // unpartitioned table, generate a partition
            PartitionInfo.Builder pib = PartitionInfo.newBuilder().setDbName(getUdbContext().getDbName()).setTableName(tableName).addAllDataCols(HiveUtils.toProto(table.getSd().getCols())).setStorage(HiveUtils.toProto(table.getSd(), pathTranslator)).setPartitionName(tableName).putAllParameters(table.getParameters());
            udbPartitions.add(new HivePartition(new HiveLayout(pib.build(), Collections.emptyList())));
        } else {
            for (Partition partition : partitions) {
                String partName = FileUtils.makePartName(partitionColumns, partition.getValues());
                PartitionInfo.Builder pib = PartitionInfo.newBuilder().setDbName(getUdbContext().getDbName()).setTableName(tableName).addAllDataCols(HiveUtils.toProto(partition.getSd().getCols())).setStorage(HiveUtils.toProto(partition.getSd(), pathTranslator)).setPartitionName(partName).putAllParameters(partition.getParameters());
                if (partition.getValues() != null) {
                    pib.addAllValues(partition.getValues());
                }
                udbPartitions.add(new HivePartition(new HiveLayout(pib.build(), statsMap.getOrDefault(partName, Collections.emptyList()))));
            }
        }
        return new HiveTable(tableName, HiveUtils.toProtoSchema(table.getSd().getCols()), colStats, HiveUtils.toProto(table.getPartitionKeys()), udbPartitions, layout, table);
    } catch (NoSuchObjectException e) {
        throw new NotFoundException("Table " + tableName + " does not exist.", e);
    } catch (TException e) {
        throw new IOException("Failed to get table: " + tableName + " error: " + e.getMessage(), e);
    }
}
Also used : ColumnStatisticsInfo(alluxio.grpc.table.ColumnStatisticsInfo) UdbUtils(alluxio.table.common.udb.UdbUtils) UnderDatabase(alluxio.table.common.udb.UnderDatabase) UdbPartition(alluxio.table.common.UdbPartition) MetaException(org.apache.hadoop.hive.metastore.api.MetaException) UdbContext(alluxio.table.common.udb.UdbContext) LoggerFactory(org.slf4j.LoggerFactory) HashMap(java.util.HashMap) Partition(org.apache.hadoop.hive.metastore.api.Partition) Warehouse(org.apache.hadoop.hive.metastore.Warehouse) ArrayList(java.util.ArrayList) DatabaseInfo(alluxio.master.table.DatabaseInfo) PathUtils(alluxio.util.io.PathUtils) HiveClientPoolCache(alluxio.table.under.hive.util.HiveClientPoolCache) Lists(com.google.common.collect.Lists) CloseableResource(alluxio.resource.CloseableResource) AbstractHiveClientPool(alluxio.table.under.hive.util.AbstractHiveClientPool) AlluxioURI(alluxio.AlluxioURI) UdbBypassSpec(alluxio.table.common.udb.UdbBypassSpec) Map(java.util.Map) UdbConfiguration(alluxio.table.common.udb.UdbConfiguration) Logger(org.slf4j.Logger) ColumnStatisticsObj(org.apache.hadoop.hive.metastore.api.ColumnStatisticsObj) Layout(alluxio.grpc.table.Layout) TException(org.apache.thrift.TException) AlluxioException(alluxio.exception.AlluxioException) PrincipalType(org.apache.hadoop.hive.metastore.api.PrincipalType) IOException(java.io.IOException) NotFoundException(alluxio.exception.status.NotFoundException) Collectors(java.util.stream.Collectors) Table(org.apache.hadoop.hive.metastore.api.Table) Objects(java.util.Objects) FieldSchema(org.apache.hadoop.hive.metastore.api.FieldSchema) PartitionInfo(alluxio.grpc.table.layout.hive.PartitionInfo) List(java.util.List) PathTranslator(alluxio.table.common.udb.PathTranslator) IMetaStoreClient(org.apache.hadoop.hive.metastore.IMetaStoreClient) UdbTable(alluxio.table.common.udb.UdbTable) FileUtils(org.apache.hadoop.hive.common.FileUtils) VisibleForTesting(com.google.common.annotations.VisibleForTesting) HiveLayout(alluxio.table.common.layout.HiveLayout) Database(org.apache.hadoop.hive.metastore.api.Database) Collections(java.util.Collections) NoSuchObjectException(org.apache.hadoop.hive.metastore.api.NoSuchObjectException) TException(org.apache.thrift.TException) HiveLayout(alluxio.table.common.layout.HiveLayout) HashMap(java.util.HashMap) FieldSchema(org.apache.hadoop.hive.metastore.api.FieldSchema) ArrayList(java.util.ArrayList) NotFoundException(alluxio.exception.status.NotFoundException) IMetaStoreClient(org.apache.hadoop.hive.metastore.IMetaStoreClient) UdbPartition(alluxio.table.common.UdbPartition) ColumnStatisticsObj(org.apache.hadoop.hive.metastore.api.ColumnStatisticsObj) ArrayList(java.util.ArrayList) List(java.util.List) PartitionInfo(alluxio.grpc.table.layout.hive.PartitionInfo) UdbPartition(alluxio.table.common.UdbPartition) Partition(org.apache.hadoop.hive.metastore.api.Partition) Table(org.apache.hadoop.hive.metastore.api.Table) UdbTable(alluxio.table.common.udb.UdbTable) IOException(java.io.IOException) PathTranslator(alluxio.table.common.udb.PathTranslator) Layout(alluxio.grpc.table.Layout) HiveLayout(alluxio.table.common.layout.HiveLayout) ColumnStatisticsInfo(alluxio.grpc.table.ColumnStatisticsInfo) NoSuchObjectException(org.apache.hadoop.hive.metastore.api.NoSuchObjectException)

Aggregations

CloseableResource (alluxio.resource.CloseableResource)5 AlluxioURI (alluxio.AlluxioURI)4 PathUtils (alluxio.util.io.PathUtils)3 IOException (java.io.IOException)3 ArrayList (java.util.ArrayList)3 List (java.util.List)3 Map (java.util.Map)3 PropertyKey (alluxio.conf.PropertyKey)2 ServerConfiguration (alluxio.conf.ServerConfiguration)2 ExceptionMessage (alluxio.exception.ExceptionMessage)2 InvalidPathException (alluxio.exception.InvalidPathException)2 HeartbeatContext (alluxio.heartbeat.HeartbeatContext)2 HeartbeatThread (alluxio.heartbeat.HeartbeatThread)2 MountTable (alluxio.master.file.meta.MountTable)2 MountInfo (alluxio.master.file.meta.options.MountInfo)2 JournalContext (alluxio.master.journal.JournalContext)2 Journaled (alluxio.master.journal.Journaled)2 CheckpointName (alluxio.master.journal.checkpoint.CheckpointName)2 File (alluxio.proto.journal.File)2 JournalEntry (alluxio.proto.journal.Journal.JournalEntry)2