Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Add support for custom COAP requests logging #99

Merged
merged 5 commits into from
Sep 4, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@
*/
package com.mbed.coap.server;

import static com.mbed.coap.transport.CoapTransport.logSent;
import static com.mbed.coap.transport.TransportContext.RESPONSE_TIMEOUT;
import static com.mbed.coap.utils.Timer.toTimer;
import static com.mbed.coap.utils.Validations.require;
Expand Down Expand Up @@ -50,6 +49,7 @@
import com.mbed.coap.server.observe.ObservationsStore;
import com.mbed.coap.transmission.RetransmissionBackOff;
import com.mbed.coap.transport.CoapTransport;
import com.mbed.coap.transport.LoggingCoapTransport;
import com.mbed.coap.utils.Filter;
import com.mbed.coap.utils.Service;
import com.mbed.coap.utils.Timer;
Expand Down Expand Up @@ -80,9 +80,11 @@
private int maxQueueSize = 100;
private Filter.SimpleFilter<CoapRequest, CoapResponse> outboundFilter = Filter.identity();
private Filter.SimpleFilter<CoapRequest, CoapResponse> routeFilter = Filter.identity();
private Filter.SimpleFilter<CoapRequest, CoapResponse> inboundRequestFilter = Filter.identity();
private NotificationsReceiver notificationsReceiver = NotificationsReceiver.REJECT_ALL;
private ObservationsStore observationStore = ObservationsStore.ALWAYS_EMPTY;
private RequestTagSupplier requestTagSupplier = RequestTagSupplier.createSequential();
private boolean isTransportLoggingEnabled = true;

CoapServerBuilder() {
}
Expand Down Expand Up @@ -118,6 +120,11 @@
return this;
}

public CoapServerBuilder inboundRequestFilter(Filter.SimpleFilter<CoapRequest, CoapResponse> inboundRequestFilter) {
this.inboundRequestFilter = requireNonNull(inboundRequestFilter);
return this;

Check warning on line 125 in coap-core/src/main/java/com/mbed/coap/server/CoapServerBuilder.java

View check run for this annotation

Codecov / codecov/patch

coap-core/src/main/java/com/mbed/coap/server/CoapServerBuilder.java#L124-L125

Added lines #L124 - L125 were not covered by tests
}

public CoapServerBuilder outboundFilter(Filter.SimpleFilter<CoapRequest, CoapResponse> outboundFilter) {
this.outboundFilter = requireNonNull(outboundFilter);
return this;
Expand Down Expand Up @@ -216,14 +223,19 @@
return this;
}

public CoapServerBuilder transportLogging(boolean isTransportLoggingEnabled) {
this.isTransportLoggingEnabled = isTransportLoggingEnabled;
return this;

Check warning on line 228 in coap-core/src/main/java/com/mbed/coap/server/CoapServerBuilder.java

View check run for this annotation

Codecov / codecov/patch

coap-core/src/main/java/com/mbed/coap/server/CoapServerBuilder.java#L227-L228

Added lines #L227 - L228 were not covered by tests
}

