Search in sources :

Example 6 with Connection

use of com.hazelcast.internal.nio.Connection in project hazelcast by hazelcast.

the class Networking method createFlowControlPacket.

private Map<Address, byte[]> createFlowControlPacket() throws IOException {
    class MemberData {

        final BufferObjectDataOutput output = createObjectDataOutput(nodeEngine, lastFlowPacketSize);

        final Connection memberConnection;

        Long startedExecutionId;

        MemberData(Address address) {
            memberConnection = getMemberConnection(nodeEngine, address);
        }
    }
    Map<Address, MemberData> res = new HashMap<>();
    for (ExecutionContext execCtx : jobExecutionService.getExecutionContexts()) {
        Map<SenderReceiverKey, ReceiverTasklet> receiverMap = execCtx.receiverMap();
        if (receiverMap == null) {
            continue;
        }
        for (Entry<SenderReceiverKey, ReceiverTasklet> en : receiverMap.entrySet()) {
            assert !en.getKey().address.equals(nodeEngine.getThisAddress());
            MemberData md = res.computeIfAbsent(en.getKey().address, address -> new MemberData(address));
            if (md.startedExecutionId == null) {
                md.startedExecutionId = execCtx.executionId();
                md.output.writeLong(md.startedExecutionId);
            }
            assert en.getKey().vertexId != TERMINAL_VERTEX_ID;
            md.output.writeInt(en.getKey().vertexId);
            md.output.writeInt(en.getKey().ordinal);
            md.output.writeInt(en.getValue().updateAndGetSendSeqLimitCompressed(md.memberConnection));
        }
        for (MemberData md : res.values()) {
            if (md.startedExecutionId != null) {
                // write a mark to terminate values for an execution
                md.output.writeInt(TERMINAL_VERTEX_ID);
                md.startedExecutionId = null;
            }
        }
    }
    for (MemberData md : res.values()) {
        assert md.output.position() > 0;
        // write a mark to terminate all executions
        // Execution IDs are generated using Flake ID generator and those are >0 normally, we
        // use MIN_VALUE as a terminator.
        md.output.writeLong(TERMINAL_EXECUTION_ID);
    }
    // finalize the packets
    int maxSize = 0;
    for (Entry<Address, MemberData> entry : res.entrySet()) {
        byte[] data = entry.getValue().output.toByteArray();
        // we break type safety to avoid creating a new map, we replace the values to a different type in place
        @SuppressWarnings({ "unchecked", "rawtypes" }) Entry<Address, byte[]> entry1 = (Entry) entry;
        entry1.setValue(data);
        if (data.length > maxSize) {
            maxSize = data.length;
        }
    }
    lastFlowPacketSize = maxSize;
    return (Map) res;
}
Also used : Address(com.hazelcast.cluster.Address) HashMap(java.util.HashMap) ImdgUtil.getMemberConnection(com.hazelcast.jet.impl.util.ImdgUtil.getMemberConnection) Connection(com.hazelcast.internal.nio.Connection) ReceiverTasklet(com.hazelcast.jet.impl.execution.ReceiverTasklet) BufferObjectDataOutput(com.hazelcast.internal.nio.BufferObjectDataOutput) Entry(java.util.Map.Entry) ExecutionContext(com.hazelcast.jet.impl.execution.ExecutionContext) SenderReceiverKey(com.hazelcast.jet.impl.execution.ExecutionContext.SenderReceiverKey) HashMap(java.util.HashMap) Map(java.util.Map)

Example 7 with Connection

use of com.hazelcast.internal.nio.Connection in project hazelcast by hazelcast.

the class SqlClientService method fetchAsync.

