Search in sources :

Example 21 with SafeIllegalStateException

use of com.palantir.logsafe.exceptions.SafeIllegalStateException in project tritium by palantir.

the class RemotingCompatibleTracingInvocationEventHandler method isUsingMultipleTracers.

// explicitly qualifying given remoting3 vs. tracing
@SuppressWarnings("UnnecessarilyFullyQualified")
private static boolean isUsingMultipleTracers(Class<?> tracersClass) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
    if (tracersClass != null) {
        Method wrapMethod = tracersClass.getMethod("wrap", Runnable.class);
        if (wrapMethod != null) {
            Object wrappedTrace = wrapMethod.invoke(null, (Runnable) () -> {
            });
            String expectedTracingPackage = com.palantir.tracing.Tracers.class.getPackage().getName();
            String actualTracingPackage = wrappedTrace.getClass().getPackage().getName();
            if (!Objects.equals(expectedTracingPackage, actualTracingPackage)) {
                if (shouldLogFallbackError.compareAndSet(/* expectedValue= */
                false, /* newValue= */
                true)) {
                    log.error("Multiple tracing implementations detected, expected '{}' but found '{}'," + " using legacy remoting3 tracing for backward compatibility", SafeArg.of("expectedPackage", expectedTracingPackage), SafeArg.of("actualPackage", actualTracingPackage), new SafeIllegalStateException("Multiple tracing implementations detected"));
                }
                return true;
            }
        }
    }
    return false;
}
Also used : Method(java.lang.reflect.Method) SafeIllegalStateException(com.palantir.logsafe.exceptions.SafeIllegalStateException)

Example 22 with SafeIllegalStateException

use of com.palantir.logsafe.exceptions.SafeIllegalStateException in project dialogue by palantir.

the class ReloadingClientFactory method getStickyChannels.

