Search in sources :

Example 1 with TokenExpiredException

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

the class ConditionalOutputStreamImpl method write.

@Override
public boolean write(ByteBuffer data, long expectedOffset) throws SegmentSealedException {
    Exceptions.checkNotClosed(closed.get(), this);
    synchronized (lock) {
        // Used to preserver order.
        long appendSequence = requestIdGenerator.get();
        return retrySchedule.retryWhen(e -> {
            Throwable cause = Exceptions.unwrap(e);
            boolean hasTokenExpired = cause instanceof TokenExpiredException;
            if (hasTokenExpired) {
                this.tokenProvider.signalTokenExpired();
            }
            return cause instanceof Exception && (hasTokenExpired || cause instanceof ConnectionFailedException);
        }).run(() -> {
            if (client == null || client.isClosed()) {
                client = new RawClient(controller, connectionPool, segmentId);
                long requestId = client.getFlow().getNextSequenceNumber();
                log.debug("Setting up appends on segment {} for ConditionalOutputStream with writer id {}", segmentId, writerId);
                CompletableFuture<Reply> reply = tokenProvider.retrieveToken().thenCompose(token -> {
                    SetupAppend setup = new SetupAppend(requestId, writerId, segmentId.getScopedName(), token);
                    return client.sendRequest(requestId, setup);
                });
                AppendSetup appendSetup = transformAppendSetup(reply.join());
                if (appendSetup.getLastEventNumber() >= appendSequence) {
                    return true;
                }
            }
            long requestId = client.getFlow().getNextSequenceNumber();
            val request = new ConditionalAppend(writerId, appendSequence, expectedOffset, new Event(Unpooled.wrappedBuffer(data)), requestId);
            val reply = client.sendRequest(requestId, request);
            return transformDataAppended(reply.join());
        });
    }
}
Also used : Event(io.pravega.shared.protocol.netty.WireCommands.Event) TokenExpiredException(io.pravega.auth.TokenExpiredException) ConnectionFailedException(io.pravega.shared.protocol.netty.ConnectionFailedException) Reply(io.pravega.shared.protocol.netty.Reply) Exceptions(io.pravega.common.Exceptions) ConditionalCheckFailed(io.pravega.shared.protocol.netty.WireCommands.ConditionalCheckFailed) RequiredArgsConstructor(lombok.RequiredArgsConstructor) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) CompletableFuture(java.util.concurrent.CompletableFuture) Supplier(java.util.function.Supplier) ByteBuffer(java.nio.ByteBuffer) Unpooled(io.netty.buffer.Unpooled) RawClient(io.pravega.client.connection.impl.RawClient) SetupAppend(io.pravega.shared.protocol.netty.WireCommands.SetupAppend) AuthTokenCheckFailed(io.pravega.shared.protocol.netty.WireCommands.AuthTokenCheckFailed) ConditionalAppend(io.pravega.shared.protocol.netty.WireCommands.ConditionalAppend) RetryWithBackoff(io.pravega.common.util.Retry.RetryWithBackoff) ConnectionPool(io.pravega.client.connection.impl.ConnectionPool) AppendSetup(io.pravega.shared.protocol.netty.WireCommands.AppendSetup) lombok.val(lombok.val) AuthenticationException(io.pravega.auth.AuthenticationException) UUID(java.util.UUID) WireCommands(io.pravega.shared.protocol.netty.WireCommands) GuardedBy(javax.annotation.concurrent.GuardedBy) WrongHost(io.pravega.shared.protocol.netty.WireCommands.WrongHost) DelegationTokenProvider(io.pravega.client.security.auth.DelegationTokenProvider) AtomicLong(java.util.concurrent.atomic.AtomicLong) InvalidEventNumber(io.pravega.shared.protocol.netty.WireCommands.InvalidEventNumber) Slf4j(lombok.extern.slf4j.Slf4j) VisibleForTesting(com.google.common.annotations.VisibleForTesting) DataAppended(io.pravega.shared.protocol.netty.WireCommands.DataAppended) SegmentIsSealed(io.pravega.shared.protocol.netty.WireCommands.SegmentIsSealed) Controller(io.pravega.client.control.impl.Controller) lombok.val(lombok.val) ConditionalAppend(io.pravega.shared.protocol.netty.WireCommands.ConditionalAppend) RawClient(io.pravega.client.connection.impl.RawClient) TokenExpiredException(io.pravega.auth.TokenExpiredException) ConnectionFailedException(io.pravega.shared.protocol.netty.ConnectionFailedException) AuthenticationException(io.pravega.auth.AuthenticationException) AppendSetup(io.pravega.shared.protocol.netty.WireCommands.AppendSetup) TokenExpiredException(io.pravega.auth.TokenExpiredException) SetupAppend(io.pravega.shared.protocol.netty.WireCommands.SetupAppend) Reply(io.pravega.shared.protocol.netty.Reply) Event(io.pravega.shared.protocol.netty.WireCommands.Event) ConnectionFailedException(io.pravega.shared.protocol.netty.ConnectionFailedException)

