Search in sources :

Example 1 with Loza

use of org.apache.ignite.internal.raft.Loza in project ignite-3 by apache.

the class MetaStorageManager method start.

/**
 * {@inheritDoc}
 */
@Override
public void start() {
    String[] metastorageNodes = this.locCfgMgr.configurationRegistry().getConfiguration(NodeConfiguration.KEY).metastorageNodes().value();
    Predicate<ClusterNode> metaStorageNodesContainsLocPred = clusterNode -> Arrays.asList(metastorageNodes).contains(clusterNode.name());
    if (metastorageNodes.length > 0) {
        metaStorageNodesOnStart = true;
        List<ClusterNode> metaStorageMembers = clusterNetSvc.topologyService().allMembers().stream().filter(metaStorageNodesContainsLocPred).collect(Collectors.toList());
        // without hosting metastorage, this will be rewritten in init phase https://issues.apache.org/jira/browse/IGNITE-15114
        if (metaStorageMembers.isEmpty()) {
            throw new IgniteException("Cannot start meta storage manager because there is no node in the cluster that hosts meta storage.");
        }
        // This will be rewritten in init phase https://issues.apache.org/jira/browse/IGNITE-15114
        if (metastorageNodes.length > 1) {
            throw new IgniteException("Cannot start meta storage manager because it is not allowed to start several metastorage nodes.");
        }
        storage.start();
        try {
            raftGroupServiceFut = raftMgr.prepareRaftGroup(METASTORAGE_RAFT_GROUP_NAME, metaStorageMembers, () -> new MetaStorageListener(storage));
        } catch (NodeStoppingException e) {
            throw new AssertionError("Loza was stopped before Meta Storage manager", e);
        }
        this.metaStorageSvcFut = raftGroupServiceFut.thenApply(service -> new MetaStorageServiceImpl(service, clusterNetSvc.topologyService().localMember().id()));
        if (hasMetastorageLocally(locCfgMgr)) {
            clusterNetSvc.topologyService().addEventHandler(new TopologyEventHandler() {

                @Override
                public void onAppeared(ClusterNode member) {
                // No-op.
                }

                @Override
                public void onDisappeared(ClusterNode member) {
                    metaStorageSvcFut.thenCompose(svc -> svc.closeCursors(member.id()));
                }
            });
        }
    } else {
        this.metaStorageSvcFut = new CompletableFuture<>();
    }
// TODO: IGNITE-15114 Cluster initialization flow. Here we should complete metaStorageServiceFuture.
// clusterNetSvc.messagingService().addMessageHandler((message, senderAddr, correlationId) -> {});
}
Also used : ClusterNode(org.apache.ignite.network.ClusterNode) OperationTimeoutException(org.apache.ignite.internal.metastorage.client.OperationTimeoutException) Arrays(java.util.Arrays) WatchListener(org.apache.ignite.internal.metastorage.client.WatchListener) IgniteLogger(org.apache.ignite.lang.IgniteLogger) CompactedException(org.apache.ignite.internal.metastorage.client.CompactedException) ByteUtils.bytesToLong(org.apache.ignite.internal.util.ByteUtils.bytesToLong) RaftGroupService(org.apache.ignite.raft.client.service.RaftGroupService) Map(java.util.Map) KeyCriterion(org.apache.ignite.internal.metastorage.watch.KeyCriterion) NodeConfiguration(org.apache.ignite.configuration.schemas.runner.NodeConfiguration) IgniteComponent(org.apache.ignite.internal.manager.IgniteComponent) KeyValueStorage(org.apache.ignite.internal.metastorage.server.KeyValueStorage) Predicate(java.util.function.Predicate) Collection(java.util.Collection) Set(java.util.Set) Cursor(org.apache.ignite.internal.util.Cursor) ConfigurationManager(org.apache.ignite.internal.configuration.ConfigurationManager) Collectors(java.util.stream.Collectors) If(org.apache.ignite.internal.metastorage.client.If) IgniteBiTuple(org.apache.ignite.lang.IgniteBiTuple) ClusterNode(org.apache.ignite.network.ClusterNode) Nullable(org.jetbrains.annotations.Nullable) List(java.util.List) MetaStorageListener(org.apache.ignite.internal.metastorage.server.raft.MetaStorageListener) IgniteInternalException(org.apache.ignite.lang.IgniteInternalException) Optional(java.util.Optional) NotNull(org.jetbrains.annotations.NotNull) Operation(org.apache.ignite.internal.metastorage.client.Operation) StatementResult(org.apache.ignite.internal.metastorage.client.StatementResult) IgniteException(org.apache.ignite.lang.IgniteException) VaultManager(org.apache.ignite.internal.vault.VaultManager) Loza(org.apache.ignite.internal.raft.Loza) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) CompletableFuture(java.util.concurrent.CompletableFuture) ByteUtils.longToBytes(org.apache.ignite.internal.util.ByteUtils.longToBytes) MetaStorageServiceImpl(org.apache.ignite.internal.metastorage.client.MetaStorageServiceImpl) TopologyEventHandler(org.apache.ignite.network.TopologyEventHandler) AggregatedWatch(org.apache.ignite.internal.metastorage.watch.AggregatedWatch) IgniteUtils(org.apache.ignite.internal.util.IgniteUtils) WatchAggregator(org.apache.ignite.internal.metastorage.watch.WatchAggregator) IgniteSpinBusyLock(org.apache.ignite.internal.util.IgniteSpinBusyLock) NoSuchElementException(java.util.NoSuchElementException) Entry(org.apache.ignite.internal.metastorage.client.Entry) Iterator(java.util.Iterator) NodeStoppingException(org.apache.ignite.lang.NodeStoppingException) ByteArray(org.apache.ignite.lang.ByteArray) MetaStorageService(org.apache.ignite.internal.metastorage.client.MetaStorageService) ExecutionException(java.util.concurrent.ExecutionException) ClusterService(org.apache.ignite.network.ClusterService) Condition(org.apache.ignite.internal.metastorage.client.Condition) IgniteUuid(org.apache.ignite.lang.IgniteUuid) NodeStoppingException(org.apache.ignite.lang.NodeStoppingException) MetaStorageServiceImpl(org.apache.ignite.internal.metastorage.client.MetaStorageServiceImpl) MetaStorageListener(org.apache.ignite.internal.metastorage.server.raft.MetaStorageListener) IgniteException(org.apache.ignite.lang.IgniteException) TopologyEventHandler(org.apache.ignite.network.TopologyEventHandler)

