Search in sources :

Example 31 with Message

use of io.vertx.core.eventbus.Message in project hono by eclipse.

the class LoraProtocolAdapter method handleCommand.

private void handleCommand(final CommandContext commandContext) {
    Tags.COMPONENT.set(commandContext.getTracingSpan(), getTypeName());
    final Sample timer = metrics.startTimer();
    final Command command = commandContext.getCommand();
    if (command.getGatewayId() == null) {
        final String errorMsg = "no gateway defined for command";
        LOG.debug("{} [{}]", errorMsg, command);
        commandContext.release(new ServerErrorException(HttpURLConnection.HTTP_UNAVAILABLE, errorMsg));
        return;
    }
    final String tenant = command.getTenant();
    final String gatewayId = command.getGatewayId();
    final LoraProvider loraProvider = Optional.ofNullable(commandSubscriptions.get(new SubscriptionKey(tenant, gatewayId))).map(Pair::two).orElse(null);
    if (loraProvider == null) {
        LOG.debug("received command for unknown gateway [{}] for tenant [{}]", gatewayId, tenant);
        TracingHelper.logError(commandContext.getTracingSpan(), String.format("received command for unknown gateway [%s]", gatewayId));
        commandContext.release(new ServerErrorException(HttpURLConnection.HTTP_UNAVAILABLE, "received command for unknown gateway"));
        return;
    }
    final Future<TenantObject> tenantTracker = getTenantConfiguration(tenant, commandContext.getTracingContext());
    tenantTracker.compose(tenantObject -> {
        if (command.isValid()) {
            return checkMessageLimit(tenantObject, command.getPayloadSize(), commandContext.getTracingContext());
        } else {
            return Future.failedFuture(new ClientErrorException(HttpURLConnection.HTTP_BAD_REQUEST, "malformed command message"));
        }
    }).compose(success -> getRegistrationClient().assertRegistration(tenant, gatewayId, null, commandContext.getTracingContext())).compose(registrationAssertion -> sendCommandToGateway(commandContext, loraProvider, registrationAssertion.getCommandEndpoint())).onSuccess(aVoid -> {
        addMicrometerSample(commandContext, timer);
        commandContext.accept();
        metrics.reportCommand(command.isOneWay() ? Direction.ONE_WAY : Direction.REQUEST, tenant, tenantTracker.result(), MetricsTags.ProcessingOutcome.FORWARDED, command.getPayloadSize(), timer);
    }).onFailure(t -> {
        LOG.debug("error sending command", t);
        commandContext.release(t);
        metrics.reportCommand(command.isOneWay() ? Direction.ONE_WAY : Direction.REQUEST, tenant, tenantTracker.result(), MetricsTags.ProcessingOutcome.from(t), command.getPayloadSize(), timer);
    });
}
Also used : HttpURLConnection(java.net.HttpURLConnection) LoraProviderMalformedPayloadException(org.eclipse.hono.adapter.lora.providers.LoraProviderMalformedPayloadException) LoggerFactory(org.slf4j.LoggerFactory) Router(io.vertx.ext.web.Router) Tag(io.opentracing.tag.Tag) RoutingContext(io.vertx.ext.web.RoutingContext) Tags(io.opentracing.tag.Tags) Map(java.util.Map) Pair(org.eclipse.hono.util.Pair) Fields(io.opentracing.log.Fields) JsonObject(io.vertx.core.json.JsonObject) TracingHelper(org.eclipse.hono.tracing.TracingHelper) TenantServiceBasedX509Authentication(org.eclipse.hono.adapter.auth.device.TenantServiceBasedX509Authentication) ChainAuthHandler(io.vertx.ext.web.handler.ChainAuthHandler) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) CommandContext(org.eclipse.hono.client.command.CommandContext) MetricsTags(org.eclipse.hono.service.metric.MetricsTags) Message(io.vertx.core.eventbus.Message) EventConstants(org.eclipse.hono.util.EventConstants) StringTag(io.opentracing.tag.StringTag) Future(io.vertx.core.Future) HonoBasicAuthHandler(org.eclipse.hono.adapter.http.HonoBasicAuthHandler) Device(org.eclipse.hono.auth.Device) Objects(java.util.Objects) List(java.util.List) Buffer(io.vertx.core.buffer.Buffer) X509AuthHandler(org.eclipse.hono.adapter.http.X509AuthHandler) CommandConsumer(org.eclipse.hono.client.command.CommandConsumer) Optional(java.util.Optional) Span(io.opentracing.Span) UsernamePasswordCredentials(org.eclipse.hono.adapter.auth.device.UsernamePasswordCredentials) CommandEndpoint(org.eclipse.hono.util.CommandEndpoint) HttpContext(org.eclipse.hono.service.http.HttpContext) Json(io.vertx.core.json.Json) LoraProvider(org.eclipse.hono.adapter.lora.providers.LoraProvider) WebClient(io.vertx.ext.web.client.WebClient) Command(org.eclipse.hono.client.command.Command) ClientErrorException(org.eclipse.hono.client.ClientErrorException) TenantDisabledOrNotRegisteredException(org.eclipse.hono.client.registry.TenantDisabledOrNotRegisteredException) Constants(org.eclipse.hono.util.Constants) ArrayList(java.util.ArrayList) TracingHandler(org.eclipse.hono.service.http.TracingHandler) CompositeFuture(io.vertx.core.CompositeFuture) StatusCodeMapper(org.eclipse.hono.client.StatusCodeMapper) HttpUtils(org.eclipse.hono.service.http.HttpUtils) LinkedList(java.util.LinkedList) UsernamePasswordAuthProvider(org.eclipse.hono.adapter.auth.device.UsernamePasswordAuthProvider) Logger(org.slf4j.Logger) Direction(org.eclipse.hono.service.metric.MetricsTags.Direction) AbstractVertxBasedHttpProtocolAdapter(org.eclipse.hono.adapter.http.AbstractVertxBasedHttpProtocolAdapter) Promise(io.vertx.core.Promise) ServerErrorException(org.eclipse.hono.client.ServerErrorException) Sample(io.micrometer.core.instrument.Timer.Sample) TenantObject(org.eclipse.hono.util.TenantObject) SpanContext(io.opentracing.SpanContext) HttpRequest(io.vertx.ext.web.client.HttpRequest) DeviceCredentialsAuthProvider(org.eclipse.hono.adapter.auth.device.DeviceCredentialsAuthProvider) X509AuthProvider(org.eclipse.hono.adapter.auth.device.X509AuthProvider) HttpMethod(io.vertx.core.http.HttpMethod) HttpProtocolAdapterProperties(org.eclipse.hono.adapter.http.HttpProtocolAdapterProperties) SubjectDnCredentials(org.eclipse.hono.adapter.auth.device.SubjectDnCredentials) TenantObject(org.eclipse.hono.util.TenantObject) LoraProvider(org.eclipse.hono.adapter.lora.providers.LoraProvider) Command(org.eclipse.hono.client.command.Command) Sample(io.micrometer.core.instrument.Timer.Sample) ClientErrorException(org.eclipse.hono.client.ClientErrorException) ServerErrorException(org.eclipse.hono.client.ServerErrorException)