public void fetchAsync(Connection connection, QueryId queryId, int cursorBufferSize, SqlClientResult res) {
    ClientMessage requestMessage = SqlFetchCodec.encodeRequest(queryId, cursorBufferSize);
    ClientInvocationFuture future = invokeAsync(requestMessage, connection);
    future.whenComplete(withTryCatch(logger, (message, error) -> handleFetchResponse(connection, res, message, error)));
}
Also used : HazelcastClientInstanceImpl(com.hazelcast.client.impl.clientside.HazelcastClientInstanceImpl) ClientConnection(com.hazelcast.client.impl.connection.ClientConnection) Member(com.hazelcast.cluster.Member) SqlStatement(com.hazelcast.sql.SqlStatement) CompletableFuture(java.util.concurrent.CompletableFuture) ConnectionType(com.hazelcast.internal.nio.ConnectionType) SqlFetchCodec(com.hazelcast.client.impl.protocol.codec.SqlFetchCodec) SqlRowMetadata(com.hazelcast.sql.SqlRowMetadata) ArrayList(java.util.ArrayList) ILogger(com.hazelcast.logging.ILogger) InternalSerializationService(com.hazelcast.internal.serialization.InternalSerializationService) QueryUtils(com.hazelcast.sql.impl.QueryUtils) ClientInvocation(com.hazelcast.client.impl.spi.impl.ClientInvocation) Nonnull(javax.annotation.Nonnull) QueryException(com.hazelcast.sql.impl.QueryException) SqlService(com.hazelcast.sql.SqlService) HazelcastSqlException(com.hazelcast.sql.HazelcastSqlException) Connection(com.hazelcast.internal.nio.Connection) Data(com.hazelcast.internal.serialization.Data) SqlCloseCodec(com.hazelcast.client.impl.protocol.codec.SqlCloseCodec) SqlMappingDdlCodec(com.hazelcast.client.impl.protocol.codec.SqlMappingDdlCodec) UUID(java.util.UUID) QueryId(com.hazelcast.sql.impl.QueryId) Preconditions.checkNotNull(com.hazelcast.internal.util.Preconditions.checkNotNull) List(java.util.List) ClientDelegatingFuture(com.hazelcast.client.impl.ClientDelegatingFuture) ClientInvocationFuture(com.hazelcast.client.impl.spi.impl.ClientInvocationFuture) SqlResult(com.hazelcast.sql.SqlResult) AccessControlException(java.security.AccessControlException) ExceptionUtil.withTryCatch(com.hazelcast.internal.util.ExceptionUtil.withTryCatch) SqlExecuteCodec(com.hazelcast.client.impl.protocol.codec.SqlExecuteCodec) SqlErrorCode(com.hazelcast.sql.impl.SqlErrorCode) ClientMessage(com.hazelcast.client.impl.protocol.ClientMessage) ClientMessage(com.hazelcast.client.impl.protocol.ClientMessage) ClientInvocationFuture(com.hazelcast.client.impl.spi.impl.ClientInvocationFuture)

Example 8 with Connection

use of com.hazelcast.internal.nio.Connection in project hazelcast by hazelcast.

the class TcpClientConnectionTest method destroyConnection_whenDestroyedMultipleTimes_thenListenerRemoveCalledOnce.

@Test
public void destroyConnection_whenDestroyedMultipleTimes_thenListenerRemoveCalledOnce() {
    HazelcastInstance server = hazelcastFactory.newHazelcastInstance();
    HazelcastInstance client = hazelcastFactory.newHazelcastClient();
    HazelcastClientInstanceImpl clientImpl = ClientTestUtil.getHazelcastClientInstanceImpl(client);
    ClientConnectionManager connectionManager = clientImpl.getConnectionManager();
    final CountingConnectionListener listener = new CountingConnectionListener();
    connectionManager.addConnectionListener(listener);
    UUID serverUuid = server.getCluster().getLocalMember().getUuid();
    final Connection connectionToServer = connectionManager.getConnection(serverUuid);
    ReconnectListener reconnectListener = new ReconnectListener();
    clientImpl.getLifecycleService().addLifecycleListener(reconnectListener);
    connectionToServer.close(null, null);
    assertOpenEventually(reconnectListener.reconnectedLatch);
    connectionToServer.close(null, null);
    assertEqualsEventually(() -> listener.connectionRemovedCount.get(), 1);
    sleepMillis(100);
    assertEquals("connection removed should be called only once", 1, listener.connectionRemovedCount.get());
}
Also used : HazelcastInstance(com.hazelcast.core.HazelcastInstance) Connection(com.hazelcast.internal.nio.Connection) HazelcastClientInstanceImpl(com.hazelcast.client.impl.clientside.HazelcastClientInstanceImpl) UUID(java.util.UUID) ClientConnectionManager(com.hazelcast.client.impl.connection.ClientConnectionManager) ParallelJVMTest(com.hazelcast.test.annotation.ParallelJVMTest) QuickTest(com.hazelcast.test.annotation.QuickTest) Test(org.junit.Test)