Example 2 with Loza

use of org.apache.ignite.internal.raft.Loza in project ignite-3 by apache.

the class TableManager method createTableLocally.

/**
 * Creates local structures for a table.
 *
 * @param causalityToken Causality token.
 * @param name  Table name.
 * @param tblId Table id.
 * @param assignment Affinity assignment.
 */
private void createTableLocally(long causalityToken, String name, UUID tblId, List<List<ClusterNode>> assignment, SchemaDescriptor schemaDesc) {
    int partitions = assignment.size();
    var partitionsGroupsFutures = new ArrayList<CompletableFuture<RaftGroupService>>();
    Path storageDir = partitionsStoreDir.resolve(name);
    try {
        Files.createDirectories(storageDir);
    } catch (IOException e) {
        throw new IgniteInternalException("Failed to create partitions store directory for " + name + ": " + e.getMessage(), e);
    }
    TableConfiguration tableCfg = tablesCfg.tables().get(name);
    DataRegion dataRegion = dataRegions.computeIfAbsent(tableCfg.dataRegion().value(), dataRegionName -> {
        DataRegion newDataRegion = engine.createDataRegion(dataStorageCfg.regions().get(dataRegionName));
        try {
            newDataRegion.start();
        } catch (Exception e) {
            try {
                newDataRegion.stop();
            } catch (Exception stopException) {
                e.addSuppressed(stopException);
            }
            throw e;
        }
        return newDataRegion;
    });
    TableStorage tableStorage = engine.createTable(storageDir, tableCfg, dataRegion);
    tableStorage.start();
    for (int p = 0; p < partitions; p++) {
        int partId = p;
        try {
            partitionsGroupsFutures.add(raftMgr.prepareRaftGroup(raftGroupName(tblId, p), assignment.get(p), () -> new PartitionListener(tblId, new VersionedRowStore(tableStorage.getOrCreatePartition(partId), txManager))));
        } catch (NodeStoppingException e) {
            throw new AssertionError("Loza was stopped before Table manager", e);
        }
    }
    CompletableFuture.allOf(partitionsGroupsFutures.toArray(CompletableFuture[]::new)).thenRun(() -> {
        try {
            Int2ObjectOpenHashMap<RaftGroupService> partitionMap = new Int2ObjectOpenHashMap<>(partitions);
            for (int p = 0; p < partitions; p++) {
                CompletableFuture<RaftGroupService> future = partitionsGroupsFutures.get(p);
                assert future.isDone();
                RaftGroupService service = future.join();
                partitionMap.put(p, service);
            }
            InternalTableImpl internalTable = new InternalTableImpl(name, tblId, partitionMap, partitions, netAddrResolver, txManager, tableStorage);
            var schemaRegistry = new SchemaRegistryImpl(v -> {
                if (!busyLock.enterBusy()) {
                    throw new IgniteException(new NodeStoppingException());
                }
                try {
                    return tableSchema(tblId, v);
                } finally {
                    busyLock.leaveBusy();
                }
            }, () -> {
                if (!busyLock.enterBusy()) {
                    throw new IgniteException(new NodeStoppingException());
                }
                try {
                    return latestSchemaVersion(tblId);
                } finally {
                    busyLock.leaveBusy();
                }
            });
            schemaRegistry.onSchemaRegistered(schemaDesc);
            var table = new TableImpl(internalTable, schemaRegistry);
            tablesVv.update(causalityToken, previous -> {
                var val = previous == null ? new HashMap() : new HashMap<>(previous);
                val.put(name, table);
                return val;
            }, th -> {
                throw new IgniteInternalException(IgniteStringFormatter.format("Cannot create a table [name={}, id={}]", name, tblId), th);
            });
            tablesByIdVv.update(causalityToken, previous -> {
                var val = previous == null ? new HashMap() : new HashMap<>(previous);
                val.put(tblId, table);
                return val;
            }, th -> {
                throw new IgniteInternalException(IgniteStringFormatter.format("Cannot create a table [name={}, id={}]", name, tblId), th);
            });
            completeApiCreateFuture(table);
            fireEvent(TableEvent.CREATE, new TableEventParameters(causalityToken, table), null);
        } catch (Exception e) {
            fireEvent(TableEvent.CREATE, new TableEventParameters(causalityToken, tblId, name), e);
        }
    }).join();
}
Also used : TableStorage(org.apache.ignite.internal.storage.engine.TableStorage) IgniteTablesInternal(org.apache.ignite.internal.table.IgniteTablesInternal) ExtendedTableConfiguration(org.apache.ignite.internal.configuration.schema.ExtendedTableConfiguration) TableAlreadyExistsException(org.apache.ignite.lang.TableAlreadyExistsException) ConfigurationUtil.directProxy(org.apache.ignite.internal.configuration.util.ConfigurationUtil.directProxy) ConfigurationUtil.getByInternalId(org.apache.ignite.internal.configuration.util.ConfigurationUtil.getByInternalId) ExtendedTableChange(org.apache.ignite.internal.configuration.schema.ExtendedTableChange) IgniteLogger(org.apache.ignite.lang.IgniteLogger) RaftGroupService(org.apache.ignite.raft.client.service.RaftGroupService) Map(java.util.Map) DataRegion(org.apache.ignite.internal.storage.engine.DataRegion) TableNotFoundException(org.apache.ignite.lang.TableNotFoundException) Path(java.nio.file.Path) SchemaUtils(org.apache.ignite.internal.schema.SchemaUtils) ExtendedTableView(org.apache.ignite.internal.configuration.schema.ExtendedTableView) IgniteComponent(org.apache.ignite.internal.manager.IgniteComponent) SchemaConfiguration(org.apache.ignite.internal.configuration.schema.SchemaConfiguration) Int2ObjectOpenHashMap(it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap) InternalTableImpl(org.apache.ignite.internal.table.distributed.storage.InternalTableImpl) DataStorageConfiguration(org.apache.ignite.configuration.schemas.store.DataStorageConfiguration) TablesConfiguration(org.apache.ignite.configuration.schemas.table.TablesConfiguration) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Set(java.util.Set) DEFAULT_DATA_REGION_NAME(org.apache.ignite.configuration.schemas.store.DataStorageConfigurationSchema.DEFAULT_DATA_REGION_NAME) CompletionException(java.util.concurrent.CompletionException) Producer(org.apache.ignite.internal.manager.Producer) StorageEngine(org.apache.ignite.internal.storage.engine.StorageEngine) UUID(java.util.UUID) ConfigurationChangeException(org.apache.ignite.configuration.ConfigurationChangeException) Collectors(java.util.stream.Collectors) TxManager(org.apache.ignite.internal.tx.TxManager) TableView(org.apache.ignite.configuration.schemas.table.TableView) ClusterNode(org.apache.ignite.network.ClusterNode) Nullable(org.jetbrains.annotations.Nullable) List(java.util.List) IgniteInternalException(org.apache.ignite.lang.IgniteInternalException) IgniteStringFormatter(org.apache.ignite.lang.IgniteStringFormatter) NotNull(org.jetbrains.annotations.NotNull) InternalTable(org.apache.ignite.internal.table.InternalTable) IgniteException(org.apache.ignite.lang.IgniteException) Loza(org.apache.ignite.internal.raft.Loza) SchemaRegistryImpl(org.apache.ignite.internal.schema.registry.SchemaRegistryImpl) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) TableConfiguration(org.apache.ignite.configuration.schemas.table.TableConfiguration) ByteUtils(org.apache.ignite.internal.util.ByteUtils) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) SchemaSerializerImpl(org.apache.ignite.internal.schema.marshaller.schema.SchemaSerializerImpl) Function(java.util.function.Function) Supplier(java.util.function.Supplier) SchemaView(org.apache.ignite.internal.configuration.schema.SchemaView) VersionedRowStore(org.apache.ignite.internal.table.distributed.storage.VersionedRowStore) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) TableImpl(org.apache.ignite.internal.table.TableImpl) IgniteSpinBusyLock(org.apache.ignite.internal.util.IgniteSpinBusyLock) IgniteTables(org.apache.ignite.table.manager.IgniteTables) NoSuchElementException(java.util.NoSuchElementException) VersionedValue(org.apache.ignite.internal.causality.VersionedValue) TopologyService(org.apache.ignite.network.TopologyService) SchemaDescriptor(org.apache.ignite.internal.schema.SchemaDescriptor) TableEventParameters(org.apache.ignite.internal.table.event.TableEventParameters) Files(java.nio.file.Files) NamedListView(org.apache.ignite.configuration.NamedListView) NodeStoppingException(org.apache.ignite.lang.NodeStoppingException) IgniteObjectName(org.apache.ignite.internal.util.IgniteObjectName) IOException(java.io.IOException) Ignite(org.apache.ignite.Ignite) BaselineManager(org.apache.ignite.internal.baseline.BaselineManager) TableStorage(org.apache.ignite.internal.storage.engine.TableStorage) ConfigurationNamedListListener(org.apache.ignite.configuration.notifications.ConfigurationNamedListListener) NetworkAddress(org.apache.ignite.network.NetworkAddress) Consumer(java.util.function.Consumer) ConfigurationNotificationEvent(org.apache.ignite.configuration.notifications.ConfigurationNotificationEvent) TableEvent(org.apache.ignite.internal.table.event.TableEvent) AffinityUtils(org.apache.ignite.internal.affinity.AffinityUtils) EventListener(org.apache.ignite.internal.manager.EventListener) PartitionListener(org.apache.ignite.internal.table.distributed.raft.PartitionListener) Table(org.apache.ignite.table.Table) ConfigurationValidationException(org.apache.ignite.configuration.validation.ConfigurationValidationException) RocksDbStorageEngine(org.apache.ignite.internal.storage.rocksdb.RocksDbStorageEngine) TableChange(org.apache.ignite.configuration.schemas.table.TableChange) NodeStoppingException(org.apache.ignite.lang.NodeStoppingException) Int2ObjectOpenHashMap(it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) InternalTableImpl(org.apache.ignite.internal.table.distributed.storage.InternalTableImpl) TableImpl(org.apache.ignite.internal.table.TableImpl) CompletableFuture(java.util.concurrent.CompletableFuture) IgniteException(org.apache.ignite.lang.IgniteException) ExtendedTableConfiguration(org.apache.ignite.internal.configuration.schema.ExtendedTableConfiguration) TableConfiguration(org.apache.ignite.configuration.schemas.table.TableConfiguration) Path(java.nio.file.Path) VersionedRowStore(org.apache.ignite.internal.table.distributed.storage.VersionedRowStore) Int2ObjectOpenHashMap(it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap) IgniteInternalException(org.apache.ignite.lang.IgniteInternalException) RaftGroupService(org.apache.ignite.raft.client.service.RaftGroupService) IOException(java.io.IOException) SchemaRegistryImpl(org.apache.ignite.internal.schema.registry.SchemaRegistryImpl) TableAlreadyExistsException(org.apache.ignite.lang.TableAlreadyExistsException) TableNotFoundException(org.apache.ignite.lang.TableNotFoundException) CompletionException(java.util.concurrent.CompletionException) ConfigurationChangeException(org.apache.ignite.configuration.ConfigurationChangeException) IgniteInternalException(org.apache.ignite.lang.IgniteInternalException) IgniteException(org.apache.ignite.lang.IgniteException) NoSuchElementException(java.util.NoSuchElementException) NodeStoppingException(org.apache.ignite.lang.NodeStoppingException) IOException(java.io.IOException) ConfigurationValidationException(org.apache.ignite.configuration.validation.ConfigurationValidationException) PartitionListener(org.apache.ignite.internal.table.distributed.raft.PartitionListener) TableEventParameters(org.apache.ignite.internal.table.event.TableEventParameters) InternalTableImpl(org.apache.ignite.internal.table.distributed.storage.InternalTableImpl) DataRegion(org.apache.ignite.internal.storage.engine.DataRegion)