Example 32 with Message

use of io.vertx.core.eventbus.Message in project hono by eclipse.

the class LoraProtocolAdapter method handleTenantTimeout.

private void handleTenantTimeout(final Message<String> msg) {
    final String tenantId = msg.body();
    log.debug("check command subscriptions on timeout of tenant [{}]", tenantId);
    final Span span = TracingHelper.buildSpan(tracer, null, "check command subscriptions on tenant timeout", getClass().getSimpleName()).withTag(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_CLIENT).start();
    TracingHelper.setDeviceTags(span, tenantId, null);
    // check if tenant still exists
    getTenantConfiguration(tenantId, span.context()).recover(thr -> {
        if (thr instanceof TenantDisabledOrNotRegisteredException) {
            log.debug("tenant [{}] disabled or removed, removing corresponding command consumers", tenantId);
            span.log("tenant disabled or removed, corresponding command consumers will be closed");
            @SuppressWarnings("rawtypes") final List<Future> consumerCloseFutures = new LinkedList<>();
            for (final var iter = commandSubscriptions.entrySet().iterator(); iter.hasNext(); ) {
                final var entry = iter.next();
                if (entry.getKey().getTenant().equals(tenantId)) {
                    final CommandConsumer commandConsumer = entry.getValue().one();
                    consumerCloseFutures.add(commandConsumer.close(span.context()));
                    iter.remove();
                }
            }
            return CompositeFuture.join(consumerCloseFutures).mapEmpty();
        } else {
            return Future.failedFuture(thr);
        }
    }).onFailure(thr -> TracingHelper.logError(span, thr)).onComplete(ar -> span.finish());
}
Also used : HttpURLConnection(java.net.HttpURLConnection) LoraProviderMalformedPayloadException(org.eclipse.hono.adapter.lora.providers.LoraProviderMalformedPayloadException) LoggerFactory(org.slf4j.LoggerFactory) Router(io.vertx.ext.web.Router) Tag(io.opentracing.tag.Tag) RoutingContext(io.vertx.ext.web.RoutingContext) Tags(io.opentracing.tag.Tags) Map(java.util.Map) Pair(org.eclipse.hono.util.Pair) Fields(io.opentracing.log.Fields) JsonObject(io.vertx.core.json.JsonObject) TracingHelper(org.eclipse.hono.tracing.TracingHelper) TenantServiceBasedX509Authentication(org.eclipse.hono.adapter.auth.device.TenantServiceBasedX509Authentication) ChainAuthHandler(io.vertx.ext.web.handler.ChainAuthHandler) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) CommandContext(org.eclipse.hono.client.command.CommandContext) MetricsTags(org.eclipse.hono.service.metric.MetricsTags) Message(io.vertx.core.eventbus.Message) EventConstants(org.eclipse.hono.util.EventConstants) StringTag(io.opentracing.tag.StringTag) Future(io.vertx.core.Future) HonoBasicAuthHandler(org.eclipse.hono.adapter.http.HonoBasicAuthHandler) Device(org.eclipse.hono.auth.Device) Objects(java.util.Objects) List(java.util.List) Buffer(io.vertx.core.buffer.Buffer) X509AuthHandler(org.eclipse.hono.adapter.http.X509AuthHandler) CommandConsumer(org.eclipse.hono.client.command.CommandConsumer) Optional(java.util.Optional) Span(io.opentracing.Span) UsernamePasswordCredentials(org.eclipse.hono.adapter.auth.device.UsernamePasswordCredentials) CommandEndpoint(org.eclipse.hono.util.CommandEndpoint) HttpContext(org.eclipse.hono.service.http.HttpContext) Json(io.vertx.core.json.Json) LoraProvider(org.eclipse.hono.adapter.lora.providers.LoraProvider) WebClient(io.vertx.ext.web.client.WebClient) Command(org.eclipse.hono.client.command.Command) ClientErrorException(org.eclipse.hono.client.ClientErrorException) TenantDisabledOrNotRegisteredException(org.eclipse.hono.client.registry.TenantDisabledOrNotRegisteredException) Constants(org.eclipse.hono.util.Constants) ArrayList(java.util.ArrayList) TracingHandler(org.eclipse.hono.service.http.TracingHandler) CompositeFuture(io.vertx.core.CompositeFuture) StatusCodeMapper(org.eclipse.hono.client.StatusCodeMapper) HttpUtils(org.eclipse.hono.service.http.HttpUtils) LinkedList(java.util.LinkedList) UsernamePasswordAuthProvider(org.eclipse.hono.adapter.auth.device.UsernamePasswordAuthProvider) Logger(org.slf4j.Logger) Direction(org.eclipse.hono.service.metric.MetricsTags.Direction) AbstractVertxBasedHttpProtocolAdapter(org.eclipse.hono.adapter.http.AbstractVertxBasedHttpProtocolAdapter) Promise(io.vertx.core.Promise) ServerErrorException(org.eclipse.hono.client.ServerErrorException) Sample(io.micrometer.core.instrument.Timer.Sample) TenantObject(org.eclipse.hono.util.TenantObject) SpanContext(io.opentracing.SpanContext) HttpRequest(io.vertx.ext.web.client.HttpRequest) DeviceCredentialsAuthProvider(org.eclipse.hono.adapter.auth.device.DeviceCredentialsAuthProvider) X509AuthProvider(org.eclipse.hono.adapter.auth.device.X509AuthProvider) HttpMethod(io.vertx.core.http.HttpMethod) HttpProtocolAdapterProperties(org.eclipse.hono.adapter.http.HttpProtocolAdapterProperties) SubjectDnCredentials(org.eclipse.hono.adapter.auth.device.SubjectDnCredentials) CommandConsumer(org.eclipse.hono.client.command.CommandConsumer) Future(io.vertx.core.Future) CompositeFuture(io.vertx.core.CompositeFuture) TenantDisabledOrNotRegisteredException(org.eclipse.hono.client.registry.TenantDisabledOrNotRegisteredException) Span(io.opentracing.Span) LinkedList(java.util.LinkedList)

