Search in sources :

Example 6 with WireCommand

use of io.pravega.shared.protocol.netty.WireCommand in project pravega by pravega.

the class CommandEncoderTest method testExactBatch.

@Test
public void testExactBatch() throws IOException {
    AppendBatchSizeTracker batchSizeTracker = new FixedBatchSizeTracker(100);
    DecodingOutputStream output = new DecodingOutputStream();
    PravegaNodeUri endpoint = new PravegaNodeUri("localhost", SERVICE_PORT);
    CommandEncoder commandEncoder = new CommandEncoder(x -> batchSizeTracker, null, output, null, endpoint);
    UUID writerId = UUID.randomUUID();
    WireCommand setupAppend = new WireCommands.SetupAppend(0, writerId, "seg", "");
    commandEncoder.write(setupAppend);
    assertEquals(output.decoded.remove(0), setupAppend);
    ByteBuf data = Unpooled.wrappedBuffer(new byte[100]);
    Event event = new WireCommands.Event(data);
    Append append = new Append("seg", writerId, 1, event, 0);
    commandEncoder.write(append);
    AppendBlock block = (AppendBlock) output.decoded.remove(0);
    assertEquals(108, block.getData().readableBytes());
    AppendBlockEnd blockEnd = (AppendBlockEnd) output.decoded.remove(0);
    assertEquals(writerId, blockEnd.getWriterId());
    assertEquals(108, blockEnd.getSizeOfWholeEvents());
    assertEquals(0, blockEnd.getData().readableBytes());
    assertEquals(1, blockEnd.getNumEvents());
}
Also used : WireCommand(io.pravega.shared.protocol.netty.WireCommand) AppendBatchSizeTracker(io.pravega.shared.protocol.netty.AppendBatchSizeTracker) ByteBuf(io.netty.buffer.ByteBuf) AppendBlock(io.pravega.shared.protocol.netty.WireCommands.AppendBlock) Append(io.pravega.shared.protocol.netty.Append) PravegaNodeUri(io.pravega.shared.protocol.netty.PravegaNodeUri) AppendBlockEnd(io.pravega.shared.protocol.netty.WireCommands.AppendBlockEnd) Event(io.pravega.shared.protocol.netty.WireCommands.Event) UUID(java.util.UUID) Test(org.junit.Test)

Example 7 with WireCommand

use of io.pravega.shared.protocol.netty.WireCommand in project pravega by pravega.

the class CommandEncoderTest method testOverBatchSize.

@Test
public void testOverBatchSize() throws IOException {
    AppendBatchSizeTracker batchSizeTracker = new FixedBatchSizeTracker(100);
    DecodingOutputStream output = new DecodingOutputStream();
    PravegaNodeUri endpoint = new PravegaNodeUri("localhost", SERVICE_PORT);
    CommandEncoder commandEncoder = new CommandEncoder(x -> batchSizeTracker, null, output, null, endpoint);
    UUID writerId = UUID.randomUUID();
    WireCommand setupAppend = new WireCommands.SetupAppend(0, writerId, "seg", "");
    commandEncoder.write(setupAppend);
    assertEquals(output.decoded.remove(0), setupAppend);
    ByteBuf data = Unpooled.wrappedBuffer(new byte[200]);
    Event event = new WireCommands.Event(data);
    Append append = new Append("seg", writerId, 1, event, 0);
    commandEncoder.write(append);
    AppendBlock block = (AppendBlock) output.decoded.remove(0);
    assertEquals(208, block.getData().readableBytes());
    AppendBlockEnd blockEnd = (AppendBlockEnd) output.decoded.remove(0);
    assertEquals(writerId, blockEnd.getWriterId());
    assertEquals(208, blockEnd.getSizeOfWholeEvents());
    assertEquals(0, blockEnd.getData().readableBytes());
    assertEquals(1, blockEnd.getNumEvents());
}
Also used : WireCommand(io.pravega.shared.protocol.netty.WireCommand) AppendBatchSizeTracker(io.pravega.shared.protocol.netty.AppendBatchSizeTracker) ByteBuf(io.netty.buffer.ByteBuf) AppendBlock(io.pravega.shared.protocol.netty.WireCommands.AppendBlock) Append(io.pravega.shared.protocol.netty.Append) PravegaNodeUri(io.pravega.shared.protocol.netty.PravegaNodeUri) AppendBlockEnd(io.pravega.shared.protocol.netty.WireCommands.AppendBlockEnd) Event(io.pravega.shared.protocol.netty.WireCommands.Event) UUID(java.util.UUID) Test(org.junit.Test)

Example 8 with WireCommand

use of io.pravega.shared.protocol.netty.WireCommand in project pravega by pravega.

the class TableSegmentImplTest method testGetALotOfKeys.