Example 3 with Loza

use of org.apache.ignite.internal.raft.Loza in project ignite-3 by apache.

the class TableManager method start.

/**
 * {@inheritDoc}
 */
@Override
public void start() {
    tablesCfg.tables().listenElements(new ConfigurationNamedListListener<>() {

        @Override
        public CompletableFuture<?> onCreate(ConfigurationNotificationEvent<TableView> ctx) {
            if (!busyLock.enterBusy()) {
                String tblName = ctx.newValue().name();
                UUID tblId = ((ExtendedTableView) ctx.newValue()).id();
                fireEvent(TableEvent.CREATE, new TableEventParameters(ctx.storageRevision(), tblId, tblName), new NodeStoppingException());
                return CompletableFuture.failedFuture(new NodeStoppingException());
            }
            try {
                onTableCreateInternal(ctx);
            } finally {
                busyLock.leaveBusy();
            }
            return CompletableFuture.completedFuture(null);
        }

        /**
         * Method for handle a table configuration event.
         *
         * @param ctx Configuration event.
         */
        private void onTableCreateInternal(ConfigurationNotificationEvent<TableView> ctx) {
            String tblName = ctx.newValue().name();
            UUID tblId = ((ExtendedTableView) ctx.newValue()).id();
            // configuration, which is not supported now.
            assert ((ExtendedTableView) ctx.newValue()).assignments() != null : IgniteStringFormatter.format("Table [id={}, name={}] has empty assignments.", tblId, tblName);
            // TODO: IGNITE-16369 Listener with any placeholder should be used instead.
            ((ExtendedTableConfiguration) tablesCfg.tables().get(tblName)).schemas().listenElements(new ConfigurationNamedListListener<>() {

                @Override
                public CompletableFuture<?> onCreate(ConfigurationNotificationEvent<SchemaView> schemasCtx) {
                    long causalityToken = schemasCtx.storageRevision();
                    if (!busyLock.enterBusy()) {
                        fireEvent(TableEvent.ALTER, new TableEventParameters(causalityToken, tblId, tblName), new NodeStoppingException());
                        return CompletableFuture.failedFuture(new NodeStoppingException());
                    }
                    try {
                        // FIXME: https://issues.apache.org/jira/browse/IGNITE-16369
                        if (ctx.storageRevision() != schemasCtx.storageRevision()) {
                            return tablesByIdVv.get(causalityToken).thenAccept(tablesById -> {
                                TableImpl table = tablesById.get(tblId);
                                ((SchemaRegistryImpl) table.schemaView()).onSchemaRegistered(SchemaSerializerImpl.INSTANCE.deserialize((schemasCtx.newValue().schema())));
                                fireEvent(TableEvent.ALTER, new TableEventParameters(causalityToken, table), null);
                            });
                        }
                        return CompletableFuture.completedFuture(null);
                    } catch (Exception e) {
                        fireEvent(TableEvent.ALTER, new TableEventParameters(causalityToken, tblId, tblName), e);
                        return CompletableFuture.failedFuture(e);
                    } finally {
                        busyLock.leaveBusy();
                    }
                }
            });
            ((ExtendedTableConfiguration) tablesCfg.tables().get(tblName)).assignments().listen(assignmentsCtx -> {
                if (!busyLock.enterBusy()) {
                    return CompletableFuture.failedFuture(new NodeStoppingException());
                }
                try {
                    // FIXME: https://issues.apache.org/jira/browse/IGNITE-16369
                    if (ctx.storageRevision() == assignmentsCtx.storageRevision()) {
                        return CompletableFuture.completedFuture(null);
                    } else {
                        return updateAssignmentInternal(assignmentsCtx.storageRevision(), tblId, assignmentsCtx);
                    }
                } finally {
                    busyLock.leaveBusy();
                }
            });
            createTableLocally(ctx.storageRevision(), tblName, tblId, (List<List<ClusterNode>>) ByteUtils.fromBytes(((ExtendedTableView) ctx.newValue()).assignments()), SchemaSerializerImpl.INSTANCE.deserialize(((ExtendedTableView) ctx.newValue()).schemas().get(String.valueOf(INITIAL_SCHEMA_VERSION)).schema()));
        }

        private CompletableFuture<?> updateAssignmentInternal(long causalityToken, UUID tblId, ConfigurationNotificationEvent<byte[]> assignmentsCtx) {
            List<List<ClusterNode>> oldAssignments = (List<List<ClusterNode>>) ByteUtils.fromBytes(assignmentsCtx.oldValue());
            List<List<ClusterNode>> newAssignments = (List<List<ClusterNode>>) ByteUtils.fromBytes(assignmentsCtx.newValue());
            CompletableFuture<?>[] futures = new CompletableFuture<?>[oldAssignments.size()];
            // TODO: be exact same amount of partitions and replicas for both old and new assignments
            for (int i = 0; i < oldAssignments.size(); i++) {
                int partId = i;
                List<ClusterNode> oldPartitionAssignment = oldAssignments.get(partId);
                List<ClusterNode> newPartitionAssignment = newAssignments.get(partId);
                var toAdd = new HashSet<>(newPartitionAssignment);
                toAdd.removeAll(oldPartitionAssignment);
                // Create new raft nodes according to new assignments.
                futures[i] = tablesByIdVv.get(causalityToken).thenCompose(tablesById -> {
                    InternalTable internalTable = tablesById.get(tblId).internalTable();
                    try {
                        return raftMgr.updateRaftGroup(raftGroupName(tblId, partId), newPartitionAssignment, toAdd, () -> new PartitionListener(tblId, new VersionedRowStore(internalTable.storage().getOrCreatePartition(partId), txManager))).thenAccept(updatedRaftGroupService -> ((InternalTableImpl) internalTable).updateInternalTableRaftGroupService(partId, updatedRaftGroupService)).exceptionally(th -> {
                            LOG.error("Failed to update raft groups one the node", th);
                            return null;
                        });
                    } catch (NodeStoppingException e) {
                        throw new AssertionError("Loza was stopped before Table manager", e);
                    }
                });
            }
            return CompletableFuture.allOf(futures);
        }

        @Override
        public CompletableFuture<?> onRename(String oldName, String newName, ConfigurationNotificationEvent<TableView> ctx) {
            return CompletableFuture.completedFuture(null);
        }

        @Override
        public CompletableFuture<?> onDelete(ConfigurationNotificationEvent<TableView> ctx) {
            if (!busyLock.enterBusy()) {
                String tblName = ctx.oldValue().name();
                UUID tblId = ((ExtendedTableView) ctx.oldValue()).id();
                fireEvent(TableEvent.DROP, new TableEventParameters(ctx.storageRevision(), tblId, tblName), new NodeStoppingException());
                return CompletableFuture.failedFuture(new NodeStoppingException());
            }
            try {
                dropTableLocally(ctx.storageRevision(), ctx.oldValue().name(), ((ExtendedTableView) ctx.oldValue()).id(), (List<List<ClusterNode>>) ByteUtils.fromBytes(((ExtendedTableView) ctx.oldValue()).assignments()));
            } finally {
                busyLock.leaveBusy();
            }
            return CompletableFuture.completedFuture(null);
        }
    });
    engine.start();
    DataRegion defaultDataRegion = engine.createDataRegion(dataStorageCfg.defaultRegion());
    dataRegions.put(DEFAULT_DATA_REGION_NAME, defaultDataRegion);
    defaultDataRegion.start();
}
Also used : IgniteTablesInternal(org.apache.ignite.internal.table.IgniteTablesInternal) ExtendedTableConfiguration(org.apache.ignite.internal.configuration.schema.ExtendedTableConfiguration) TableAlreadyExistsException(org.apache.ignite.lang.TableAlreadyExistsException) ConfigurationUtil.directProxy(org.apache.ignite.internal.configuration.util.ConfigurationUtil.directProxy) ConfigurationUtil.getByInternalId(org.apache.ignite.internal.configuration.util.ConfigurationUtil.getByInternalId) ExtendedTableChange(org.apache.ignite.internal.configuration.schema.ExtendedTableChange) IgniteLogger(org.apache.ignite.lang.IgniteLogger) RaftGroupService(org.apache.ignite.raft.client.service.RaftGroupService) Map(java.util.Map) DataRegion(org.apache.ignite.internal.storage.engine.DataRegion) TableNotFoundException(org.apache.ignite.lang.TableNotFoundException) Path(java.nio.file.Path) SchemaUtils(org.apache.ignite.internal.schema.SchemaUtils) ExtendedTableView(org.apache.ignite.internal.configuration.schema.ExtendedTableView) IgniteComponent(org.apache.ignite.internal.manager.IgniteComponent) SchemaConfiguration(org.apache.ignite.internal.configuration.schema.SchemaConfiguration) Int2ObjectOpenHashMap(it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap) InternalTableImpl(org.apache.ignite.internal.table.distributed.storage.InternalTableImpl) DataStorageConfiguration(org.apache.ignite.configuration.schemas.store.DataStorageConfiguration) TablesConfiguration(org.apache.ignite.configuration.schemas.table.TablesConfiguration) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Set(java.util.Set) DEFAULT_DATA_REGION_NAME(org.apache.ignite.configuration.schemas.store.DataStorageConfigurationSchema.DEFAULT_DATA_REGION_NAME) CompletionException(java.util.concurrent.CompletionException) Producer(org.apache.ignite.internal.manager.Producer) StorageEngine(org.apache.ignite.internal.storage.engine.StorageEngine) UUID(java.util.UUID) ConfigurationChangeException(org.apache.ignite.configuration.ConfigurationChangeException) Collectors(java.util.stream.Collectors) TxManager(org.apache.ignite.internal.tx.TxManager) TableView(org.apache.ignite.configuration.schemas.table.TableView) ClusterNode(org.apache.ignite.network.ClusterNode) Nullable(org.jetbrains.annotations.Nullable) List(java.util.List) IgniteInternalException(org.apache.ignite.lang.IgniteInternalException) IgniteStringFormatter(org.apache.ignite.lang.IgniteStringFormatter) NotNull(org.jetbrains.annotations.NotNull) InternalTable(org.apache.ignite.internal.table.InternalTable) IgniteException(org.apache.ignite.lang.IgniteException) Loza(org.apache.ignite.internal.raft.Loza) SchemaRegistryImpl(org.apache.ignite.internal.schema.registry.SchemaRegistryImpl) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) TableConfiguration(org.apache.ignite.configuration.schemas.table.TableConfiguration) ByteUtils(org.apache.ignite.internal.util.ByteUtils) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) SchemaSerializerImpl(org.apache.ignite.internal.schema.marshaller.schema.SchemaSerializerImpl) Function(java.util.function.Function) Supplier(java.util.function.Supplier) SchemaView(org.apache.ignite.internal.configuration.schema.SchemaView) VersionedRowStore(org.apache.ignite.internal.table.distributed.storage.VersionedRowStore) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) TableImpl(org.apache.ignite.internal.table.TableImpl) IgniteSpinBusyLock(org.apache.ignite.internal.util.IgniteSpinBusyLock) IgniteTables(org.apache.ignite.table.manager.IgniteTables) NoSuchElementException(java.util.NoSuchElementException) VersionedValue(org.apache.ignite.internal.causality.VersionedValue) TopologyService(org.apache.ignite.network.TopologyService) SchemaDescriptor(org.apache.ignite.internal.schema.SchemaDescriptor) TableEventParameters(org.apache.ignite.internal.table.event.TableEventParameters) Files(java.nio.file.Files) NamedListView(org.apache.ignite.configuration.NamedListView) NodeStoppingException(org.apache.ignite.lang.NodeStoppingException) IgniteObjectName(org.apache.ignite.internal.util.IgniteObjectName) IOException(java.io.IOException) Ignite(org.apache.ignite.Ignite) BaselineManager(org.apache.ignite.internal.baseline.BaselineManager) TableStorage(org.apache.ignite.internal.storage.engine.TableStorage) ConfigurationNamedListListener(org.apache.ignite.configuration.notifications.ConfigurationNamedListListener) NetworkAddress(org.apache.ignite.network.NetworkAddress) Consumer(java.util.function.Consumer) ConfigurationNotificationEvent(org.apache.ignite.configuration.notifications.ConfigurationNotificationEvent) TableEvent(org.apache.ignite.internal.table.event.TableEvent) AffinityUtils(org.apache.ignite.internal.affinity.AffinityUtils) EventListener(org.apache.ignite.internal.manager.EventListener) PartitionListener(org.apache.ignite.internal.table.distributed.raft.PartitionListener) Table(org.apache.ignite.table.Table) ConfigurationValidationException(org.apache.ignite.configuration.validation.ConfigurationValidationException) RocksDbStorageEngine(org.apache.ignite.internal.storage.rocksdb.RocksDbStorageEngine) TableChange(org.apache.ignite.configuration.schemas.table.TableChange) NodeStoppingException(org.apache.ignite.lang.NodeStoppingException) InternalTableImpl(org.apache.ignite.internal.table.distributed.storage.InternalTableImpl) TableImpl(org.apache.ignite.internal.table.TableImpl) ExtendedTableConfiguration(org.apache.ignite.internal.configuration.schema.ExtendedTableConfiguration) CompletableFuture(java.util.concurrent.CompletableFuture) ConfigurationNamedListListener(org.apache.ignite.configuration.notifications.ConfigurationNamedListListener) ConfigurationNotificationEvent(org.apache.ignite.configuration.notifications.ConfigurationNotificationEvent) List(java.util.List) ArrayList(java.util.ArrayList) UUID(java.util.UUID) ExtendedTableView(org.apache.ignite.internal.configuration.schema.ExtendedTableView) TableView(org.apache.ignite.configuration.schemas.table.TableView) ClusterNode(org.apache.ignite.network.ClusterNode) VersionedRowStore(org.apache.ignite.internal.table.distributed.storage.VersionedRowStore) ExtendedTableView(org.apache.ignite.internal.configuration.schema.ExtendedTableView) SchemaRegistryImpl(org.apache.ignite.internal.schema.registry.SchemaRegistryImpl) InternalTable(org.apache.ignite.internal.table.InternalTable) TableAlreadyExistsException(org.apache.ignite.lang.TableAlreadyExistsException) TableNotFoundException(org.apache.ignite.lang.TableNotFoundException) CompletionException(java.util.concurrent.CompletionException) ConfigurationChangeException(org.apache.ignite.configuration.ConfigurationChangeException) IgniteInternalException(org.apache.ignite.lang.IgniteInternalException) IgniteException(org.apache.ignite.lang.IgniteException) NoSuchElementException(java.util.NoSuchElementException) NodeStoppingException(org.apache.ignite.lang.NodeStoppingException) IOException(java.io.IOException) ConfigurationValidationException(org.apache.ignite.configuration.validation.ConfigurationValidationException) TableEventParameters(org.apache.ignite.internal.table.event.TableEventParameters) PartitionListener(org.apache.ignite.internal.table.distributed.raft.PartitionListener) InternalTableImpl(org.apache.ignite.internal.table.distributed.storage.InternalTableImpl) DataRegion(org.apache.ignite.internal.storage.engine.DataRegion)