Example 33 with Message

use of io.vertx.core.eventbus.Message in project vert.x by eclipse.

the class JSONEventBusTest method testChangesNotVisibleArray3.

@Test
public void testChangesNotVisibleArray3() {
    List<Object> list = new ArrayList<>();
    final JsonArray obj = new JsonArray(list);
    eb.<JsonArray>consumer("foo").handler((Message<JsonArray> msg) -> {
        vertx.setTimer(1000, id -> {
            assertEquals(0, msg.body().size());
            testComplete();
        });
    });
    eb.send("foo", obj);
    list.add("uhwqdiuh");
    await();
}
Also used : JsonArray(io.vertx.core.json.JsonArray) Message(io.vertx.core.eventbus.Message) ArrayList(java.util.ArrayList) JsonObject(io.vertx.core.json.JsonObject) Test(org.junit.Test)

Example 34 with Message

use of io.vertx.core.eventbus.Message in project vert.x by eclipse.

the class JSONEventBusTest method testChangesNotVisibleObject2.

@Test
public void testChangesNotVisibleObject2() {
    final JsonObject obj = new JsonObject();
    eb.<JsonObject>consumer("foo").handler((Message<JsonObject> msg) -> {
        msg.body().put("b", "uqwduihwqd");
    });
    eb.send("foo", obj);
    vertx.setTimer(1000, id -> {
        assertFalse(obj.containsKey("b"));
        testComplete();
    });
    await();
}
Also used : Message(io.vertx.core.eventbus.Message) JsonObject(io.vertx.core.json.JsonObject) Test(org.junit.Test)

