Search in sources :

Example 1 with TokenException

use of io.pravega.auth.TokenException in project pravega by pravega.

the class AppendProcessor method handleException.

private Void handleException(UUID writerId, long requestId, String segment, long eventNumber, String doingWhat, Throwable u) {
    if (u == null) {
        IllegalStateException exception = new IllegalStateException("No exception to handle.");
        log.error(requestId, "Append processor: Error {} on segment = '{}'", doingWhat, segment, exception);
        throw exception;
    }
    u = Exceptions.unwrap(u);
    String clientReplyStackTrace = replyWithStackTraceOnError ? Throwables.getStackTraceAsString(u) : EMPTY_STACK_TRACE;
    if (u instanceof StreamSegmentExistsException) {
        log.warn(requestId, "Segment '{}' already exists and {} cannot perform operation '{}'.", segment, writerId, doingWhat);
        connection.send(new SegmentAlreadyExists(requestId, segment, clientReplyStackTrace));
    } else if (u instanceof StreamSegmentNotExistsException) {
        log.warn(requestId, "Segment '{}' does not exist and {} cannot perform operation '{}'.", segment, writerId, doingWhat);
        connection.send(new NoSuchSegment(requestId, segment, clientReplyStackTrace, -1L));
    } else if (u instanceof StreamSegmentSealedException) {
        log.info("Segment '{}' is sealed and {} cannot perform operation '{}'.", segment, writerId, doingWhat);
        connection.send(new SegmentIsSealed(requestId, segment, clientReplyStackTrace, eventNumber));
    } else if (u instanceof ContainerNotFoundException) {
        int containerId = ((ContainerNotFoundException) u).getContainerId();
        log.warn(requestId, "Wrong host. Segment '{}' (Container {}) is not owned and {} cannot perform operation '{}'.", segment, containerId, writerId, doingWhat);
        connection.send(new WrongHost(requestId, segment, "", clientReplyStackTrace));
    } else if (u instanceof BadAttributeUpdateException) {
        log.warn(requestId, "Bad attribute update by {} on segment {}.", writerId, segment, u);
        connection.send(new InvalidEventNumber(writerId, requestId, clientReplyStackTrace));
        close();
    } else if (u instanceof TokenExpiredException) {
        log.warn(requestId, "Token expired for writer {} on segment {}.", writerId, segment, u);
        close();
    } else if (u instanceof TokenException) {
        log.warn(requestId, "Token check failed or writer {} on segment {}.", writerId, segment, u);
        connection.send(new WireCommands.AuthTokenCheckFailed(requestId, clientReplyStackTrace, WireCommands.AuthTokenCheckFailed.ErrorCode.TOKEN_CHECK_FAILED));
    } else if (u instanceof UnsupportedOperationException) {
        log.warn(requestId, "Unsupported Operation '{}'.", doingWhat, u);
        connection.send(new OperationUnsupported(requestId, doingWhat, clientReplyStackTrace));
    } else if (u instanceof CancellationException) {
        // Cancellation exception is thrown when the Operation processor is shutting down.
        log.info("Closing connection '{}' while performing append on Segment '{}' due to {}.", connection, segment, u.toString());
        close();
    } else {
        logError(segment, u);
        // Closing connection should reinitialize things, and hopefully fix the problem
        close();
    }
    return null;
}
Also used : OperationUnsupported(io.pravega.shared.protocol.netty.WireCommands.OperationUnsupported) WrongHost(io.pravega.shared.protocol.netty.WireCommands.WrongHost) StreamSegmentNotExistsException(io.pravega.segmentstore.contracts.StreamSegmentNotExistsException) StreamSegmentExistsException(io.pravega.segmentstore.contracts.StreamSegmentExistsException) SegmentAlreadyExists(io.pravega.shared.protocol.netty.WireCommands.SegmentAlreadyExists) TokenExpiredException(io.pravega.auth.TokenExpiredException) StreamSegmentSealedException(io.pravega.segmentstore.contracts.StreamSegmentSealedException) SegmentIsSealed(io.pravega.shared.protocol.netty.WireCommands.SegmentIsSealed) BadAttributeUpdateException(io.pravega.segmentstore.contracts.BadAttributeUpdateException) InvalidEventNumber(io.pravega.shared.protocol.netty.WireCommands.InvalidEventNumber) CancellationException(java.util.concurrent.CancellationException) TokenException(io.pravega.auth.TokenException) NoSuchSegment(io.pravega.shared.protocol.netty.WireCommands.NoSuchSegment) WireCommands(io.pravega.shared.protocol.netty.WireCommands) ContainerNotFoundException(io.pravega.segmentstore.contracts.ContainerNotFoundException)