Example 4 with Loza

use of org.apache.ignite.internal.raft.Loza in project ignite-3 by apache.

the class ItTxDistributedTestSingleNode method before.

/**
 * Initialize the test state.
 */
@Override
@BeforeEach
public void before() throws Exception {
    int nodes = nodes();
    int replicas = replicas();
    assertTrue(nodes > 0);
    assertTrue(replicas > 0);
    List<NetworkAddress> localAddresses = findLocalAddresses(NODE_PORT_BASE, NODE_PORT_BASE + nodes);
    var nodeFinder = new StaticNodeFinder(localAddresses);
    nodeFinder.findNodes().parallelStream().map(addr -> startNode(testInfo, addr.toString(), addr.port(), nodeFinder)).forEach(cluster::add);
    for (ClusterService node : cluster) {
        assertTrue(waitForTopology(node, nodes, 1000));
    }
    log.info("The cluster has been started");
    if (startClient()) {
        client = startNode(testInfo, "client", NODE_PORT_BASE - 1, nodeFinder);
        assertTrue(waitForTopology(client, nodes + 1, 1000));
        log.info("The client has been started");
    }
    // Start raft servers. Each raft server can hold multiple groups.
    raftServers = new HashMap<>(nodes);
    txManagers = new HashMap<>(nodes);
    executor = new ScheduledThreadPoolExecutor(20, new NamedThreadFactory(Loza.CLIENT_POOL_NAME));
    for (int i = 0; i < nodes; i++) {
        var raftSrv = new Loza(cluster.get(i), workDir);
        raftSrv.start();
        ClusterNode node = cluster.get(i).topologyService().localMember();
        raftServers.put(node, raftSrv);
        TableTxManagerImpl txMgr = new TableTxManagerImpl(cluster.get(i), new HeapLockManager());
        txMgr.start();
        txManagers.put(node, txMgr);
    }
    log.info("Raft servers have been started");
    final String accountsName = "accounts";
    final String customersName = "customers";
    UUID accTblId = UUID.randomUUID();
    UUID custTblId = UUID.randomUUID();
    accRaftClients = startTable(accountsName, accTblId);
    custRaftClients = startTable(customersName, custTblId);
    log.info("Partition groups have been started");
    TxManager txMgr;
    if (startClient()) {
        txMgr = new TxManagerImpl(client, new HeapLockManager());
    } else {
        // Collocated mode.
        txMgr = txManagers.get(accRaftClients.get(0).clusterService().topologyService().localMember());
    }
    assertNotNull(txMgr);
    igniteTransactions = new IgniteTransactionsImpl(txMgr);
    this.accounts = new TableImpl(new InternalTableImpl(accountsName, accTblId, accRaftClients, 1, NetworkAddress::toString, txMgr, Mockito.mock(TableStorage.class)), new DummySchemaManagerImpl(ACCOUNTS_SCHEMA));
    this.customers = new TableImpl(new InternalTableImpl(customersName, custTblId, custRaftClients, 1, NetworkAddress::toString, txMgr, Mockito.mock(TableStorage.class)), new DummySchemaManagerImpl(CUSTOMERS_SCHEMA));
    log.info("Tables have been started");
}
Also used : BeforeEach(org.junit.jupiter.api.BeforeEach) TxAbstractTest(org.apache.ignite.internal.table.TxAbstractTest) RaftMessagesFactory(org.apache.ignite.raft.jraft.RaftMessagesFactory) RaftGroupService(org.apache.ignite.raft.client.service.RaftGroupService) Map(java.util.Map) JraftServerImpl(org.apache.ignite.internal.raft.server.impl.JraftServerImpl) NodeFinder(org.apache.ignite.network.NodeFinder) Int2ObjectOpenHashMap(it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap) InternalTableImpl(org.apache.ignite.internal.table.distributed.storage.InternalTableImpl) Set(java.util.Set) ScheduledThreadPoolExecutor(java.util.concurrent.ScheduledThreadPoolExecutor) UUID(java.util.UUID) Collectors(java.util.stream.Collectors) TxManager(org.apache.ignite.internal.tx.TxManager) TestInfo(org.junit.jupiter.api.TestInfo) ClusterNode(org.apache.ignite.network.ClusterNode) List(java.util.List) StaticNodeFinder(org.apache.ignite.network.StaticNodeFinder) Assertions.assertTrue(org.junit.jupiter.api.Assertions.assertTrue) RaftGroupServiceImpl(org.apache.ignite.raft.jraft.rpc.impl.RaftGroupServiceImpl) ClusterServiceTestUtils.findLocalAddresses(org.apache.ignite.utils.ClusterServiceTestUtils.findLocalAddresses) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) Assertions.fail(org.junit.jupiter.api.Assertions.fail) ConcurrentHashMapPartitionStorage(org.apache.ignite.internal.storage.basic.ConcurrentHashMapPartitionStorage) Assertions.assertNotNull(org.junit.jupiter.api.Assertions.assertNotNull) RendezvousAffinityFunction(org.apache.ignite.internal.affinity.RendezvousAffinityFunction) ClusterServiceTestUtils(org.apache.ignite.utils.ClusterServiceTestUtils) Loza(org.apache.ignite.internal.raft.Loza) HashMap(java.util.HashMap) VersionedRowStore(org.apache.ignite.internal.table.distributed.storage.VersionedRowStore) HeapLockManager(org.apache.ignite.internal.tx.impl.HeapLockManager) TestScaleCubeClusterServiceFactory(org.apache.ignite.network.scalecube.TestScaleCubeClusterServiceFactory) TestUtils.waitForTopology(org.apache.ignite.raft.jraft.test.TestUtils.waitForTopology) TableImpl(org.apache.ignite.internal.table.TableImpl) IgniteUtils(org.apache.ignite.internal.util.IgniteUtils) DummySchemaManagerImpl(org.apache.ignite.internal.table.impl.DummySchemaManagerImpl) TxManagerImpl(org.apache.ignite.internal.tx.impl.TxManagerImpl) TableTxManagerImpl(org.apache.ignite.internal.table.distributed.TableTxManagerImpl) TableStorage(org.apache.ignite.internal.storage.engine.TableStorage) NetworkAddress(org.apache.ignite.network.NetworkAddress) TimeUnit(java.util.concurrent.TimeUnit) Mockito(org.mockito.Mockito) Peer(org.apache.ignite.raft.client.Peer) AfterEach(org.junit.jupiter.api.AfterEach) ClusterService(org.apache.ignite.network.ClusterService) PartitionListener(org.apache.ignite.internal.table.distributed.raft.PartitionListener) IgniteTransactionsImpl(org.apache.ignite.internal.tx.impl.IgniteTransactionsImpl) NamedThreadFactory(org.apache.ignite.internal.thread.NamedThreadFactory) Table(org.apache.ignite.table.Table) ClusterNode(org.apache.ignite.network.ClusterNode) TableStorage(org.apache.ignite.internal.storage.engine.TableStorage) StaticNodeFinder(org.apache.ignite.network.StaticNodeFinder) IgniteTransactionsImpl(org.apache.ignite.internal.tx.impl.IgniteTransactionsImpl) ScheduledThreadPoolExecutor(java.util.concurrent.ScheduledThreadPoolExecutor) NamedThreadFactory(org.apache.ignite.internal.thread.NamedThreadFactory) InternalTableImpl(org.apache.ignite.internal.table.distributed.storage.InternalTableImpl) TableImpl(org.apache.ignite.internal.table.TableImpl) TxManager(org.apache.ignite.internal.tx.TxManager) Loza(org.apache.ignite.internal.raft.Loza) DummySchemaManagerImpl(org.apache.ignite.internal.table.impl.DummySchemaManagerImpl) HeapLockManager(org.apache.ignite.internal.tx.impl.HeapLockManager) ClusterService(org.apache.ignite.network.ClusterService) InternalTableImpl(org.apache.ignite.internal.table.distributed.storage.InternalTableImpl) NetworkAddress(org.apache.ignite.network.NetworkAddress) TxManagerImpl(org.apache.ignite.internal.tx.impl.TxManagerImpl) TableTxManagerImpl(org.apache.ignite.internal.table.distributed.TableTxManagerImpl) TableTxManagerImpl(org.apache.ignite.internal.table.distributed.TableTxManagerImpl) UUID(java.util.UUID) BeforeEach(org.junit.jupiter.api.BeforeEach)

