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());
});
}
}
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);
}
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;
}
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);
}
}
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;
});
}
Aggregations