Example 2 with TokenException

use of io.pravega.auth.TokenException in project pravega by pravega.

the class PravegaRequestProcessor method handleException.

private Void handleException(long requestId, String segment, long offset, String operation, Throwable u) {
    if (u == null) {
        IllegalStateException exception = new IllegalStateException("No exception to handle.");
        log.error(requestId, "Error (Segment = '{}', Operation = '{}')", segment, operation, exception);
        throw exception;
    }
    u = Exceptions.unwrap(u);
    String clientReplyStackTrace = replyWithStackTraceOnError ? Throwables.getStackTraceAsString(u) : EMPTY_STACK_TRACE;
    final Consumer<Throwable> failureHandler = t -> {
        log.error(requestId, "Error (Segment = '{}', Operation = '{}')", segment, "handling result of " + operation, t);
        connection.close();
    };
    if (u instanceof StreamSegmentExistsException) {
        log.info(requestId, "Segment '{}' already exists and cannot perform operation '{}'.", segment, operation);
        invokeSafely(connection::send, new SegmentAlreadyExists(requestId, segment, clientReplyStackTrace), failureHandler);
    } else if (u instanceof StreamSegmentNotExistsException) {
        log.warn(requestId, "Segment '{}' does not exist and cannot perform operation '{}'.", segment, operation);
        invokeSafely(connection::send, new NoSuchSegment(requestId, segment, clientReplyStackTrace, offset), failureHandler);
    } else if (u instanceof StreamSegmentSealedException) {
        log.info(requestId, "Segment '{}' is sealed and cannot perform operation '{}'.", segment, operation);
        invokeSafely(connection::send, new SegmentIsSealed(requestId, segment, clientReplyStackTrace, offset), failureHandler);
    } else if (u instanceof ContainerNotFoundException) {
        int containerId = ((ContainerNotFoundException) u).getContainerId();
        log.warn(requestId, "Wrong host. Segment = '{}' (Container {}) is not owned. Operation = '{}').", segment, containerId, operation);
        invokeSafely(connection::send, new WrongHost(requestId, segment, "", clientReplyStackTrace), failureHandler);
    } else if (u instanceof ReadCancellationException) {
        log.info(requestId, "Sending empty response on connection {} while reading segment {} due to CancellationException.", connection, segment);
        invokeSafely(connection::send, new SegmentRead(segment, offset, true, false, EMPTY_BUFFER, requestId), failureHandler);
    } else if (u instanceof CancellationException) {
        log.info(requestId, "Closing connection {} while performing {} due to {}.", connection, operation, u.toString());
        connection.close();
    } else if (u instanceof TokenExpiredException) {
        log.warn(requestId, "Expired token during operation {}", operation);
        invokeSafely(connection::send, new AuthTokenCheckFailed(requestId, clientReplyStackTrace, AuthTokenCheckFailed.ErrorCode.TOKEN_EXPIRED), failureHandler);
    } else if (u instanceof TokenException) {
        log.warn(requestId, "Token exception encountered during operation {}.", operation, u);
        invokeSafely(connection::send, new AuthTokenCheckFailed(requestId, clientReplyStackTrace, AuthTokenCheckFailed.ErrorCode.TOKEN_CHECK_FAILED), failureHandler);
    } else if (u instanceof UnsupportedOperationException) {
        log.warn(requestId, "Unsupported Operation '{}'.", operation, u);
        invokeSafely(connection::send, new OperationUnsupported(requestId, operation, clientReplyStackTrace), failureHandler);
    } else if (u instanceof BadOffsetException) {
        BadOffsetException badOffset = (BadOffsetException) u;
        log.info(requestId, "Segment '{}' is truncated and cannot perform operation '{}' at offset '{}'", segment, operation, offset);
        invokeSafely(connection::send, new SegmentIsTruncated(requestId, segment, badOffset.getExpectedOffset(), clientReplyStackTrace, offset), failureHandler);
    } else if (u instanceof TableSegmentNotEmptyException) {
        log.warn(requestId, "Table segment '{}' is not empty to perform '{}'.", segment, operation);
        invokeSafely(connection::send, new TableSegmentNotEmpty(requestId, segment, clientReplyStackTrace), failureHandler);
    } else if (u instanceof KeyNotExistsException) {
        log.warn(requestId, "Conditional update on Table segment '{}' failed as the key does not exist.", segment);
        invokeSafely(connection::send, new WireCommands.TableKeyDoesNotExist(requestId, segment, clientReplyStackTrace), failureHandler);
    } else if (u instanceof BadKeyVersionException) {
        log.warn(requestId, "Conditional update on Table segment '{}' failed due to bad key version.", segment);
        invokeSafely(connection::send, new WireCommands.TableKeyBadVersion(requestId, segment, clientReplyStackTrace), failureHandler);
    } else if (errorCodeExists(u)) {
        log.warn(requestId, "Operation on segment '{}' failed due to a {}.", segment, u.getClass());
        invokeSafely(connection::send, new WireCommands.ErrorMessage(requestId, segment, u.getMessage(), WireCommands.ErrorMessage.ErrorCode.valueOf(u.getClass())), failureHandler);
    } else {
        logError(requestId, segment, operation, u);
        // Closing connection should reinitialize things, and hopefully fix the problem
        connection.close();
        throw new IllegalStateException("Unknown exception.", u);
    }
    return null;
}
Also used : SCALE_POLICY_RATE(io.pravega.segmentstore.contracts.Attributes.SCALE_POLICY_RATE) Arrays(java.util.Arrays) TableSegmentConfig(io.pravega.segmentstore.contracts.tables.TableSegmentConfig) ErrorCode(io.pravega.shared.protocol.netty.WireCommands.ErrorMessage.ErrorCode) READ(io.pravega.auth.AuthHandler.Permissions.READ) StreamSegmentNotExistsException(io.pravega.segmentstore.contracts.StreamSegmentNotExistsException) SegmentIsTruncated(io.pravega.shared.protocol.netty.WireCommands.SegmentIsTruncated) CreateTableSegment(io.pravega.shared.protocol.netty.WireCommands.CreateTableSegment) CREATION_TIME(io.pravega.segmentstore.contracts.Attributes.CREATION_TIME) GetStreamSegmentInfo(io.pravega.shared.protocol.netty.WireCommands.GetStreamSegmentInfo) AuthTokenCheckFailed(io.pravega.shared.protocol.netty.WireCommands.AuthTokenCheckFailed) MergeSegments(io.pravega.shared.protocol.netty.WireCommands.MergeSegments) Duration(java.time.Duration) Map(java.util.Map) SegmentCreated(io.pravega.shared.protocol.netty.WireCommands.SegmentCreated) DeltaIteratorState(io.pravega.segmentstore.server.tables.DeltaIteratorState) StreamSegmentStore(io.pravega.segmentstore.contracts.StreamSegmentStore) Attributes(io.pravega.segmentstore.contracts.Attributes) TableKey(io.pravega.segmentstore.contracts.tables.TableKey) CancellationException(java.util.concurrent.CancellationException) NonNull(lombok.NonNull) ThreadSafe(javax.annotation.concurrent.ThreadSafe) ContainerNotFoundException(io.pravega.segmentstore.contracts.ContainerNotFoundException) GuardedBy(javax.annotation.concurrent.GuardedBy) CreateSegment(io.pravega.shared.protocol.netty.WireCommands.CreateSegment) SealSegment(io.pravega.shared.protocol.netty.WireCommands.SealSegment) SegmentSealed(io.pravega.shared.protocol.netty.WireCommands.SegmentSealed) EndOfStreamSegment(io.pravega.segmentstore.contracts.ReadResultEntryType.EndOfStreamSegment) Futures(io.pravega.common.concurrent.Futures) SegmentAttribute(io.pravega.shared.protocol.netty.WireCommands.SegmentAttribute) IllegalContainerStateException(io.pravega.segmentstore.server.IllegalContainerStateException) Exceptions(io.pravega.common.Exceptions) BadAttributeUpdateException(io.pravega.segmentstore.contracts.BadAttributeUpdateException) GetSegmentAttribute(io.pravega.shared.protocol.netty.WireCommands.GetSegmentAttribute) BadKeyVersionException(io.pravega.segmentstore.contracts.tables.BadKeyVersionException) ArrayList(java.util.ArrayList) READ_UPDATE(io.pravega.auth.AuthHandler.Permissions.READ_UPDATE) SegmentType(io.pravega.segmentstore.contracts.SegmentType) SegmentRead(io.pravega.shared.protocol.netty.WireCommands.SegmentRead) AccessLevel(lombok.AccessLevel) Future(io.pravega.segmentstore.contracts.ReadResultEntryType.Future) FailingRequestProcessor(io.pravega.shared.protocol.netty.FailingRequestProcessor) TokenException(io.pravega.auth.TokenException) StreamSegmentTruncatedException(io.pravega.segmentstore.contracts.StreamSegmentTruncatedException) KeyNotExistsException(io.pravega.segmentstore.contracts.tables.KeyNotExistsException) DeleteTableSegment(io.pravega.shared.protocol.netty.WireCommands.DeleteTableSegment) AttributeId(io.pravega.segmentstore.contracts.AttributeId) lombok.val(lombok.val) Throwables(com.google.common.base.Throwables) WireCommands(io.pravega.shared.protocol.netty.WireCommands) WrongHost(io.pravega.shared.protocol.netty.WireCommands.WrongHost) SegmentDeleted(io.pravega.shared.protocol.netty.WireCommands.SegmentDeleted) AttributeUpdateCollection(io.pravega.segmentstore.contracts.AttributeUpdateCollection) Truncated(io.pravega.segmentstore.contracts.ReadResultEntryType.Truncated) SegmentTruncated(io.pravega.shared.protocol.netty.WireCommands.SegmentTruncated) RequestProcessor(io.pravega.shared.protocol.netty.RequestProcessor) OperationUnsupported(io.pravega.shared.protocol.netty.WireCommands.OperationUnsupported) Preconditions(com.google.common.base.Preconditions) Callbacks.invokeSafely(io.pravega.common.function.Callbacks.invokeSafely) TableEntry(io.pravega.segmentstore.contracts.tables.TableEntry) EMPTY_BUFFER(io.netty.buffer.Unpooled.EMPTY_BUFFER) Cache(io.pravega.segmentstore.contracts.ReadResultEntryType.Cache) TokenExpiredException(io.pravega.auth.TokenExpiredException) TableStore(io.pravega.segmentstore.contracts.tables.TableStore) LoggerFactory(org.slf4j.LoggerFactory) Unpooled(io.netty.buffer.Unpooled) IteratorArgs(io.pravega.segmentstore.contracts.tables.IteratorArgs) SegmentProperties(io.pravega.segmentstore.contracts.SegmentProperties) AttributeUpdate(io.pravega.segmentstore.contracts.AttributeUpdate) StreamSegmentSealedException(io.pravega.segmentstore.contracts.StreamSegmentSealedException) TagLogger(io.pravega.common.tracing.TagLogger) UpdateSegmentAttribute(io.pravega.shared.protocol.netty.WireCommands.UpdateSegmentAttribute) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) BufferView(io.pravega.common.util.BufferView) UpdateSegmentPolicy(io.pravega.shared.protocol.netty.WireCommands.UpdateSegmentPolicy) SegmentStatsRecorder(io.pravega.segmentstore.server.host.stat.SegmentStatsRecorder) ROLLOVER_SIZE(io.pravega.segmentstore.contracts.Attributes.ROLLOVER_SIZE) Collection(java.util.Collection) CompletionException(java.util.concurrent.CompletionException) Math.min(java.lang.Math.min) Collectors(java.util.stream.Collectors) List(java.util.List) StreamSegmentExistsException(io.pravega.segmentstore.contracts.StreamSegmentExistsException) PassingTokenVerifier(io.pravega.segmentstore.server.host.delegationtoken.PassingTokenVerifier) BadOffsetException(io.pravega.segmentstore.contracts.BadOffsetException) DelegationTokenVerifier(io.pravega.segmentstore.server.host.delegationtoken.DelegationTokenVerifier) Math.max(java.lang.Math.max) SegmentIsSealed(io.pravega.shared.protocol.netty.WireCommands.SegmentIsSealed) ReadResult(io.pravega.segmentstore.contracts.ReadResult) IntStream(java.util.stream.IntStream) Setter(lombok.Setter) DeleteSegment(io.pravega.shared.protocol.netty.WireCommands.DeleteSegment) SegmentPolicyUpdated(io.pravega.shared.protocol.netty.WireCommands.SegmentPolicyUpdated) Getter(lombok.Getter) NoSuchSegment(io.pravega.shared.protocol.netty.WireCommands.NoSuchSegment) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) Iterators(com.google.common.collect.Iterators) TableSegmentNotEmpty(io.pravega.shared.protocol.netty.WireCommands.TableSegmentNotEmpty) TableSegmentNotEmptyException(io.pravega.segmentstore.contracts.tables.TableSegmentNotEmptyException) ByteBuf(io.netty.buffer.ByteBuf) ReadResultEntry(io.pravega.segmentstore.contracts.ReadResultEntry) SCALE_POLICY_TYPE(io.pravega.segmentstore.contracts.Attributes.SCALE_POLICY_TYPE) TYPE_PLUS_LENGTH_SIZE(io.pravega.shared.protocol.netty.WireCommands.TYPE_PLUS_LENGTH_SIZE) StreamSegmentInfo(io.pravega.shared.protocol.netty.WireCommands.StreamSegmentInfo) TruncateSegment(io.pravega.shared.protocol.netty.WireCommands.TruncateSegment) ReadSegment(io.pravega.shared.protocol.netty.WireCommands.ReadSegment) SegmentAlreadyExists(io.pravega.shared.protocol.netty.WireCommands.SegmentAlreadyExists) ByteBufWrapper(io.pravega.shared.protocol.netty.ByteBufWrapper) LoggerHelpers(io.pravega.common.LoggerHelpers) MergeStreamSegmentResult(io.pravega.segmentstore.contracts.MergeStreamSegmentResult) StreamSegmentMergedException(io.pravega.segmentstore.contracts.StreamSegmentMergedException) Timer(io.pravega.common.Timer) TableSegmentStatsRecorder(io.pravega.segmentstore.server.host.stat.TableSegmentStatsRecorder) SegmentAttributeUpdated(io.pravega.shared.protocol.netty.WireCommands.SegmentAttributeUpdated) Consumer(java.util.function.Consumer) AbstractMap(java.util.AbstractMap) Collectors.toList(java.util.stream.Collectors.toList) VisibleForTesting(com.google.common.annotations.VisibleForTesting) AttributeUpdateType(io.pravega.segmentstore.contracts.AttributeUpdateType) Collections(java.util.Collections) BadKeyVersionException(io.pravega.segmentstore.contracts.tables.BadKeyVersionException) WrongHost(io.pravega.shared.protocol.netty.WireCommands.WrongHost) SegmentAlreadyExists(io.pravega.shared.protocol.netty.WireCommands.SegmentAlreadyExists) AuthTokenCheckFailed(io.pravega.shared.protocol.netty.WireCommands.AuthTokenCheckFailed) StreamSegmentSealedException(io.pravega.segmentstore.contracts.StreamSegmentSealedException) SegmentIsSealed(io.pravega.shared.protocol.netty.WireCommands.SegmentIsSealed) SegmentRead(io.pravega.shared.protocol.netty.WireCommands.SegmentRead) SegmentIsTruncated(io.pravega.shared.protocol.netty.WireCommands.SegmentIsTruncated) TokenException(io.pravega.auth.TokenException) BadOffsetException(io.pravega.segmentstore.contracts.BadOffsetException) TableSegmentNotEmpty(io.pravega.shared.protocol.netty.WireCommands.TableSegmentNotEmpty) WireCommands(io.pravega.shared.protocol.netty.WireCommands) ContainerNotFoundException(io.pravega.segmentstore.contracts.ContainerNotFoundException) OperationUnsupported(io.pravega.shared.protocol.netty.WireCommands.OperationUnsupported) StreamSegmentNotExistsException(io.pravega.segmentstore.contracts.StreamSegmentNotExistsException) StreamSegmentExistsException(io.pravega.segmentstore.contracts.StreamSegmentExistsException) TokenExpiredException(io.pravega.auth.TokenExpiredException) CancellationException(java.util.concurrent.CancellationException) KeyNotExistsException(io.pravega.segmentstore.contracts.tables.KeyNotExistsException) TableSegmentNotEmptyException(io.pravega.segmentstore.contracts.tables.TableSegmentNotEmptyException) NoSuchSegment(io.pravega.shared.protocol.netty.WireCommands.NoSuchSegment)