Example 5 with Loza

use of org.apache.ignite.internal.raft.Loza in project ignite-3 by apache.

the class ItTxDistributedTestSingleNode method startTable.

/**
 * Starts a table.
 *
 * @param name The name.
 * @param tblId Table id.
 * @return Groups map.
 */
protected Int2ObjectOpenHashMap<RaftGroupService> startTable(String name, UUID tblId) throws Exception {
    List<List<ClusterNode>> assignment = RendezvousAffinityFunction.assignPartitions(cluster.stream().map(node -> node.topologyService().localMember()).collect(Collectors.toList()), 1, replicas(), false, null);
    Int2ObjectOpenHashMap<RaftGroupService> clients = new Int2ObjectOpenHashMap<>();
    for (int p = 0; p < assignment.size(); p++) {
        List<ClusterNode> partNodes = assignment.get(p);
        String grpId = name + "-part-" + p;
        List<Peer> conf = partNodes.stream().map(n -> n.address()).map(Peer::new).collect(Collectors.toList());
        for (ClusterNode node : partNodes) {
            raftServers.get(node).prepareRaftGroup(grpId, partNodes, () -> new PartitionListener(tblId, new VersionedRowStore(new ConcurrentHashMapPartitionStorage(), txManagers.get(node))));
        }
        if (startClient()) {
            RaftGroupService service = RaftGroupServiceImpl.start(grpId, client, FACTORY, 10_000, conf, true, 200, executor).get(5, TimeUnit.SECONDS);
            clients.put(p, service);
        } else {
            // Create temporary client to find a leader address.
            ClusterService tmpSvc = raftServers.values().stream().findFirst().get().service();
            RaftGroupService service = RaftGroupServiceImpl.start(grpId, tmpSvc, FACTORY, 10_000, conf, true, 200, executor).get(5, TimeUnit.SECONDS);
            Peer leader = service.leader();
            service.shutdown();
            Loza leaderSrv = raftServers.get(tmpSvc.topologyService().getByAddress(leader.address()));
            RaftGroupService leaderClusterSvc = RaftGroupServiceImpl.start(grpId, leaderSrv.service(), FACTORY, 10_000, conf, true, 200, executor).get(5, TimeUnit.SECONDS);
            clients.put(p, leaderClusterSvc);
        }
    }
    return clients;
}
Also used : ClusterNode(org.apache.ignite.network.ClusterNode) VersionedRowStore(org.apache.ignite.internal.table.distributed.storage.VersionedRowStore) Int2ObjectOpenHashMap(it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap) ConcurrentHashMapPartitionStorage(org.apache.ignite.internal.storage.basic.ConcurrentHashMapPartitionStorage) RaftGroupService(org.apache.ignite.raft.client.service.RaftGroupService) Peer(org.apache.ignite.raft.client.Peer) Loza(org.apache.ignite.internal.raft.Loza) PartitionListener(org.apache.ignite.internal.table.distributed.raft.PartitionListener) ClusterService(org.apache.ignite.network.ClusterService) List(java.util.List) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList)