Example 2 with TokenExpiredException

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

the class SegmentHelperTest method testProcessAndRethrowExceptions.

@Test
public void testProcessAndRethrowExceptions() {
    // The wire-command itself we use for this test is immaterial, so we are using the simplest one here.
    WireCommands.Hello dummyRequest = new WireCommands.Hello(0, 0);
    @SuppressWarnings("resource") SegmentHelper objectUnderTest = new SegmentHelper(null, null, null);
    AssertExtensions.assertThrows("Unexpected exception thrown", () -> objectUnderTest.<WireCommands.Hello>processAndRethrowException(1, dummyRequest, new ExecutionException(new ConnectionFailedException())), e -> hasWireCommandFailedWithReason(e, WireCommandFailedException.Reason.ConnectionFailed));
    AssertExtensions.assertThrows("Unexpected exception thrown", () -> objectUnderTest.<WireCommands.Hello>processAndRethrowException(1, dummyRequest, new ExecutionException(new AuthenticationException("Authentication failed"))), e -> hasWireCommandFailedWithReason(e, WireCommandFailedException.Reason.AuthFailed));
    AssertExtensions.assertThrows("Unexpected exception thrown", () -> objectUnderTest.<WireCommands.Hello>processAndRethrowException(1, dummyRequest, new ExecutionException(new TokenExpiredException("Token expired"))), e -> hasWireCommandFailedWithReason(e, WireCommandFailedException.Reason.AuthFailed));
    AssertExtensions.assertThrows("Unexpected exception thrown", () -> objectUnderTest.<WireCommands.Hello>processAndRethrowException(1, dummyRequest, new ExecutionException(new TimeoutException("Authentication failed"))), e -> hasWireCommandFailedWithReason(e, WireCommandFailedException.Reason.ConnectionFailed));
    AssertExtensions.assertThrows("Unexpected exception thrown", () -> objectUnderTest.<WireCommands.Hello>processAndRethrowException(1, dummyRequest, new ExecutionException(new RuntimeException())), e -> e instanceof ExecutionException && e.getCause() instanceof RuntimeException);
}
Also used : TokenExpiredException(io.pravega.auth.TokenExpiredException) AuthenticationException(io.pravega.auth.AuthenticationException) WireCommands(io.pravega.shared.protocol.netty.WireCommands) ExecutionException(java.util.concurrent.ExecutionException) ConnectionFailedException(io.pravega.shared.protocol.netty.ConnectionFailedException) TimeoutException(java.util.concurrent.TimeoutException) Test(org.junit.Test)

Example 3 with TokenExpiredException

use of io.pravega.auth.TokenExpiredException 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 4 with TokenExpiredException

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

the class JwtParser method parseClaims.

