Search in sources :

Example 1 with InvalidRequestException

use of org.apache.kafka.common.errors.InvalidRequestException in project apache-kafka-on-k8s by banzaicloud.

the class KafkaAdminClient method createAcls.

@Override
public CreateAclsResult createAcls(Collection<AclBinding> acls, CreateAclsOptions options) {
    final long now = time.milliseconds();
    final Map<AclBinding, KafkaFutureImpl<Void>> futures = new HashMap<>();
    final List<AclCreation> aclCreations = new ArrayList<>();
    for (AclBinding acl : acls) {
        if (futures.get(acl) == null) {
            KafkaFutureImpl<Void> future = new KafkaFutureImpl<>();
            futures.put(acl, future);
            String indefinite = acl.toFilter().findIndefiniteField();
            if (indefinite == null) {
                aclCreations.add(new AclCreation(acl));
            } else {
                future.completeExceptionally(new InvalidRequestException("Invalid ACL creation: " + indefinite));
            }
        }
    }
    runnable.call(new Call("createAcls", calcDeadlineMs(now, options.timeoutMs()), new LeastLoadedNodeProvider()) {

        @Override
        AbstractRequest.Builder createRequest(int timeoutMs) {
            return new CreateAclsRequest.Builder(aclCreations);
        }

        @Override
        void handleResponse(AbstractResponse abstractResponse) {
            CreateAclsResponse response = (CreateAclsResponse) abstractResponse;
            List<AclCreationResponse> responses = response.aclCreationResponses();
            Iterator<AclCreationResponse> iter = responses.iterator();
            for (AclCreation aclCreation : aclCreations) {
                KafkaFutureImpl<Void> future = futures.get(aclCreation.acl());
                if (!iter.hasNext()) {
                    future.completeExceptionally(new UnknownServerException("The broker reported no creation result for the given ACL."));
                } else {
                    AclCreationResponse creation = iter.next();
                    if (creation.error().isFailure()) {
                        future.completeExceptionally(creation.error().exception());
                    } else {
                        future.complete(null);
                    }
                }
            }
        }

        @Override
        void handleFailure(Throwable throwable) {
            completeAllExceptionally(futures.values(), throwable);
        }
    }, now);
    return new CreateAclsResult(new HashMap<AclBinding, KafkaFuture<Void>>(futures));
}
Also used : HashMap(java.util.HashMap) ChannelBuilder(org.apache.kafka.common.network.ChannelBuilder) ArrayList(java.util.ArrayList) CreateAclsResponse(org.apache.kafka.common.requests.CreateAclsResponse) CreateAclsRequest(org.apache.kafka.common.requests.CreateAclsRequest) Iterator(java.util.Iterator) InvalidRequestException(org.apache.kafka.common.errors.InvalidRequestException) List(java.util.List) ArrayList(java.util.ArrayList) LinkedList(java.util.LinkedList) AclBinding(org.apache.kafka.common.acl.AclBinding) AclCreation(org.apache.kafka.common.requests.CreateAclsRequest.AclCreation) KafkaFuture(org.apache.kafka.common.KafkaFuture) AbstractResponse(org.apache.kafka.common.requests.AbstractResponse) KafkaFutureImpl(org.apache.kafka.common.internals.KafkaFutureImpl) UnknownServerException(org.apache.kafka.common.errors.UnknownServerException) AclCreationResponse(org.apache.kafka.common.requests.CreateAclsResponse.AclCreationResponse)

Example 2 with InvalidRequestException

use of org.apache.kafka.common.errors.InvalidRequestException in project kafka by apache.

the class KafkaAdminClient method createAcls.