@Override
public StickyChannelFactory getStickyChannels(String serviceName) {
    Refreshable<List<Channel>> perHostChannels = perHost(serviceName).getPerHostChannels();
    Refreshable<Supplier<Channel>> bestSupplier = perHostChannels.map(singleHostChannels -> {
        if (singleHostChannels.isEmpty()) {
            EmptyInternalDialogueChannel alwaysThrowing = new EmptyInternalDialogueChannel(() -> new SafeIllegalStateException("Service not configured", SafeArg.of("serviceName", serviceName)));
            return () -> alwaysThrowing;
        }
        if (singleHostChannels.size() == 1) {
            return () -> singleHostChannels.get(0);
        }
        return StickyEndpointChannels.builder().channels(singleHostChannels.stream().map(c -> (DialogueChannel) c).collect(Collectors.toList())).channelName(ChannelNames.reloading(serviceName, params)).taggedMetricRegistry(params.taggedMetrics()).build();
    });
    return new StickyChannelFactory() {

        @Override
        public Channel getStickyChannel() {
            return bestSupplier.get().get();
        }

        @Override
        public <T> T getCurrentBest(Class<T> clientInterface) {
            return Reflection.callStaticFactoryMethod(clientInterface, getStickyChannel(), params.runtime());
        }

        @Override
        public String toString() {
            return "StickyChannelFactory{" + bestSupplier.get() + '}';
        }
    };
}
Also used : ListenableFuture(com.google.common.util.concurrent.ListenableFuture) SafeIllegalStateException(com.palantir.logsafe.exceptions.SafeIllegalStateException) ClientConfiguration(com.palantir.conjure.java.client.config.ClientConfiguration) OptionalInt(java.util.OptionalInt) Function(java.util.function.Function) Supplier(java.util.function.Supplier) StickyChannelFactory2(com.palantir.dialogue.clients.DialogueClients.StickyChannelFactory2) SafeArg(com.palantir.logsafe.SafeArg) NodeSelectionStrategy(com.palantir.conjure.java.client.config.NodeSelectionStrategy) ConjureRuntime(com.palantir.dialogue.ConjureRuntime) ImmutableList(com.google.common.collect.ImmutableList) UserAgent(com.palantir.conjure.java.api.config.service.UserAgent) Value(org.immutables.value.Value) Duration(java.time.Duration) Map(java.util.Map) Suppliers(com.google.common.base.Suppliers) DefaultConjureRuntime(com.palantir.conjure.java.dialogue.serde.DefaultConjureRuntime) Endpoint(com.palantir.dialogue.Endpoint) ApacheHttpClientChannels(com.palantir.dialogue.hc5.ApacheHttpClientChannels) ServiceConfiguration(com.palantir.conjure.java.api.config.service.ServiceConfiguration) Request(com.palantir.dialogue.Request) StickyChannelFactory(com.palantir.dialogue.clients.DialogueClients.StickyChannelFactory) ExecutorService(java.util.concurrent.ExecutorService) EndpointChannelFactory(com.palantir.dialogue.EndpointChannelFactory) Refreshable(com.palantir.refreshable.Refreshable) ServiceConfigurationFactory(com.palantir.conjure.java.api.config.service.ServiceConfigurationFactory) Clients(com.palantir.dialogue.Clients) PerHostClientFactory(com.palantir.dialogue.clients.DialogueClients.PerHostClientFactory) Channel(com.palantir.dialogue.Channel) Maps(com.google.common.collect.Maps) TaggedMetricRegistry(com.palantir.tritium.metrics.registry.TaggedMetricRegistry) Collectors(java.util.stream.Collectors) Provider(java.security.Provider) HostEventsSink(com.palantir.conjure.java.client.config.HostEventsSink) ServicesConfigBlock(com.palantir.conjure.java.api.config.service.ServicesConfigBlock) StickyEndpointChannels(com.palantir.dialogue.core.StickyEndpointChannels) Futures(com.google.common.util.concurrent.Futures) EndpointChannel(com.palantir.dialogue.EndpointChannel) List(java.util.List) DialogueChannel(com.palantir.dialogue.core.DialogueChannel) PartialServiceConfiguration(com.palantir.conjure.java.api.config.service.PartialServiceConfiguration) Optional(java.util.Optional) VisibleForTesting(com.google.common.annotations.VisibleForTesting) Response(com.palantir.dialogue.Response) Preconditions(com.palantir.logsafe.Preconditions) DialogueChannel(com.palantir.dialogue.core.DialogueChannel) ImmutableList(com.google.common.collect.ImmutableList) List(java.util.List) Supplier(java.util.function.Supplier) SafeIllegalStateException(com.palantir.logsafe.exceptions.SafeIllegalStateException) StickyChannelFactory(com.palantir.dialogue.clients.DialogueClients.StickyChannelFactory)

Example 23 with SafeIllegalStateException

use of com.palantir.logsafe.exceptions.SafeIllegalStateException in project dialogue by palantir.

the class ReloadingClientFactory method getInternalDialogueChannel.

private Refreshable<InternalDialogueChannel> getInternalDialogueChannel(String serviceName) {
    Preconditions.checkNotNull(serviceName, "serviceName");
    String channelName = ChannelNames.reloading(serviceName, params);
    return params.scb().map(block -> {
        Preconditions.checkNotNull(block, "Refreshable must not provide a null ServicesConfigBlock");
        if (!block.services().containsKey(serviceName)) {
            return new EmptyInternalDialogueChannel(() -> new SafeIllegalStateException("Service not configured (config block not present)", SafeArg.of("serviceName", serviceName), SafeArg.of("available", block.services().keySet())));
        }
        if (block.services().get(serviceName).uris().isEmpty()) {
            return new EmptyInternalDialogueChannel(() -> {
                Map<String, PartialServiceConfiguration> servicesWithUris = Maps.filterValues(block.services(), c -> !c.uris().isEmpty());
                return new SafeIllegalStateException("Service not configured (no URIs)", SafeArg.of("serviceName", serviceName), SafeArg.of("available", servicesWithUris.keySet()));
            });
        }
        ServiceConfiguration serviceConf = ServiceConfigurationFactory.of(block).get(serviceName);
        DialogueChannel dialogueChannel = cache.getNonReloadingChannel(params, serviceConf, channelName, OptionalInt.empty());
        return new InternalDialogueChannelFromDialogueChannel(dialogueChannel);
    });
}
Also used : ServiceConfiguration(com.palantir.conjure.java.api.config.service.ServiceConfiguration) PartialServiceConfiguration(com.palantir.conjure.java.api.config.service.PartialServiceConfiguration) DialogueChannel(com.palantir.dialogue.core.DialogueChannel) PartialServiceConfiguration(com.palantir.conjure.java.api.config.service.PartialServiceConfiguration) SafeIllegalStateException(com.palantir.logsafe.exceptions.SafeIllegalStateException)