/**
 * Tests the {@link TableSegmentImpl#get} method when the response coming back from the server is truncated.
 * Connection reset failures are not tested here; they're checked in {@link #testReconnect()}.
 */
@Test
public void testGetALotOfKeys() throws Exception {
    // Manual calculation of TableSegmentImpl.MAX_GET_KEY_BATCH_SIZE.
    val expectedBatchKeyLength = 15;
    val requestKeys = LongStream.range(0, 61).mapToObj(l -> l * 100).collect(Collectors.toList());
    val expectedEntries = requestKeys.stream().map(key -> versionedEntry(key, key.toString(), key)).collect(Collectors.toList());
    // This key does not exist.
    expectedEntries.set(expectedEntries.size() - 1, null);
    val expectedWireKeys = toWireKeys(requestKeys.stream().map(this::buf).map(TableSegmentKey::unversioned).collect(Collectors.toList()));
    // Calculate the expected sent/receive ranges.
    // Key: Start Index, Value: End Index.
    val expectedRanges = new ArrayList<Map.Entry<Integer, Integer>>();
    int idx = 0;
    while (idx < expectedEntries.size()) {
        val expectedLength = Math.min(expectedBatchKeyLength, expectedEntries.size() - idx);
        expectedRanges.add(new AbstractMap.SimpleImmutableEntry<>(idx, idx + expectedLength));
        idx += expectedLength;
    }
    @Cleanup val context = new TestContext();
    // Initiate a get request.
    val getResult = context.segment.get(requestKeys.stream().map(this::buf).iterator());
    // Capture all the requests sent over the wire and verify that we've sent as many as we expected to.
    val sentWireCommands = context.getConnection().getLastSentWireCommands(expectedRanges.size());
    Assert.assertEquals(expectedRanges.size(), sentWireCommands.size());
    // Validate the sent keys and send appropriate responses.
    for (int i = 0; i < expectedRanges.size(); i++) {
        int rangeStart = expectedRanges.get(i).getKey();
        int rangeEnd = expectedRanges.get(i).getValue();
        val expectedSentKeys = expectedWireKeys.subList(rangeStart, rangeEnd);
        val wireCommand = (WireCommands.ReadTable) sentWireCommands.get(i);
        checkWireCommand(expectedSentKeys, wireCommand.getKeys());
        val returnedKeys = requestKeys.subList(rangeStart, rangeEnd);
        val returnedEntries = expectedEntries.subList(rangeStart, rangeEnd);
        val replyWireEntries = toWireEntries(returnedEntries, returnedKeys);
        context.sendReply(new WireCommands.TableRead(wireCommand.getRequestId(), SEGMENT.getScopedName(), replyWireEntries));
    }
    // Validate final result.
    val actualEntries = getResult.get(SHORT_TIMEOUT, TimeUnit.MILLISECONDS);
    AssertExtensions.assertListEquals("Unexpected return value", expectedEntries, actualEntries, this::entryEquals);
}
Also used : lombok.val(lombok.val) Arrays(java.util.Arrays) NoSuchKeyException(io.pravega.client.tables.NoSuchKeyException) AssertExtensions(io.pravega.test.common.AssertExtensions) RequiredArgsConstructor(lombok.RequiredArgsConstructor) Cleanup(lombok.Cleanup) Unpooled(io.netty.buffer.Unpooled) MockController(io.pravega.client.stream.mock.MockController) ClientConnection(io.pravega.client.connection.impl.ClientConnection) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Map(java.util.Map) PravegaNodeUri(io.pravega.shared.protocol.netty.PravegaNodeUri) IteratorItem(io.pravega.client.tables.IteratorItem) Request(io.pravega.shared.protocol.netty.Request) DelegationTokenProviderFactory(io.pravega.client.security.auth.DelegationTokenProviderFactory) Collectors(java.util.stream.Collectors) RetriesExhaustedException(io.pravega.common.util.RetriesExhaustedException) List(java.util.List) ThreadPooledTestSuite(io.pravega.test.common.ThreadPooledTestSuite) TestUtils(io.pravega.test.common.TestUtils) BadKeyVersionException(io.pravega.client.tables.BadKeyVersionException) IntStream(java.util.stream.IntStream) Segment(io.pravega.client.segment.impl.Segment) Setter(lombok.Setter) Getter(lombok.Getter) ConnectionFailedException(io.pravega.shared.protocol.netty.ConnectionFailedException) Reply(io.pravega.shared.protocol.netty.Reply) Exceptions(io.pravega.common.Exceptions) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) CompletableFuture(java.util.concurrent.CompletableFuture) Deque(java.util.Deque) Append(io.pravega.shared.protocol.netty.Append) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) Supplier(java.util.function.Supplier) Iterators(com.google.common.collect.Iterators) ArrayList(java.util.ArrayList) BiPredicate(java.util.function.BiPredicate) Lists(com.google.common.collect.Lists) ByteBuf(io.netty.buffer.ByteBuf) Charsets(com.google.common.base.Charsets) LongStream(java.util.stream.LongStream) MockConnectionFactoryImpl(io.pravega.client.stream.mock.MockConnectionFactoryImpl) lombok.val(lombok.val) AsyncIterator(io.pravega.common.util.AsyncIterator) Test(org.junit.Test) AuthenticationException(io.pravega.auth.AuthenticationException) WireCommands(io.pravega.shared.protocol.netty.WireCommands) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) WireCommand(io.pravega.shared.protocol.netty.WireCommand) AbstractMap(java.util.AbstractMap) KeyValueTableClientConfiguration(io.pravega.client.tables.KeyValueTableClientConfiguration) ArrayDeque(java.util.ArrayDeque) Assert(org.junit.Assert) Collections(java.util.Collections) ArrayList(java.util.ArrayList) Cleanup(lombok.Cleanup) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) AbstractMap(java.util.AbstractMap) WireCommands(io.pravega.shared.protocol.netty.WireCommands) Map(java.util.Map) AbstractMap(java.util.AbstractMap) Test(org.junit.Test)