Example 9 with Connection

use of com.hazelcast.internal.nio.Connection in project hazelcast by hazelcast.

the class ExecutionPlan method initialize.

/**
 * A method called on the members as part of the InitExecutionOperation.
 * Creates tasklets, inboxes/outboxes and connects these to make them ready
 * for a later StartExecutionOperation.
 */
public void initialize(NodeEngineImpl nodeEngine, long jobId, long executionId, @Nonnull SnapshotContext snapshotContext, ConcurrentHashMap<String, File> tempDirectories, InternalSerializationService jobSerializationService) {
    this.nodeEngine = nodeEngine;
    this.jobClassLoaderService = ((JetServiceBackend) nodeEngine.getService(JetServiceBackend.SERVICE_NAME)).getJobClassLoaderService();
    this.executionId = executionId;
    initProcSuppliers(jobId, tempDirectories, jobSerializationService);
    initDag(jobSerializationService);
    this.ptionArrgmt = new PartitionArrangement(partitionAssignment, nodeEngine.getThisAddress());
    Set<Integer> higherPriorityVertices = VertexDef.getHigherPriorityVertices(vertices);
    for (Address destAddr : remoteMembers.get()) {
        Connection conn = getMemberConnection(nodeEngine, destAddr);
        if (conn == null) {
            throw new TopologyChangedException("no connection to job participant: " + destAddr);
        }
        memberConnections.put(destAddr, conn);
    }
    for (VertexDef vertex : vertices) {
        ClassLoader processorClassLoader = isLightJob ? null : jobClassLoaderService.getProcessorClassLoader(jobId, vertex.name());
        Collection<? extends Processor> processors = doWithClassLoader(processorClassLoader, () -> createProcessors(vertex, vertex.localParallelism()));
        String jobPrefix = prefix(jobConfig.getName(), jobId, vertex.name());
        // create StoreSnapshotTasklet and the queues to it
        ConcurrentConveyor<Object> ssConveyor = null;
        if (!isLightJob) {
            // Note that we create the snapshot queues for all non-light jobs, even if they don't have
            // processing guarantee enabled, because in EE one can request a snapshot also for
            // non-snapshotted jobs.
            @SuppressWarnings("unchecked") QueuedPipe<Object>[] snapshotQueues = new QueuedPipe[vertex.localParallelism()];
            Arrays.setAll(snapshotQueues, i -> new OneToOneConcurrentArrayQueue<>(SNAPSHOT_QUEUE_SIZE));
            ssConveyor = ConcurrentConveyor.concurrentConveyor(null, snapshotQueues);
            ILogger storeSnapshotLogger = prefixedLogger(nodeEngine.getLogger(StoreSnapshotTasklet.class), jobPrefix);
            StoreSnapshotTasklet ssTasklet = new StoreSnapshotTasklet(snapshotContext, ConcurrentInboundEdgeStream.create(ssConveyor, 0, 0, true, jobPrefix + "/ssFrom", null), new AsyncSnapshotWriterImpl(nodeEngine, snapshotContext, vertex.name(), memberIndex, memberCount, jobSerializationService), storeSnapshotLogger, vertex.name(), higherPriorityVertices.contains(vertex.vertexId()));
            tasklets.add(ssTasklet);
        }
        int localProcessorIdx = 0;
        for (Processor processor : processors) {
            int globalProcessorIndex = memberIndex * vertex.localParallelism() + localProcessorIdx;
            String processorPrefix = prefix(jobConfig.getName(), jobId, vertex.name(), globalProcessorIndex);
            ILogger logger = prefixedLogger(nodeEngine.getLogger(processor.getClass()), processorPrefix);
            ProcCtx context = new ProcCtx(nodeEngine, jobId, executionId, getJobConfig(), logger, vertex.name(), localProcessorIdx, globalProcessorIndex, isLightJob, partitionAssignment, vertex.localParallelism(), memberIndex, memberCount, tempDirectories, jobSerializationService, subject, processorClassLoader);
            // createOutboundEdgeStreams() populates localConveyorMap and edgeSenderConveyorMap.
            // Also populates instance fields: senderMap, receiverMap, tasklets.
            List<OutboundEdgeStream> outboundStreams = createOutboundEdgeStreams(vertex, localProcessorIdx, jobPrefix, jobSerializationService);
            List<InboundEdgeStream> inboundStreams = createInboundEdgeStreams(vertex, localProcessorIdx, jobPrefix, globalProcessorIndex);
            OutboundCollector snapshotCollector = ssConveyor == null ? null : new ConveyorCollector(ssConveyor, localProcessorIdx, null);
            // vertices which are only used for snapshot restore will not be marked as "source=true" in metrics
            // also do not consider snapshot restore edges for determining source tag
            boolean isSource = vertex.inboundEdges().stream().allMatch(EdgeDef::isSnapshotRestoreEdge) && !vertex.isSnapshotVertex();
            ProcessorTasklet processorTasklet = new ProcessorTasklet(context, nodeEngine.getExecutionService().getExecutor(TASKLET_INIT_CLOSE_EXECUTOR_NAME), jobSerializationService, processor, inboundStreams, outboundStreams, snapshotContext, snapshotCollector, isSource);
            tasklets.add(processorTasklet);
            this.processors.add(processor);
            localProcessorIdx++;
        }
    }
    List<ReceiverTasklet> allReceivers = receiverMap.values().stream().flatMap(o -> o.values().stream()).flatMap(a -> a.values().stream()).collect(toList());
    tasklets.addAll(allReceivers);
}
Also used : Address(com.hazelcast.cluster.Address) ImdgUtil.getMemberConnection(com.hazelcast.jet.impl.util.ImdgUtil.getMemberConnection) Arrays(java.util.Arrays) SnapshotContext(com.hazelcast.jet.impl.execution.SnapshotContext) Collections.unmodifiableList(java.util.Collections.unmodifiableList) ConcurrentConveyor.concurrentConveyor(com.hazelcast.internal.util.concurrent.ConcurrentConveyor.concurrentConveyor) Processor(com.hazelcast.jet.core.Processor) OutboundCollector.compositeCollector(com.hazelcast.jet.impl.execution.OutboundCollector.compositeCollector) ObjectWithPartitionId(com.hazelcast.jet.impl.util.ObjectWithPartitionId) ProcessorTasklet(com.hazelcast.jet.impl.execution.ProcessorTasklet) ImdgUtil(com.hazelcast.jet.impl.util.ImdgUtil) Collectors.toMap(java.util.stream.Collectors.toMap) ConcurrentConveyor(com.hazelcast.internal.util.concurrent.ConcurrentConveyor) Map(java.util.Map) Util.memoize(com.hazelcast.jet.impl.util.Util.memoize) SerializationServiceAware(com.hazelcast.internal.serialization.SerializationServiceAware) DISTRIBUTE_TO_ALL(com.hazelcast.jet.core.Edge.DISTRIBUTE_TO_ALL) ObjectDataInput(com.hazelcast.nio.ObjectDataInput) TASKLET_INIT_CLOSE_EXECUTOR_NAME(com.hazelcast.jet.impl.execution.TaskletExecutionService.TASKLET_INIT_CLOSE_EXECUTOR_NAME) InboundEdgeStream(com.hazelcast.jet.impl.execution.InboundEdgeStream) PrefixedLogger.prefix(com.hazelcast.jet.impl.util.PrefixedLogger.prefix) Collection(java.util.Collection) IPartitionService(com.hazelcast.internal.partition.IPartitionService) JobConfig(com.hazelcast.jet.config.JobConfig) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Set(java.util.Set) ConcurrentInboundEdgeStream(com.hazelcast.jet.impl.execution.ConcurrentInboundEdgeStream) Collectors(java.util.stream.Collectors) Objects(java.util.Objects) List(java.util.List) Stream(java.util.stream.Stream) DEFAULT_QUEUE_SIZE(com.hazelcast.jet.config.EdgeConfig.DEFAULT_QUEUE_SIZE) StoreSnapshotTasklet(com.hazelcast.jet.impl.execution.StoreSnapshotTasklet) ObjectDataOutput(com.hazelcast.nio.ObjectDataOutput) TopologyChangedException(com.hazelcast.jet.core.TopologyChangedException) IntStream(java.util.stream.IntStream) ComparatorEx(com.hazelcast.function.ComparatorEx) IdentifiedDataSerializable(com.hazelcast.nio.serialization.IdentifiedDataSerializable) ImdgUtil.writeList(com.hazelcast.jet.impl.util.ImdgUtil.writeList) OutboundEdgeStream(com.hazelcast.jet.impl.execution.OutboundEdgeStream) RoutingPolicy(com.hazelcast.jet.core.Edge.RoutingPolicy) Util.doWithClassLoader(com.hazelcast.jet.impl.util.Util.doWithClassLoader) SenderTasklet(com.hazelcast.jet.impl.execution.SenderTasklet) HashMap(java.util.HashMap) Supplier(java.util.function.Supplier) ProcSupplierCtx(com.hazelcast.jet.impl.execution.init.Contexts.ProcSupplierCtx) ArrayList(java.util.ArrayList) PrefixedLogger.prefixedLogger(com.hazelcast.jet.impl.util.PrefixedLogger.prefixedLogger) JetException(com.hazelcast.jet.JetException) ConveyorCollector(com.hazelcast.jet.impl.execution.ConveyorCollector) ReceiverTasklet(com.hazelcast.jet.impl.execution.ReceiverTasklet) ILogger(com.hazelcast.logging.ILogger) InternalSerializationService(com.hazelcast.internal.serialization.InternalSerializationService) Nonnull(javax.annotation.Nonnull) ProcessorSupplier(com.hazelcast.jet.core.ProcessorSupplier) QueuedPipe(com.hazelcast.internal.util.concurrent.QueuedPipe) IntFunction(java.util.function.IntFunction) JetConfig(com.hazelcast.jet.config.JetConfig) NodeEngineImpl(com.hazelcast.spi.impl.NodeEngineImpl) OneToOneConcurrentArrayQueue(com.hazelcast.internal.util.concurrent.OneToOneConcurrentArrayQueue) Connection(com.hazelcast.internal.nio.Connection) Tasklet(com.hazelcast.jet.impl.execution.Tasklet) ProcCtx(com.hazelcast.jet.impl.execution.init.Contexts.ProcCtx) AsyncSnapshotWriterImpl(com.hazelcast.jet.impl.util.AsyncSnapshotWriterImpl) IOException(java.io.IOException) ConveyorCollectorWithPartition(com.hazelcast.jet.impl.execution.ConveyorCollectorWithPartition) Subject(javax.security.auth.Subject) File(java.io.File) ImdgUtil.readList(com.hazelcast.jet.impl.util.ImdgUtil.readList) Collectors.toList(java.util.stream.Collectors.toList) OutboundCollector(com.hazelcast.jet.impl.execution.OutboundCollector) JobClassLoaderService(com.hazelcast.jet.impl.JobClassLoaderService) ProcessingGuarantee(com.hazelcast.jet.config.ProcessingGuarantee) JetServiceBackend(com.hazelcast.jet.impl.JetServiceBackend) Processor(com.hazelcast.jet.core.Processor) Address(com.hazelcast.cluster.Address) AsyncSnapshotWriterImpl(com.hazelcast.jet.impl.util.AsyncSnapshotWriterImpl) OutboundCollector(com.hazelcast.jet.impl.execution.OutboundCollector) ConveyorCollector(com.hazelcast.jet.impl.execution.ConveyorCollector) ProcCtx(com.hazelcast.jet.impl.execution.init.Contexts.ProcCtx) InboundEdgeStream(com.hazelcast.jet.impl.execution.InboundEdgeStream) ConcurrentInboundEdgeStream(com.hazelcast.jet.impl.execution.ConcurrentInboundEdgeStream) Util.doWithClassLoader(com.hazelcast.jet.impl.util.Util.doWithClassLoader) ILogger(com.hazelcast.logging.ILogger) StoreSnapshotTasklet(com.hazelcast.jet.impl.execution.StoreSnapshotTasklet) ProcessorTasklet(com.hazelcast.jet.impl.execution.ProcessorTasklet) ImdgUtil.getMemberConnection(com.hazelcast.jet.impl.util.ImdgUtil.getMemberConnection) Connection(com.hazelcast.internal.nio.Connection) OutboundEdgeStream(com.hazelcast.jet.impl.execution.OutboundEdgeStream) ReceiverTasklet(com.hazelcast.jet.impl.execution.ReceiverTasklet) TopologyChangedException(com.hazelcast.jet.core.TopologyChangedException) QueuedPipe(com.hazelcast.internal.util.concurrent.QueuedPipe)