Example 3 with TokenException

use of io.pravega.auth.TokenException in project pravega by pravega.

the class TokenVerifierImpl method verifyToken.

@Override
public JsonWebToken verifyToken(@NonNull String resource, String token, @NonNull AuthHandler.Permissions expectedLevel) throws TokenExpiredException, InvalidTokenException, InvalidClaimException, TokenException {
    if (Strings.isNullOrEmpty(token)) {
        throw new InvalidTokenException("Token is null or empty");
    }
    // All key value pairs inside the payload are returned, including standard fields such as sub (for subject),
    // aud (for audience), iat, exp, as well as custom fields of the form "<resource> -> <permission>" set by
    // Pravega.
    JsonWebToken jwt = JwtParser.parse(token, tokenSigningKey);
    Map<String, Object> permissionsByResource = jwt.getPermissionsByResource();
    Optional<Map.Entry<String, Object>> matchingClaim = permissionsByResource.entrySet().stream().filter(entry -> resourceMatchesClaimKey(entry.getKey(), resource) && expectedLevel.compareTo(AuthHandler.Permissions.valueOf(entry.getValue().toString())) <= 0).findFirst();
    if (!matchingClaim.isPresent()) {
        log.debug(String.format("No matching claim found for resource [%s] and permission [%s] in token.", resource, expectedLevel));
        throw new InvalidClaimException(String.format("No matching claim found for resource: [%s] and permission: [%s] in the delegation token.", resource, expectedLevel));
    }
    return jwt;
}
Also used : InvalidClaimException(io.pravega.auth.InvalidClaimException) TokenExpiredException(io.pravega.auth.TokenExpiredException) NonNull(lombok.NonNull) AuthHandler(io.pravega.auth.AuthHandler) Exceptions(io.pravega.common.Exceptions) JsonWebToken(io.pravega.shared.security.token.JsonWebToken) Strings(com.google.common.base.Strings) Slf4j(lombok.extern.slf4j.Slf4j) JwtParser(io.pravega.shared.security.token.JwtParser) InvalidTokenException(io.pravega.auth.InvalidTokenException) Map(java.util.Map) TokenException(io.pravega.auth.TokenException) Optional(java.util.Optional) VisibleForTesting(com.google.common.annotations.VisibleForTesting) Pattern(java.util.regex.Pattern) InvalidTokenException(io.pravega.auth.InvalidTokenException) InvalidClaimException(io.pravega.auth.InvalidClaimException) JsonWebToken(io.pravega.shared.security.token.JsonWebToken)