Aggregations

Loza (org.apache.ignite.internal.raft.Loza)7 ClusterNode (org.apache.ignite.network.ClusterNode)7 Int2ObjectOpenHashMap (it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap)6 List (java.util.List)6 Map (java.util.Map)6 RaftGroupService (org.apache.ignite.raft.client.service.RaftGroupService)6 HashMap (java.util.HashMap)5 Set (java.util.Set)5 Collectors (java.util.stream.Collectors)5 PartitionListener (org.apache.ignite.internal.table.distributed.raft.PartitionListener)5 VersionedRowStore (org.apache.ignite.internal.table.distributed.storage.VersionedRowStore)5 UUID (java.util.UUID)4 CopyOnWriteArrayList (java.util.concurrent.CopyOnWriteArrayList)3 JraftServerImpl (org.apache.ignite.internal.raft.server.impl.JraftServerImpl)3 ConcurrentHashMapPartitionStorage (org.apache.ignite.internal.storage.basic.ConcurrentHashMapPartitionStorage)3 TableStorage (org.apache.ignite.internal.storage.engine.TableStorage)3 TableImpl (org.apache.ignite.internal.table.TableImpl)3 InternalTableImpl (org.apache.ignite.internal.table.distributed.storage.InternalTableImpl)3 TxManager (org.apache.ignite.internal.tx.TxManager)3 ClusterService (org.apache.ignite.network.ClusterService)3