Example 10 with Connection

use of com.hazelcast.internal.nio.Connection in project hazelcast by hazelcast.

the class SqlClientExecuteCloseRaceTest method testExecuteClose.

@Test
public void testExecuteClose() {
    QueryId queryId = QueryId.create(UUID.randomUUID());
    // Send "execute"
    Connection connection = clientService.getQueryConnection();
    ClientMessage executeResponse = sendExecuteRequest(connection, queryId);
    checkExecuteResponse(executeResponse, true);
    assertEquals(1, memberService.getInternalService().getClientStateRegistry().getCursorCount());
    // Send "close"
    ClientMessage closeRequest = SqlCloseCodec.encodeRequest(queryId);
    clientService.invokeOnConnection(connection, closeRequest);
    assertEquals(0, memberService.getInternalService().getClientStateRegistry().getCursorCount());
}
Also used : QueryId(com.hazelcast.sql.impl.QueryId) Connection(com.hazelcast.internal.nio.Connection) ClientMessage(com.hazelcast.client.impl.protocol.ClientMessage) ParallelJVMTest(com.hazelcast.test.annotation.ParallelJVMTest) QuickTest(com.hazelcast.test.annotation.QuickTest) Test(org.junit.Test)

Aggregations

Connection (com.hazelcast.internal.nio.Connection)41 Test (org.junit.Test)14 QuickTest (com.hazelcast.test.annotation.QuickTest)11 ClientMessage (com.hazelcast.client.impl.protocol.ClientMessage)8 ServerConnection (com.hazelcast.internal.server.ServerConnection)7 ParallelJVMTest (com.hazelcast.test.annotation.ParallelJVMTest)7 ClientConnection (com.hazelcast.client.impl.connection.ClientConnection)6 Address (com.hazelcast.cluster.Address)6 HazelcastClientInstanceImpl (com.hazelcast.client.impl.clientside.HazelcastClientInstanceImpl)5 Member (com.hazelcast.cluster.Member)5 HazelcastInstance (com.hazelcast.core.HazelcastInstance)5 ConnectionListener (com.hazelcast.internal.nio.ConnectionListener)5 ClientConnectionManager (com.hazelcast.client.impl.connection.ClientConnectionManager)4 ILogger (com.hazelcast.logging.ILogger)4 QueryId (com.hazelcast.sql.impl.QueryId)4 Map (java.util.Map)4 UUID (java.util.UUID)4 ClientInvocation (com.hazelcast.client.impl.spi.impl.ClientInvocation)3 TargetDisconnectedException (com.hazelcast.spi.exception.TargetDisconnectedException)3 IOException (java.io.IOException)3