Example 9 with WireCommand

use of io.pravega.shared.protocol.netty.WireCommand in project pravega by pravega.

the class SegmentHelper method removeTableKeys.

/**
 * This method sends a WireCommand to remove table keys.
 *
 * @param tableName       Qualified table name.
 * @param keys            List of {@link TableSegmentKey}s to be removed. Only if all the elements in the list has version
 *                        as {@link TableSegmentKeyVersion#NO_VERSION} then an unconditional update/removal is performed.
 *                        Else an atomic conditional update (removal) is performed.
 * @param delegationToken The token to be presented to the Segment Store.
 * @param clientRequestId Request id.
 * @return A CompletableFuture that will complete normally when the provided keys are deleted.
 * If the operation failed, the future will be failed with the causing exception. If the exception can be
 * retried then the future will be failed with {@link WireCommandFailedException}.
 */
public CompletableFuture<Void> removeTableKeys(final String tableName, final List<TableSegmentKey> keys, String delegationToken, final long clientRequestId) {
    final Controller.NodeUri uri = getTableUri(tableName);
    final WireCommandType type = WireCommandType.REMOVE_TABLE_KEYS;
    List<WireCommands.TableKey> keyList = keys.stream().map(x -> {
        WireCommands.TableKey key = convertToWireCommand(x);
        return key;
    }).collect(Collectors.toList());
    RawClient connection = new RawClient(ModelHelper.encode(uri), connectionPool);
    final long requestId = connection.getFlow().asLong();
    WireCommands.RemoveTableKeys request = new WireCommands.RemoveTableKeys(requestId, tableName, delegationToken, keyList, WireCommands.NULL_TABLE_SEGMENT_OFFSET);
    return sendRequest(connection, clientRequestId, request).thenAccept(rpl -> handleReply(clientRequestId, rpl, connection, tableName, WireCommands.RemoveTableKeys.class, type));
}
Also used : SneakyThrows(lombok.SneakyThrows) TokenExpiredException(io.pravega.auth.TokenExpiredException) LoggerFactory(org.slf4j.LoggerFactory) TimeoutException(java.util.concurrent.TimeoutException) Unpooled(io.netty.buffer.Unpooled) TagLogger(io.pravega.common.tracing.TagLogger) Pair(org.apache.commons.lang3.tuple.Pair) Duration(java.time.Duration) Map(java.util.Map) PravegaNodeUri(io.pravega.shared.protocol.netty.PravegaNodeUri) HashTableIteratorItem(io.pravega.client.tables.impl.HashTableIteratorItem) Controller(io.pravega.controller.stream.api.grpc.v1.Controller) ImmutableSet(com.google.common.collect.ImmutableSet) ImmutableMap(com.google.common.collect.ImmutableMap) Set(java.util.Set) CompletionException(java.util.concurrent.CompletionException) Request(io.pravega.shared.protocol.netty.Request) UUID(java.util.UUID) Collectors(java.util.stream.Collectors) List(java.util.List) Config(io.pravega.controller.util.Config) Futures(io.pravega.common.concurrent.Futures) TableSegmentKeyVersion(io.pravega.client.tables.impl.TableSegmentKeyVersion) ConnectionFailedException(io.pravega.shared.protocol.netty.ConnectionFailedException) Reply(io.pravega.shared.protocol.netty.Reply) ModelHelper(io.pravega.client.control.impl.ModelHelper) Exceptions(io.pravega.common.Exceptions) CompletableFuture(java.util.concurrent.CompletableFuture) AtomicReference(java.util.concurrent.atomic.AtomicReference) NameUtils.getSegmentNumber(io.pravega.shared.NameUtils.getSegmentNumber) RawClient(io.pravega.client.connection.impl.RawClient) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) WireCommandType(io.pravega.shared.protocol.netty.WireCommandType) NameUtils.getQualifiedStreamSegmentName(io.pravega.shared.NameUtils.getQualifiedStreamSegmentName) RecordHelper(io.pravega.controller.store.stream.records.RecordHelper) Host(io.pravega.common.cluster.Host) TableSegmentKey(io.pravega.client.tables.impl.TableSegmentKey) ConnectionPool(io.pravega.client.connection.impl.ConnectionPool) AuthenticationException(io.pravega.auth.AuthenticationException) WireCommands(io.pravega.shared.protocol.netty.WireCommands) ImmutablePair(org.apache.commons.lang3.tuple.ImmutablePair) WireCommand(io.pravega.shared.protocol.netty.WireCommand) AbstractMap(java.util.AbstractMap) TableSegmentEntry(io.pravega.client.tables.impl.TableSegmentEntry) HostControllerStore(io.pravega.controller.store.host.HostControllerStore) TxnStatus(io.pravega.controller.stream.api.grpc.v1.Controller.TxnStatus) Preconditions(com.google.common.base.Preconditions) VisibleForTesting(com.google.common.annotations.VisibleForTesting) ConnectionClosedException(io.pravega.client.stream.impl.ConnectionClosedException) ScalingPolicy(io.pravega.client.stream.ScalingPolicy) NameUtils.getTransactionNameFromId(io.pravega.shared.NameUtils.getTransactionNameFromId) WireCommandType(io.pravega.shared.protocol.netty.WireCommandType) RawClient(io.pravega.client.connection.impl.RawClient) Controller(io.pravega.controller.stream.api.grpc.v1.Controller) WireCommands(io.pravega.shared.protocol.netty.WireCommands)