Example 4 with TokenException

use of io.pravega.auth.TokenException in project pravega by pravega.

the class AppendProcessor method setupAppend.

/**
 * Setup an append so that subsequent append calls can occur.
 * This requires validating that the segment exists.
 * The reply: AppendSetup indicates that appends may proceed and contains the eventNumber which they should proceed
 * from (in the event that this is a reconnect from a producer we have seen before)
 */
@Override
public void setupAppend(SetupAppend setupAppend) {
    String newSegment = setupAppend.getSegment();
    UUID writer = setupAppend.getWriterId();
    log.info("Setting up appends for writer: {} on segment: {}", writer, newSegment);
    if (this.tokenVerifier != null) {
        try {
            JsonWebToken token = tokenVerifier.verifyToken(newSegment, setupAppend.getDelegationToken(), AuthHandler.Permissions.READ_UPDATE);
            setupTokenExpiryTask(setupAppend, token);
        } catch (TokenException e) {
            handleException(setupAppend.getWriterId(), setupAppend.getRequestId(), newSegment, "Update Segment Attribute", e);
            return;
        }
    }
    // Get the last Event Number for this writer from the Store. This operation (cache=true) will automatically put
    // the value in the Store's cache so it's faster to access later.
    AttributeId writerAttributeId = AttributeId.fromUUID(writer);
    Futures.exceptionallyComposeExpecting(store.getAttributes(newSegment, Collections.singleton(writerAttributeId), true, TIMEOUT), e -> e instanceof StreamSegmentSealedException, () -> store.getAttributes(newSegment, Collections.singleton(writerAttributeId), false, TIMEOUT)).whenComplete((attributes, u) -> {
        try {
            if (u != null) {
                handleException(writer, setupAppend.getRequestId(), newSegment, "setting up append", u);
            } else {
                // Last event number stored according to Segment store.
                long eventNumber = attributes.getOrDefault(writerAttributeId, Attributes.NULL_ATTRIBUTE_VALUE);
                // Create a new WriterState object based on the attribute value for the last event number for the writer.
                // It should be noted that only one connection for a given segment writer is created by the client.
                // The event number sent by the AppendSetup command is an implicit ack, the writer acks all events
                // below the specified event number.
                WriterState current = this.writerStates.put(Pair.of(newSegment, writer), new WriterState(eventNumber));
                if (current != null) {
                    log.info("SetupAppend invoked again for writer {}. Last event number from store is {}. Prev writer state {}", writer, eventNumber, current);
                }
                connection.send(new AppendSetup(setupAppend.getRequestId(), newSegment, writer, eventNumber));
            }
        } catch (Throwable e) {
            handleException(writer, setupAppend.getRequestId(), newSegment, "handling setupAppend result", e);
        }
    });
}
Also used : Arrays(java.util.Arrays) StreamSegmentNotExistsException(io.pravega.segmentstore.contracts.StreamSegmentNotExistsException) TokenExpiredException(io.pravega.auth.TokenExpiredException) AuthHandler(io.pravega.auth.AuthHandler) LoggerFactory(org.slf4j.LoggerFactory) CREATION_TIME(io.pravega.segmentstore.contracts.Attributes.CREATION_TIME) AttributeUpdate(io.pravega.segmentstore.contracts.AttributeUpdate) StreamSegmentSealedException(io.pravega.segmentstore.contracts.StreamSegmentSealedException) TagLogger(io.pravega.common.tracing.TagLogger) Pair(org.apache.commons.lang3.tuple.Pair) Duration(java.time.Duration) SegmentStatsRecorder(io.pravega.segmentstore.server.host.stat.SegmentStatsRecorder) SegmentCreated(io.pravega.shared.protocol.netty.WireCommands.SegmentCreated) StreamSegmentStore(io.pravega.segmentstore.contracts.StreamSegmentStore) Attributes(io.pravega.segmentstore.contracts.Attributes) CancellationException(java.util.concurrent.CancellationException) NonNull(lombok.NonNull) AppendSetup(io.pravega.shared.protocol.netty.WireCommands.AppendSetup) Collection(java.util.Collection) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) ContainerNotFoundException(io.pravega.segmentstore.contracts.ContainerNotFoundException) UUID(java.util.UUID) StreamSegmentExistsException(io.pravega.segmentstore.contracts.StreamSegmentExistsException) Builder(lombok.Builder) BadOffsetException(io.pravega.segmentstore.contracts.BadOffsetException) DelegationTokenVerifier(io.pravega.segmentstore.server.host.delegationtoken.DelegationTokenVerifier) ATTRIBUTE_SEGMENT_TYPE(io.pravega.segmentstore.contracts.Attributes.ATTRIBUTE_SEGMENT_TYPE) DataAppended(io.pravega.shared.protocol.netty.WireCommands.DataAppended) SegmentIsSealed(io.pravega.shared.protocol.netty.WireCommands.SegmentIsSealed) Futures(io.pravega.common.concurrent.Futures) Getter(lombok.Getter) IllegalContainerStateException(io.pravega.segmentstore.server.IllegalContainerStateException) NoSuchSegment(io.pravega.shared.protocol.netty.WireCommands.NoSuchSegment) Exceptions(io.pravega.common.Exceptions) ConditionalCheckFailed(io.pravega.shared.protocol.netty.WireCommands.ConditionalCheckFailed) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) CompletableFuture(java.util.concurrent.CompletableFuture) BadAttributeUpdateException(io.pravega.segmentstore.contracts.BadAttributeUpdateException) Append(io.pravega.shared.protocol.netty.Append) DelegatingRequestProcessor(io.pravega.shared.protocol.netty.DelegatingRequestProcessor) CreateTransientSegment(io.pravega.shared.protocol.netty.WireCommands.CreateTransientSegment) JsonWebToken(io.pravega.shared.security.token.JsonWebToken) HashSet(java.util.HashSet) SetupAppend(io.pravega.shared.protocol.netty.WireCommands.SetupAppend) SegmentType(io.pravega.segmentstore.contracts.SegmentType) FailingRequestProcessor(io.pravega.shared.protocol.netty.FailingRequestProcessor) TokenException(io.pravega.auth.TokenException) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) Hello(io.pravega.shared.protocol.netty.WireCommands.Hello) SegmentAlreadyExists(io.pravega.shared.protocol.netty.WireCommands.SegmentAlreadyExists) ByteBufWrapper(io.pravega.shared.protocol.netty.ByteBufWrapper) LoggerHelpers(io.pravega.common.LoggerHelpers) NameUtils(io.pravega.shared.NameUtils) EVENT_COUNT(io.pravega.segmentstore.contracts.Attributes.EVENT_COUNT) AttributeId(io.pravega.segmentstore.contracts.AttributeId) Throwables(com.google.common.base.Throwables) WireCommands(io.pravega.shared.protocol.netty.WireCommands) Timer(io.pravega.common.Timer) WrongHost(io.pravega.shared.protocol.netty.WireCommands.WrongHost) InvalidEventNumber(io.pravega.shared.protocol.netty.WireCommands.InvalidEventNumber) AttributeUpdateCollection(io.pravega.segmentstore.contracts.AttributeUpdateCollection) RequestProcessor(io.pravega.shared.protocol.netty.RequestProcessor) OperationUnsupported(io.pravega.shared.protocol.netty.WireCommands.OperationUnsupported) Preconditions(com.google.common.base.Preconditions) VisibleForTesting(com.google.common.annotations.VisibleForTesting) AttributeUpdateType(io.pravega.segmentstore.contracts.AttributeUpdateType) Collections(java.util.Collections) StreamSegmentSealedException(io.pravega.segmentstore.contracts.StreamSegmentSealedException) AttributeId(io.pravega.segmentstore.contracts.AttributeId) TokenException(io.pravega.auth.TokenException) UUID(java.util.UUID) JsonWebToken(io.pravega.shared.security.token.JsonWebToken) AppendSetup(io.pravega.shared.protocol.netty.WireCommands.AppendSetup)