public CoapServer build() {
CoapTransport coapTransport = requireNonNull(this.coapTransport.get(), "Missing transport");
CoapTransport realTransport = requireNonNull(this.coapTransport.get(), "Missing transport");
CoapTransport coapTransport = isTransportLoggingEnabled ? new LoggingCoapTransport(realTransport) : realTransport;
final boolean stopExecutor = scheduledExecutorService == null;
final ScheduledExecutorService effectiveExecutorService = scheduledExecutorService != null ? scheduledExecutorService : Executors.newSingleThreadScheduledExecutor();
Timer timer = toTimer(effectiveExecutorService);

Service<CoapPacket, Boolean> sender = packet -> coapTransport.sendPacket(packet)
.whenComplete((__, throwable) -> logSent(packet, throwable));
Service<CoapPacket, Boolean> sender = coapTransport::sendPacket;

// OUTBOUND
ExchangeFilter exchangeFilter = new ExchangeFilter();
Expand Down Expand Up @@ -259,6 +271,7 @@
DuplicateDetector duplicateDetector = new DuplicateDetector(duplicateDetectorCache, duplicatedCoapMessageCallback);
Service<CoapPacket, CoapPacket> inboundService = duplicateDetector
.andThen(new CoapRequestConverter(midSupplier))
.andThen(inboundRequestFilter)
.andThen(new RescueFilter())
.andThen(new CriticalOptionVerifier())
.andThen(new BlockWiseIncomingFilter(capabilities(), maxIncomingBlockTransferSize))
Expand Down Expand Up @@ -295,5 +308,4 @@

return new CoapServerGroup(servers);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
*/
package com.mbed.coap.server.messaging;

import static com.mbed.coap.transport.CoapTransport.logReceived;
import static com.mbed.coap.utils.FutureHelpers.logError;
import static com.mbed.coap.utils.FutureHelpers.logErrorIgnoreCancelled;
import static java.util.Objects.requireNonNull;
Expand Down Expand Up @@ -49,7 +48,6 @@ public CoapDispatcher(Service<CoapPacket, Boolean> sender,
}

public void handle(CoapPacket packet) {
logReceived(packet);
if (handlePing(packet)) {
return;
}
Expand Down
30 changes: 0 additions & 30 deletions coap-core/src/main/java/com/mbed/coap/transport/CoapTransport.java
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,8 @@
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.concurrent.CompletableFuture;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public interface CoapTransport {
Logger LOGGER = LoggerFactory.getLogger(CoapTransport.class);

void start() throws IOException;

void stop();
Expand All @@ -34,30 +30,4 @@ public interface CoapTransport {
CompletableFuture<CoapPacket> receive();

InetSocketAddress getLocalSocketAddress();

static void logSent(CoapPacket packet, Throwable maybeError) {
if (maybeError != null) {
LOGGER.warn("[{}] CoAP sent failed [{}] {}", packet.getRemoteAddrString(), packet.toString(false, false, false, true), maybeError.toString());
return;
}

if (LOGGER.isTraceEnabled()) {
LOGGER.trace("CoAP sent [{}]", packet.toString(true));
} else if (LOGGER.isDebugEnabled()) {
LOGGER.debug("CoAP sent [{}]", packet.toString(false));
} else if (LOGGER.isInfoEnabled()) {
LOGGER.info("[{}] CoAP sent [{}]", packet.getRemoteAddrString(), packet.toString(false, false, false, true));
}
}

static void logReceived(CoapPacket packet) {
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("CoAP received [{}]", packet.toString(true));
} else if (LOGGER.isDebugEnabled()) {
LOGGER.debug("[{}] CoAP received [{}]", packet.getRemoteAddrString(), packet.toString(false));
} else if (LOGGER.isInfoEnabled()) {
LOGGER.info("[{}] CoAP received [{}]", packet.getRemoteAddrString(), packet.toString(false, false, false, true));
}
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
/*
* Copyright (C) 2022-2024 java-coap contributors (https://github.com/open-coap/java-coap)
* SPDX-License-Identifier: Apache-2.0
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.mbed.coap.transport;

import com.mbed.coap.packet.CoapPacket;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.concurrent.CompletableFuture;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class LoggingCoapTransport implements CoapTransport {
akolosov-n marked this conversation as resolved.
Show resolved Hide resolved
private static Logger LOGGER = LoggerFactory.getLogger(LoggingCoapTransport.class);

private final CoapTransport transport;

public LoggingCoapTransport(CoapTransport transport) {
this.transport = transport;
}

@Override
public void start() throws IOException {
transport.start();
}

@Override
public void stop() {
transport.stop();
}

@Override
public CompletableFuture<Boolean> sendPacket(CoapPacket coapPacket) {
return transport.sendPacket(coapPacket).whenComplete((sent, error) -> {
logSent(coapPacket, error);
});
}

@Override
public CompletableFuture<CoapPacket> receive() {
return transport.receive().whenComplete((packet, __) -> {
if (packet != null) {
logReceived(packet);
}
});
}

@Override
public InetSocketAddress getLocalSocketAddress() {
return transport.getLocalSocketAddress();
}

private void logSent(CoapPacket packet, Throwable maybeError) {
if (maybeError != null) {
LOGGER.warn("[{}] CoAP sent failed [{}] {}", packet.getRemoteAddrString(), packet.toString(false, false, false, true), maybeError.toString());
return;
}

if (LOGGER.isTraceEnabled()) {
LOGGER.trace("CoAP sent [{}]", packet.toString(true));
} else if (LOGGER.isDebugEnabled()) {
LOGGER.debug("CoAP sent [{}]", packet.toString(false));

Check warning on line 74 in coap-core/src/main/java/com/mbed/coap/transport/LoggingCoapTransport.java

View check run for this annotation

Codecov / codecov/patch

coap-core/src/main/java/com/mbed/coap/transport/LoggingCoapTransport.java#L74

Added line #L74 was not covered by tests
} else if (LOGGER.isInfoEnabled()) {
LOGGER.info("[{}] CoAP sent [{}]", packet.getRemoteAddrString(), packet.toString(false, false, false, true));

Check warning on line 76 in coap-core/src/main/java/com/mbed/coap/transport/LoggingCoapTransport.java

View check run for this annotation

Codecov / codecov/patch

coap-core/src/main/java/com/mbed/coap/transport/LoggingCoapTransport.java#L76

Added line #L76 was not covered by tests
}
}

private void logReceived(CoapPacket packet) {
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("CoAP received [{}]", packet.toString(true));
} else if (LOGGER.isDebugEnabled()) {
LOGGER.debug("[{}] CoAP received [{}]", packet.getRemoteAddrString(), packet.toString(false));

Check warning on line 84 in coap-core/src/main/java/com/mbed/coap/transport/LoggingCoapTransport.java

View check run for this annotation

Codecov / codecov/patch

coap-core/src/main/java/com/mbed/coap/transport/LoggingCoapTransport.java#L84

Added line #L84 was not covered by tests
} else if (LOGGER.isInfoEnabled()) {
LOGGER.info("[{}] CoAP received [{}]", packet.getRemoteAddrString(), packet.toString(false, false, false, true));

Check warning on line 86 in coap-core/src/main/java/com/mbed/coap/transport/LoggingCoapTransport.java

View check run for this annotation

Codecov / codecov/patch

coap-core/src/main/java/com/mbed/coap/transport/LoggingCoapTransport.java#L86

Added line #L86 was not covered by tests
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@
*/
package com.mbed.coap.server;

import static com.mbed.coap.transport.CoapTransport.logSent;
import static java.util.Objects.requireNonNull;
import com.mbed.coap.client.CoapClient;
import com.mbed.coap.packet.BlockSize;
Expand All @@ -39,6 +38,7 @@
import com.mbed.coap.server.observe.NotificationsReceiver;
import com.mbed.coap.server.observe.ObservationsStore;
import com.mbed.coap.transport.CoapTcpTransport;
import com.mbed.coap.transport.LoggingCoapTransport;
import com.mbed.coap.utils.Filter;
import com.mbed.coap.utils.Service;
import java.io.IOException;
Expand All @@ -58,6 +58,7 @@
private Filter.SimpleFilter<CoapRequest, CoapResponse> routeFilter = Filter.identity();
private NotificationsReceiver notificationsReceiver = NotificationsReceiver.REJECT_ALL;
private ObservationsStore observationsStore = ObservationsStore.ALWAYS_EMPTY;
private Boolean isTransportLoggingEnabled = true;

CoapServerBuilderForTcp() {
csmStorage = new CapabilitiesStorageImpl();
Expand Down Expand Up @@ -129,14 +130,17 @@
return this;
}

public CoapServerBuilderForTcp transportLogging(Boolean transportLogging) {
this.isTransportLoggingEnabled = requireNonNull(transportLogging);
return this;

Check warning on line 135 in coap-tcp/src/main/java/com/mbed/coap/server/CoapServerBuilderForTcp.java

View check run for this annotation

Codecov / codecov/patch

coap-tcp/src/main/java/com/mbed/coap/server/CoapServerBuilderForTcp.java#L134-L135

Added lines #L134 - L135 were not covered by tests
}

public CoapClient buildClient(InetSocketAddress target) throws IOException {
return CoapClient.create(target, build().start(), r -> r.getCode() == Code.C703_PONG);
}

public CoapServer build() {
Service<CoapPacket, Boolean> sender = packet -> coapTransport
.sendPacket(packet)
.whenComplete((__, throwable) -> logSent(packet, throwable));
Service<CoapPacket, Boolean> sender = (isTransportLoggingEnabled ? new LoggingCoapTransport(coapTransport) : coapTransport)::sendPacket;

// NOTIFICATION
Service<SeparateResponse, Boolean> sendNotification = new NotificationValidator()
Expand Down Expand Up @@ -182,5 +186,4 @@
private boolean hasRoute() {
return !Objects.equals(route, RouterService.NOT_FOUND_SERVICE);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
*/
package com.mbed.coap.server.messaging;

import static com.mbed.coap.transport.CoapTransport.logReceived;
import static com.mbed.coap.utils.FutureHelpers.logError;
import com.mbed.coap.packet.CoapPacket;
import com.mbed.coap.packet.CoapRequest;
Expand Down Expand Up @@ -54,8 +53,6 @@ public CoapTcpDispatcher(Service<CoapPacket, Boolean> sender, CapabilitiesStorag
}

public void handle(CoapPacket packet) {
logReceived(packet);

// EMPTY (healthcheck)
if (packet.getCode() == null && packet.getMethod() == null) {
// ignore
Expand Down