@VisibleForTesting
static Claims parseClaims(String token, byte[] signingKey) throws TokenExpiredException, InvalidTokenException {
    if (Strings.isNullOrEmpty(token)) {
        throw new InvalidTokenException("Token is null or empty");
    }
    try {
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(signingKey).parseClaimsJws(token);
        log.debug("Successfully parsed JWT token.");
        return claimsJws.getBody();
    } catch (ExpiredJwtException e) {
        throw new TokenExpiredException(e);
    } catch (JwtException e) {
        throw new InvalidTokenException(e);
    }
}
Also used : InvalidTokenException(io.pravega.auth.InvalidTokenException) Claims(io.jsonwebtoken.Claims) ExpiredJwtException(io.jsonwebtoken.ExpiredJwtException) TokenExpiredException(io.pravega.auth.TokenExpiredException) ExpiredJwtException(io.jsonwebtoken.ExpiredJwtException) JwtException(io.jsonwebtoken.JwtException) VisibleForTesting(com.google.common.annotations.VisibleForTesting)

Example 5 with TokenExpiredException

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

the class LargeEventWriter method writeLargeEvent.

/**
 * Write the provided list of events (atomically) to the provided segment.
 *
 * @param segment The segment to write to
 * @param events The events to append
 * @param tokenProvider A token provider
 * @param config Used for retry configuration parameters
 * @throws NoSuchSegmentException If the provided segment does not exit.
 * @throws SegmentSealedException If the segment is sealed.
 * @throws AuthenticationException If the token can't be used for this segment.
 * @throws UnsupportedOperationException If the server does not support large events.
 */
public void writeLargeEvent(Segment segment, List<ByteBuffer> events, DelegationTokenProvider tokenProvider, EventWriterConfig config) throws NoSuchSegmentException, AuthenticationException, SegmentSealedException {
    List<ByteBuf> payloads = createBufs(events);
    int attempts = 1 + Math.max(0, config.getRetryAttempts());
    Retry.withExpBackoff(config.getInitialBackoffMillis(), config.getBackoffMultiple(), attempts, config.getMaxBackoffMillis()).retryWhen(t -> {
        Throwable ex = Exceptions.unwrap(t);
        if (ex instanceof ConnectionFailedException) {
            log.info("Connection failure while sending large event: {}. Retrying", ex.getMessage());
            return true;
        } else if (ex instanceof TokenExpiredException) {
            tokenProvider.signalTokenExpired();
            log.info("Authentication token expired while writing large event to segment {}. Retrying", segment);
            return true;
        } else {
            return false;
        }
    }).run(() -> {
        @Cleanup RawClient client = new RawClient(controller, connectionPool, segment);
        write(segment, payloads, client, tokenProvider);
        return null;
    });
}
Also used : Segment(io.pravega.client.segment.impl.Segment) TokenExpiredException(io.pravega.auth.TokenExpiredException) Retry(io.pravega.common.util.Retry) ConnectionFailedException(io.pravega.shared.protocol.netty.ConnectionFailedException) Reply(io.pravega.shared.protocol.netty.Reply) Exceptions(io.pravega.common.Exceptions) ConditionalCheckFailed(io.pravega.shared.protocol.netty.WireCommands.ConditionalCheckFailed) RequiredArgsConstructor(lombok.RequiredArgsConstructor) SegmentIsTruncated(io.pravega.shared.protocol.netty.WireCommands.SegmentIsTruncated) Cleanup(lombok.Cleanup) CompletableFuture(java.util.concurrent.CompletableFuture) SegmentSealedException(io.pravega.client.segment.impl.SegmentSealedException) ByteBuffer(java.nio.ByteBuffer) Unpooled(io.netty.buffer.Unpooled) CreateTransientSegment(io.pravega.shared.protocol.netty.WireCommands.CreateTransientSegment) ArrayList(java.util.ArrayList) RawClient(io.pravega.client.connection.impl.RawClient) ConditionalBlockEnd(io.pravega.shared.protocol.netty.WireCommands.ConditionalBlockEnd) SetupAppend(io.pravega.shared.protocol.netty.WireCommands.SetupAppend) ByteBuf(io.netty.buffer.ByteBuf) AuthTokenCheckFailed(io.pravega.shared.protocol.netty.WireCommands.AuthTokenCheckFailed) MergeSegments(io.pravega.shared.protocol.netty.WireCommands.MergeSegments) SegmentCreated(io.pravega.shared.protocol.netty.WireCommands.SegmentCreated) Futures.getThrowingException(io.pravega.common.concurrent.Futures.getThrowingException) WireCommandType(io.pravega.shared.protocol.netty.WireCommandType) Nonnull(javax.annotation.Nonnull) SegmentAlreadyExists(io.pravega.shared.protocol.netty.WireCommands.SegmentAlreadyExists) EventWriterConfig(io.pravega.client.stream.EventWriterConfig) Serializer(io.pravega.client.stream.Serializer) SegmentsMerged(io.pravega.shared.protocol.netty.WireCommands.SegmentsMerged) ConnectionPool(io.pravega.client.connection.impl.ConnectionPool) NoSuchSegmentException(io.pravega.client.segment.impl.NoSuchSegmentException) AppendSetup(io.pravega.shared.protocol.netty.WireCommands.AppendSetup) lombok.val(lombok.val) AuthenticationException(io.pravega.auth.AuthenticationException) UUID(java.util.UUID) WireCommands(io.pravega.shared.protocol.netty.WireCommands) WrongHost(io.pravega.shared.protocol.netty.WireCommands.WrongHost) DelegationTokenProvider(io.pravega.client.security.auth.DelegationTokenProvider) InvalidEventNumber(io.pravega.shared.protocol.netty.WireCommands.InvalidEventNumber) List(java.util.List) Slf4j(lombok.extern.slf4j.Slf4j) OperationUnsupported(io.pravega.shared.protocol.netty.WireCommands.OperationUnsupported) VisibleForTesting(com.google.common.annotations.VisibleForTesting) DataAppended(io.pravega.shared.protocol.netty.WireCommands.DataAppended) SegmentIsSealed(io.pravega.shared.protocol.netty.WireCommands.SegmentIsSealed) Controller(io.pravega.client.control.impl.Controller) TokenExpiredException(io.pravega.auth.TokenExpiredException) RawClient(io.pravega.client.connection.impl.RawClient) ByteBuf(io.netty.buffer.ByteBuf) ConnectionFailedException(io.pravega.shared.protocol.netty.ConnectionFailedException) Cleanup(lombok.Cleanup)