Example 35 with Message

use of io.vertx.core.eventbus.Message in project vert.x by eclipse.

the class JSONEventBusTest method testChangesNotVisibleArray1.

@Test
public void testChangesNotVisibleArray1() {
    JsonArray obj = new JsonArray();
    eb.<JsonArray>consumer("foo").handler((Message<JsonArray> msg) -> {
        assertEquals(0, msg.body().size());
        testComplete();
    });
    eb.send("foo", obj);
    obj.add("blah");
    await();
}
Also used : JsonArray(io.vertx.core.json.JsonArray) Message(io.vertx.core.eventbus.Message) Test(org.junit.Test)

Aggregations

Message (io.vertx.core.eventbus.Message)53 JsonObject (io.vertx.core.json.JsonObject)37 Test (org.junit.Test)33 Async (io.vertx.ext.unit.Async)19 Vertx (io.vertx.core.Vertx)18 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)17 Before (org.junit.Before)17 PermittedOptions (io.vertx.ext.bridge.PermittedOptions)16 Handler (io.vertx.core.Handler)15 BridgeOptions (io.vertx.ext.bridge.BridgeOptions)15 TestContext (io.vertx.ext.unit.TestContext)15 VertxUnitRunner (io.vertx.ext.unit.junit.VertxUnitRunner)14 After (org.junit.After)14 RunWith (org.junit.runner.RunWith)14 NetServerOptions (io.vertx.core.net.NetServerOptions)12 BridgeEventType (io.vertx.ext.bridge.BridgeEventType)12 JsonArray (io.vertx.core.json.JsonArray)11 NetClient (io.vertx.core.net.NetClient)11 NetSocket (io.vertx.core.net.NetSocket)11 FrameHelper (io.vertx.ext.eventbus.bridge.tcp.impl.protocol.FrameHelper)11