Example 24 with SafeIllegalStateException

use of com.palantir.logsafe.exceptions.SafeIllegalStateException in project conjure-java by palantir.

the class ParamTypesResolver method getParameterType.

@SuppressWarnings("CyclomaticComplexity")
public Optional<ParameterType> getParameterType(VariableElement variableElement) {
    List<AnnotationMirror> paramAnnotationMirrors = new ArrayList<>();
    for (AnnotationMirror annotationMirror : variableElement.getAnnotationMirrors()) {
        TypeElement annotationTypeElement = MoreElements.asType(annotationMirror.getAnnotationType().asElement());
        if (SUPPORTED_ANNOTATIONS.contains(annotationTypeElement.getQualifiedName().toString())) {
            paramAnnotationMirrors.add(annotationMirror);
        }
    }
    List<AnnotationReflector> annotationReflectors = paramAnnotationMirrors.stream().map(ImmutableAnnotationReflector::of).collect(Collectors.toList());
    boolean isSafe = annotationReflectors.stream().anyMatch(annotation -> annotation.isAnnotation(Safe.class));
    boolean isUnsafe = annotationReflectors.stream().anyMatch(annotation -> annotation.isAnnotation(Unsafe.class));
    SafeLoggingAnnotation safeLoggable = isUnsafe ? SafeLoggingAnnotation.UNSAFE : isSafe ? SafeLoggingAnnotation.SAFE : SafeLoggingAnnotation.UNKNOWN;
    List<AnnotationReflector> otherAnnotationReflectors = annotationReflectors.stream().filter(annotation -> !annotation.isAnnotation(Safe.class) && !annotation.isAnnotation(Unsafe.class)).collect(Collectors.toList());
    if (otherAnnotationReflectors.isEmpty()) {
        if (!safeLoggable.equals(SafeLoggingAnnotation.UNKNOWN)) {
            context.reportError("Parameter type cannot be annotated with safe logging annotations", variableElement, SafeArg.of("type", variableElement.asType()));
            return Optional.empty();
        }
        if (context.isSameTypes(variableElement.asType(), AuthHeader.class)) {
            return Optional.of(ParameterTypes.authHeader(variableElement.getSimpleName().toString()));
        } else if (context.isSameTypes(variableElement.asType(), HttpServerExchange.class)) {
            return Optional.of(ParameterTypes.exchange());
        } else if (context.isSameTypes(variableElement.asType(), RequestContext.class)) {
            return Optional.of(ParameterTypes.context());
        } else {
            context.reportError("At least one annotation should be present or type should be InputStream", variableElement, SafeArg.of("requestBody", InputStream.class), SafeArg.of("supportedAnnotations", PARAM_ANNOTATION_CLASSES));
            return Optional.empty();
        }
    }
    if (otherAnnotationReflectors.size() > 1) {
        context.reportError("Only single annotation can be used", variableElement, SafeArg.of("annotations", otherAnnotationReflectors));
        return Optional.empty();
    }
    // TODO(ckozak): More validation of values.
    AnnotationReflector annotationReflector = Iterables.getOnlyElement(otherAnnotationReflectors);
    if (annotationReflector.isAnnotation(Handle.Body.class)) {
        return Optional.of(bodyParameter(variableElement, annotationReflector));
    } else if (annotationReflector.isAnnotation(Handle.Header.class)) {
        return Optional.of(headerParameter(variableElement, annotationReflector, safeLoggable));
    } else if (annotationReflector.isAnnotation(Handle.PathParam.class)) {
        return Optional.of(pathParameter(variableElement, annotationReflector, safeLoggable));
    } else if (annotationReflector.isAnnotation(Handle.PathMultiParam.class)) {
        return Optional.of(pathMultiParameter(variableElement, annotationReflector, safeLoggable));
    } else if (annotationReflector.isAnnotation(Handle.QueryParam.class)) {
        return Optional.of(queryParameter(variableElement, annotationReflector, safeLoggable));
    } else if (annotationReflector.isAnnotation(Handle.Cookie.class)) {
        return cookieParameter(variableElement, annotationReflector, safeLoggable);
    }
    throw new SafeIllegalStateException("Not possible");
}
Also used : SafeLoggingAnnotation(com.palantir.conjure.java.undertow.processor.data.ParameterType.SafeLoggingAnnotation) Iterables(com.google.common.collect.Iterables) SafeIllegalStateException(com.palantir.logsafe.exceptions.SafeIllegalStateException) HttpServerExchange(io.undertow.server.HttpServerExchange) VariableElement(javax.lang.model.element.VariableElement) AuthHeader(com.palantir.tokens.auth.AuthHeader) TypeElement(javax.lang.model.element.TypeElement) RequestContext(com.palantir.conjure.java.undertow.lib.RequestContext) ArrayList(java.util.ArrayList) SafeArg(com.palantir.logsafe.SafeArg) BearerToken(com.palantir.tokens.auth.BearerToken) CodeBlock(com.squareup.javapoet.CodeBlock) Handle(com.palantir.conjure.java.undertow.annotations.Handle) MoreElements(com.google.auto.common.MoreElements) ImmutableSet(com.google.common.collect.ImmutableSet) ContainerType(com.palantir.conjure.java.undertow.processor.data.DefaultDecoderNames.ContainerType) Set(java.util.Set) Collectors(java.util.stream.Collectors) AnnotationMirror(javax.lang.model.element.AnnotationMirror) List(java.util.List) TypeMirror(javax.lang.model.type.TypeMirror) Safe(com.palantir.logsafe.Safe) Stream(java.util.stream.Stream) Unsafe(com.palantir.logsafe.Unsafe) Optional(java.util.Optional) DefaultParamDecoder(com.palantir.conjure.java.undertow.annotations.DefaultParamDecoder) InputStream(java.io.InputStream) SafeLoggingAnnotation(com.palantir.conjure.java.undertow.processor.data.ParameterType.SafeLoggingAnnotation) TypeElement(javax.lang.model.element.TypeElement) InputStream(java.io.InputStream) ArrayList(java.util.ArrayList) Unsafe(com.palantir.logsafe.Unsafe) Safe(com.palantir.logsafe.Safe) Handle(com.palantir.conjure.java.undertow.annotations.Handle) HttpServerExchange(io.undertow.server.HttpServerExchange) AnnotationMirror(javax.lang.model.element.AnnotationMirror) AuthHeader(com.palantir.tokens.auth.AuthHeader) SafeIllegalStateException(com.palantir.logsafe.exceptions.SafeIllegalStateException)

Aggregations

SafeIllegalStateException (com.palantir.logsafe.exceptions.SafeIllegalStateException)24 VisibleForTesting (com.google.common.annotations.VisibleForTesting)5 ImmutableSet (com.google.common.collect.ImmutableSet)5 Set (java.util.Set)5 ImmutableList (com.google.common.collect.ImmutableList)4 Iterables (com.google.common.collect.Iterables)4 SafeArg (com.palantir.logsafe.SafeArg)4 ArrayList (java.util.ArrayList)4 HashMap (java.util.HashMap)4 List (java.util.List)4 Optional (java.util.Optional)4 Collectors (java.util.stream.Collectors)4 Suppliers (com.google.common.base.Suppliers)3 RangeMap (com.google.common.collect.RangeMap)3 Sets (com.google.common.collect.Sets)3 CassandraKeyValueServiceConfig (com.palantir.atlasdb.cassandra.CassandraKeyValueServiceConfig)3 Refreshable (com.palantir.refreshable.Refreshable)3 Map (java.util.Map)3 RetryException (com.github.rholder.retry.RetryException)2 ImmutableMap (com.google.common.collect.ImmutableMap)2