@Override
public CreateAclsResult createAcls(Collection<AclBinding> acls, CreateAclsOptions options) {
    final long now = time.milliseconds();
    final Map<AclBinding, KafkaFutureImpl<Void>> futures = new HashMap<>();
    final List<AclCreation> aclCreations = new ArrayList<>();
    final List<AclBinding> aclBindingsSent = new ArrayList<>();
    for (AclBinding acl : acls) {
        if (futures.get(acl) == null) {
            KafkaFutureImpl<Void> future = new KafkaFutureImpl<>();
            futures.put(acl, future);
            String indefinite = acl.toFilter().findIndefiniteField();
            if (indefinite == null) {
                aclCreations.add(CreateAclsRequest.aclCreation(acl));
                aclBindingsSent.add(acl);
            } else {
                future.completeExceptionally(new InvalidRequestException("Invalid ACL creation: " + indefinite));
            }
        }
    }
    final CreateAclsRequestData data = new CreateAclsRequestData().setCreations(aclCreations);
    runnable.call(new Call("createAcls", calcDeadlineMs(now, options.timeoutMs()), new LeastLoadedNodeProvider()) {

        @Override
        CreateAclsRequest.Builder createRequest(int timeoutMs) {
            return new CreateAclsRequest.Builder(data);
        }

        @Override
        void handleResponse(AbstractResponse abstractResponse) {
            CreateAclsResponse response = (CreateAclsResponse) abstractResponse;
            List<AclCreationResult> responses = response.results();
            Iterator<AclCreationResult> iter = responses.iterator();
            for (AclBinding aclBinding : aclBindingsSent) {
                KafkaFutureImpl<Void> future = futures.get(aclBinding);
                if (!iter.hasNext()) {
                    future.completeExceptionally(new UnknownServerException("The broker reported no creation result for the given ACL: " + aclBinding));
                } else {
                    AclCreationResult creation = iter.next();
                    Errors error = Errors.forCode(creation.errorCode());
                    ApiError apiError = new ApiError(error, creation.errorMessage());
                    if (apiError.isFailure())
                        future.completeExceptionally(apiError.exception());
                    else
                        future.complete(null);
                }
            }
        }

        @Override
        void handleFailure(Throwable throwable) {
            completeAllExceptionally(futures.values(), throwable);
        }
    }, now);
    return new CreateAclsResult(new HashMap<>(futures));
}
Also used : HashMap(java.util.HashMap) ChannelBuilder(org.apache.kafka.common.network.ChannelBuilder) ArrayList(java.util.ArrayList) CreateAclsResponse(org.apache.kafka.common.requests.CreateAclsResponse) CreateAclsRequest(org.apache.kafka.common.requests.CreateAclsRequest) Iterator(java.util.Iterator) InvalidRequestException(org.apache.kafka.common.errors.InvalidRequestException) LinkedList(java.util.LinkedList) ArrayList(java.util.ArrayList) List(java.util.List) AclBinding(org.apache.kafka.common.acl.AclBinding) AclCreation(org.apache.kafka.common.message.CreateAclsRequestData.AclCreation) AbstractResponse(org.apache.kafka.common.requests.AbstractResponse) CreateAclsRequestData(org.apache.kafka.common.message.CreateAclsRequestData) KafkaFutureImpl(org.apache.kafka.common.internals.KafkaFutureImpl) UnknownServerException(org.apache.kafka.common.errors.UnknownServerException) Errors(org.apache.kafka.common.protocol.Errors) ApiError(org.apache.kafka.common.requests.ApiError) AclCreationResult(org.apache.kafka.common.message.CreateAclsResponseData.AclCreationResult)

Example 3 with InvalidRequestException

use of org.apache.kafka.common.errors.InvalidRequestException in project kafka by apache.

the class SaslServerAuthenticator method handleKafkaRequest.

private boolean handleKafkaRequest(byte[] requestBytes) throws IOException, AuthenticationException {
    boolean isKafkaRequest = false;
    String clientMechanism = null;
    try {
        ByteBuffer requestBuffer = ByteBuffer.wrap(requestBytes);
        RequestHeader header = RequestHeader.parse(requestBuffer);
        ApiKeys apiKey = header.apiKey();
        // following a SaslHandshakeRequest since this is not a GSSAPI client token from a Kafka 0.9.0.x client.
        if (saslState == SaslState.INITIAL_REQUEST)
            setSaslState(SaslState.HANDSHAKE_OR_VERSIONS_REQUEST);
        isKafkaRequest = true;
        // unnecessary exposure to some of the more complex schema types.
        if (apiKey != ApiKeys.API_VERSIONS && apiKey != ApiKeys.SASL_HANDSHAKE)
            throw new IllegalSaslStateException("Unexpected Kafka request of type " + apiKey + " during SASL handshake.");
        LOG.debug("Handling Kafka request {} during {}", apiKey, reauthInfo.authenticationOrReauthenticationText());
        RequestContext requestContext = new RequestContext(header, connectionId, clientAddress(), KafkaPrincipal.ANONYMOUS, listenerName, securityProtocol, ClientInformation.EMPTY, false);
        RequestAndSize requestAndSize = requestContext.parseRequest(requestBuffer);
        if (apiKey == ApiKeys.API_VERSIONS)
            handleApiVersionsRequest(requestContext, (ApiVersionsRequest) requestAndSize.request);
        else
            clientMechanism = handleHandshakeRequest(requestContext, (SaslHandshakeRequest) requestAndSize.request);
    } catch (InvalidRequestException e) {
        if (saslState == SaslState.INITIAL_REQUEST) {
            // starting with 0x60, revert to GSSAPI for both these exceptions.
            if (LOG.isDebugEnabled()) {
                StringBuilder tokenBuilder = new StringBuilder();
                for (byte b : requestBytes) {
                    tokenBuilder.append(String.format("%02x", b));
                    if (tokenBuilder.length() >= 20)
                        break;
                }
                LOG.debug("Received client packet of length {} starting with bytes 0x{}, process as GSSAPI packet", requestBytes.length, tokenBuilder);
            }
            if (enabledMechanisms.contains(SaslConfigs.GSSAPI_MECHANISM)) {
                LOG.debug("First client packet is not a SASL mechanism request, using default mechanism GSSAPI");
                clientMechanism = SaslConfigs.GSSAPI_MECHANISM;
            } else
                throw new UnsupportedSaslMechanismException("Exception handling first SASL packet from client, GSSAPI is not supported by server", e);
        } else
            throw e;
    }
    if (clientMechanism != null && (!reauthInfo.reauthenticating() || reauthInfo.saslMechanismUnchanged(clientMechanism))) {
        createSaslServer(clientMechanism);
        setSaslState(SaslState.AUTHENTICATE);
    }
    return isKafkaRequest;
}
Also used : ApiKeys(org.apache.kafka.common.protocol.ApiKeys) RequestAndSize(org.apache.kafka.common.requests.RequestAndSize) UnsupportedSaslMechanismException(org.apache.kafka.common.errors.UnsupportedSaslMechanismException) RequestHeader(org.apache.kafka.common.requests.RequestHeader) InvalidRequestException(org.apache.kafka.common.errors.InvalidRequestException) IllegalSaslStateException(org.apache.kafka.common.errors.IllegalSaslStateException) RequestContext(org.apache.kafka.common.requests.RequestContext) ByteBuffer(java.nio.ByteBuffer) ApiVersionsRequest(org.apache.kafka.common.requests.ApiVersionsRequest)