Example 10 with WireCommand

use of io.pravega.shared.protocol.netty.WireCommand in project pravega by pravega.

the class AppendTest method sendRequest.

static Reply sendRequest(EmbeddedChannel channel, Request request) throws Exception {
    channel.writeInbound(request);
    log.info("Request {} sent to Segment store", request);
    Object encodedReply = channel.readOutbound();
    for (int i = 0; encodedReply == null && i < 500; i++) {
        channel.runPendingTasks();
        Thread.sleep(10);
        encodedReply = channel.readOutbound();
    }
    if (encodedReply == null) {
        log.error("Error while try waiting for a response from Segment Store");
        throw new IllegalStateException("No reply to request: " + request);
    }
    WireCommand decoded = CommandDecoder.parseCommand((ByteBuf) encodedReply);
    ((ByteBuf) encodedReply).release();
    assertNotNull(decoded);
    return (Reply) decoded;
}
Also used : WireCommand(io.pravega.shared.protocol.netty.WireCommand) Reply(io.pravega.shared.protocol.netty.Reply) ByteBuf(io.netty.buffer.ByteBuf)

Aggregations

WireCommand (io.pravega.shared.protocol.netty.WireCommand)23 Test (org.junit.Test)18 WireCommands (io.pravega.shared.protocol.netty.WireCommands)17 ByteBuf (io.netty.buffer.ByteBuf)15 UUID (java.util.UUID)15 PravegaNodeUri (io.pravega.shared.protocol.netty.PravegaNodeUri)13 Append (io.pravega.shared.protocol.netty.Append)12 Event (io.pravega.shared.protocol.netty.WireCommands.Event)10 Cleanup (lombok.Cleanup)9 AppendBatchSizeTracker (io.pravega.shared.protocol.netty.AppendBatchSizeTracker)8 AppendBlock (io.pravega.shared.protocol.netty.WireCommands.AppendBlock)8 AppendBlockEnd (io.pravega.shared.protocol.netty.WireCommands.AppendBlockEnd)8 lombok.val (lombok.val)7 StreamSegmentStore (io.pravega.segmentstore.contracts.StreamSegmentStore)6 ArgumentMatchers.anyString (org.mockito.ArgumentMatchers.anyString)6 TableStore (io.pravega.segmentstore.contracts.tables.TableStore)5 PassingTokenVerifier (io.pravega.segmentstore.server.host.delegationtoken.PassingTokenVerifier)5 SynchronousStreamSegmentStore (io.pravega.segmentstore.server.mocks.SynchronousStreamSegmentStore)5 ServiceBuilder (io.pravega.segmentstore.server.store.ServiceBuilder)5 CompletableFuture (java.util.concurrent.CompletableFuture)5