Aggregations

TokenException (io.pravega.auth.TokenException)4 TokenExpiredException (io.pravega.auth.TokenExpiredException)4 VisibleForTesting (com.google.common.annotations.VisibleForTesting)3 Exceptions (io.pravega.common.Exceptions)3 BadAttributeUpdateException (io.pravega.segmentstore.contracts.BadAttributeUpdateException)3 ContainerNotFoundException (io.pravega.segmentstore.contracts.ContainerNotFoundException)3 StreamSegmentExistsException (io.pravega.segmentstore.contracts.StreamSegmentExistsException)3 StreamSegmentNotExistsException (io.pravega.segmentstore.contracts.StreamSegmentNotExistsException)3 StreamSegmentSealedException (io.pravega.segmentstore.contracts.StreamSegmentSealedException)3 WireCommands (io.pravega.shared.protocol.netty.WireCommands)3 NoSuchSegment (io.pravega.shared.protocol.netty.WireCommands.NoSuchSegment)3 OperationUnsupported (io.pravega.shared.protocol.netty.WireCommands.OperationUnsupported)3 SegmentAlreadyExists (io.pravega.shared.protocol.netty.WireCommands.SegmentAlreadyExists)3 SegmentIsSealed (io.pravega.shared.protocol.netty.WireCommands.SegmentIsSealed)3 WrongHost (io.pravega.shared.protocol.netty.WireCommands.WrongHost)3 NonNull (lombok.NonNull)3 Preconditions (com.google.common.base.Preconditions)2 Throwables (com.google.common.base.Throwables)2 AuthHandler (io.pravega.auth.AuthHandler)2 LoggerHelpers (io.pravega.common.LoggerHelpers)2