Aggregations

TokenExpiredException (io.pravega.auth.TokenExpiredException)10 VisibleForTesting (com.google.common.annotations.VisibleForTesting)7 AuthenticationException (io.pravega.auth.AuthenticationException)6 ConnectionFailedException (io.pravega.shared.protocol.netty.ConnectionFailedException)6 WireCommands (io.pravega.shared.protocol.netty.WireCommands)5 SegmentIsSealed (io.pravega.shared.protocol.netty.WireCommands.SegmentIsSealed)5 WrongHost (io.pravega.shared.protocol.netty.WireCommands.WrongHost)5 Exceptions (io.pravega.common.Exceptions)4 AuthTokenCheckFailed (io.pravega.shared.protocol.netty.WireCommands.AuthTokenCheckFailed)4 InvalidEventNumber (io.pravega.shared.protocol.netty.WireCommands.InvalidEventNumber)4 Unpooled (io.netty.buffer.Unpooled)3 TokenException (io.pravega.auth.TokenException)3 OperationUnsupported (io.pravega.shared.protocol.netty.WireCommands.OperationUnsupported)3 SegmentAlreadyExists (io.pravega.shared.protocol.netty.WireCommands.SegmentAlreadyExists)3 CompletableFuture (java.util.concurrent.CompletableFuture)3 ByteBuf (io.netty.buffer.ByteBuf)2 InvalidTokenException (io.pravega.auth.InvalidTokenException)2 ConnectionPool (io.pravega.client.connection.impl.ConnectionPool)2 RawClient (io.pravega.client.connection.impl.RawClient)2 Controller (io.pravega.client.control.impl.Controller)2