Example 4 with InvalidRequestException

use of org.apache.kafka.common.errors.InvalidRequestException in project kafka by apache.

the class RestExceptionMapperTest method testToResponseInvalidRequestException.

@Test
public void testToResponseInvalidRequestException() {
    RestExceptionMapper mapper = new RestExceptionMapper();
    Response resp = mapper.toResponse(new InvalidRequestException("invalid request"));
    assertEquals(resp.getStatus(), Response.Status.BAD_REQUEST.getStatusCode());
}
Also used : Response(javax.ws.rs.core.Response) InvalidRequestException(org.apache.kafka.common.errors.InvalidRequestException) Test(org.junit.jupiter.api.Test)

Example 5 with InvalidRequestException

use of org.apache.kafka.common.errors.InvalidRequestException in project kafka by apache.

the class ClusterMetadataAuthorizerTest method testDeleteAcls.

@Test
public void testDeleteAcls() throws Exception {
    MockAclMutator mutator = new MockAclMutator();
    MockClusterMetadataAuthorizer authorizer = new MockClusterMetadataAuthorizer();
    authorizer.setAclMutator(mutator);
    CompletableFuture<List<AclDeleteResult>> response = new CompletableFuture<>();
    response.complete(Arrays.asList(new AclDeleteResult(Collections.singleton(new AclBindingDeleteResult(TEST_BINDINGS.get(0)))), new AclDeleteResult(new InvalidRequestException("invalid"))));
    mutator.setDeleteAclsResponse(response);
    List<? extends CompletionStage<AclDeleteResult>> results = authorizer.deleteAcls(new MockAuthorizableRequestContext.Builder().build(), TEST_FILTERS);
    assertEquals(2, results.size());
    Collection<AclBindingDeleteResult> deleteResults0 = results.get(0).toCompletableFuture().get().aclBindingDeleteResults();
    assertEquals(1, deleteResults0.size());
    AclBindingDeleteResult deleteResult0 = deleteResults0.iterator().next();
    assertEquals(TEST_BINDINGS.get(0), deleteResult0.aclBinding());
    assertEquals(Optional.empty(), deleteResult0.exception());
    AclDeleteResult deleteResult1 = results.get(1).toCompletableFuture().get();
    assertEquals(0, deleteResult1.aclBindingDeleteResults().size());
    assertEquals(InvalidRequestException.class, deleteResult1.exception().get().getClass());
}
Also used : CompletableFuture(java.util.concurrent.CompletableFuture) AclBindingDeleteResult(org.apache.kafka.server.authorizer.AclDeleteResult.AclBindingDeleteResult) List(java.util.List) AclDeleteResult(org.apache.kafka.server.authorizer.AclDeleteResult) InvalidRequestException(org.apache.kafka.common.errors.InvalidRequestException) Test(org.junit.jupiter.api.Test)

Aggregations

InvalidRequestException (org.apache.kafka.common.errors.InvalidRequestException)13 List (java.util.List)5 Test (org.junit.jupiter.api.Test)4 ArrayList (java.util.ArrayList)3 HashMap (java.util.HashMap)3 AclBinding (org.apache.kafka.common.acl.AclBinding)3 KafkaFutureImpl (org.apache.kafka.common.internals.KafkaFutureImpl)3 ChannelBuilder (org.apache.kafka.common.network.ChannelBuilder)3 ApiKeys (org.apache.kafka.common.protocol.ApiKeys)3 AbstractResponse (org.apache.kafka.common.requests.AbstractResponse)3 ByteBuffer (java.nio.ByteBuffer)2 HashSet (java.util.HashSet)2 Iterator (java.util.Iterator)2 LinkedList (java.util.LinkedList)2 CompletableFuture (java.util.concurrent.CompletableFuture)2 IllegalSaslStateException (org.apache.kafka.common.errors.IllegalSaslStateException)2 UnknownServerException (org.apache.kafka.common.errors.UnknownServerException)2 UnsupportedSaslMechanismException (org.apache.kafka.common.errors.UnsupportedSaslMechanismException)2 UnsupportedVersionException (org.apache.kafka.common.errors.UnsupportedVersionException)2 ApiVersionsRequest (org.apache.kafka.common.requests.ApiVersionsRequest)2