mirror of
https://github.com/floci-io/floci.git
synced 2026-11-29 16:35:29 -05:00
feat(iot): search fleet things by connectivity status (#6025)
* feat(iot): search fleet things by connectivity status SearchIndex refused every connectivity field and its documents carried no connectivity, so an application that finds its things by connection state got InvalidQueryException. With connectivity indexing on, a thing now reports the MQTT broker session whose client id is its name, and connectivity.connected, connectivity.clientId and connectivity.disconnectReason can be searched. The other connectivity fields are still refused with InvalidQueryException. A thing whose client id never connected reports connected false and timestamp 0, as on AWS. The broker now records the account, region, connect time, keep alive and clean session of each session, and keeps in memory how the last one of each client id ended in each account and region, until a state reset. The reason is the one the session's disconnected lifecycle event carries, recorded by the same single endSession under the session lock, so the late end of a displaced session cannot overwrite its successor's. A plaintext session counts in the default account and region, a TLS session in its certificate's. Closes #4912 * fix(iot): serialize connectivity reads and resets with session ends A connectivity lookup read the live session without the session lock, so a search racing DeleteConnection could see the session connected after its disconnect was recorded. A state reset cleared the history without the lock too. Both now run under the session lock; the lookup tests the session's ended flag instead of the endpoint, as the lock is never held across endpoint calls. Tests cover the reset contract, a lookup and a reset racing a held DeleteConnection, and a TLS session counting in its certificate's account and region.
This commit is contained in:
1 parent
1eb402d623
commit
34d904fde5
11 files changed
+536
-67
No files matched your search
@@ -15,15 +15,15 @@ import java.util.regex.Pattern;
|
||||
* The part of the AWS IoT fleet indexing query language Floci evaluates, parsed into a predicate
|
||||
* over a thing's index document. Precedence is the one measured on AWS: NOT binds tightest, then
|
||||
* AND, then OR, and whitespace is an AND looser than OR, so {@code a OR b c} is
|
||||
* {@code (a OR b) AND c}. Values match case-insensitively, field names exactly. Floci evaluates the
|
||||
* registry fields and attributes; connectivity, shadow and Device Defender fields are refused, with
|
||||
* AWS's error while their indexing is off. Syntax AWS accepts but Floci does not evaluate is refused
|
||||
* rather than matching nothing. A query is checked in the order measured on AWS: syntax, then the
|
||||
* 12-term limit, then fields and values, the first such error in the query winning.
|
||||
* {@code (a OR b) AND c}. Values match case-insensitively, field names exactly. Syntax AWS accepts
|
||||
* but Floci does not evaluate is refused rather than matching nothing. A query is checked in the
|
||||
* order measured on AWS: syntax, then the 12-term limit, then fields and values, the first such
|
||||
* error in the query winning.
|
||||
*/
|
||||
final class IotFleetIndexQuery {
|
||||
|
||||
private static final Set<String> FIELDS = Set.of("thingName", "thingId", "thingTypeName", "thingGroupNames");
|
||||
private static final Set<String> FIELDS = Set.of("thingName", "thingId", "thingTypeName", "thingGroupNames",
|
||||
"connectivity.connected", "connectivity.clientId", "connectivity.disconnectReason");
|
||||
private static final String ATTRIBUTES = "attributes.";
|
||||
private static final Set<String> OPERATORS = Set.of("AND", "OR", "NOT", "-", ")");
|
||||
private static final Pattern COMPARISON = Pattern.compile("[<>]");
|
||||
@@ -235,11 +235,11 @@ final class IotFleetIndexQuery {
|
||||
}
|
||||
|
||||
/**
|
||||
* A registry field or attribute passes. One under connectivity, shadow or Device Defender first
|
||||
* needs that indexing on, with AWS's error: a classic shadow field needs REGISTRY_AND_SHADOW, a
|
||||
* named shadow field needs named shadow indexing and a shadow in its filter (otherwise an invalid
|
||||
* field name, as on AWS). Floci then refuses it, since it indexes none of them. Anything else is
|
||||
* the invalid field name AWS reports.
|
||||
* A field Floci indexes passes. One under connectivity, shadow or Device Defender first needs
|
||||
* that indexing on, with AWS's error: a classic shadow field needs REGISTRY_AND_SHADOW, a named
|
||||
* shadow field needs named shadow indexing and a shadow in its filter (otherwise an invalid field
|
||||
* name, as on AWS). Floci then refuses those it does not index. Anything else is the invalid
|
||||
* field name AWS reports.
|
||||
*/
|
||||
private void checkField(String field) {
|
||||
if (field.startsWith(ATTRIBUTES) && field.length() > ATTRIBUTES.length()) {
|
||||
|
||||
+1
-1
@@ -98,7 +98,7 @@ public class IotFleetIndexingController {
|
||||
@Path("/indices/search")
|
||||
public Response searchIndex(@Context HttpHeaders headers, String body) {
|
||||
IotService.Page<ObjectNode> page = fleetIndexingService.searchIndex(IotRequestBody.read(objectMapper, body),
|
||||
regionResolver.resolveRegion(headers));
|
||||
regionResolver.getAccountId(), regionResolver.resolveRegion(headers));
|
||||
ObjectNode response = objectMapper.createObjectNode();
|
||||
response.putArray("things").addAll(page.items());
|
||||
if (page.nextToken() != null) {
|
||||
|
||||
@@ -11,6 +11,7 @@ import io.github.hectorvent.floci.core.common.Base64Url;
|
||||
import io.github.hectorvent.floci.core.common.SmithyValidationErrors;
|
||||
import io.github.hectorvent.floci.core.storage.StorageBackend;
|
||||
import io.github.hectorvent.floci.core.storage.StorageFactory;
|
||||
import io.github.hectorvent.floci.services.iot.IotMqttBrokerService.Connectivity;
|
||||
import io.github.hectorvent.floci.services.iot.model.IotIndexingConfiguration;
|
||||
import io.github.hectorvent.floci.services.iot.model.IotIndexingConfiguration.Field;
|
||||
import io.github.hectorvent.floci.services.iot.model.IotIndexingConfiguration.GeoLocation;
|
||||
@@ -98,18 +99,22 @@ public class IotFleetIndexingService {
|
||||
|
||||
private final StorageBackend<String, IotIndexingConfiguration> store;
|
||||
private final IotService iotService;
|
||||
private final IotMqttBrokerService mqttBrokerService;
|
||||
/** Guards the read-modify-write of an update that changes only one of the two configurations. */
|
||||
private final Object lock = new Object();
|
||||
|
||||
@Inject
|
||||
public IotFleetIndexingService(StorageFactory storageFactory, IotService iotService) {
|
||||
public IotFleetIndexingService(StorageFactory storageFactory, IotService iotService,
|
||||
IotMqttBrokerService mqttBrokerService) {
|
||||
this(storageFactory.create("iot", "iot-indexing-configuration.json",
|
||||
new TypeReference<Map<String, IotIndexingConfiguration>>() {}), iotService);
|
||||
new TypeReference<Map<String, IotIndexingConfiguration>>() {}), iotService, mqttBrokerService);
|
||||
}
|
||||
|
||||
IotFleetIndexingService(StorageBackend<String, IotIndexingConfiguration> store, IotService iotService) {
|
||||
IotFleetIndexingService(StorageBackend<String, IotIndexingConfiguration> store, IotService iotService,
|
||||
IotMqttBrokerService mqttBrokerService) {
|
||||
this.store = store;
|
||||
this.iotService = iotService;
|
||||
this.mqttBrokerService = mqttBrokerService;
|
||||
}
|
||||
|
||||
public void updateIndexingConfiguration(JsonNode request, String region) {
|
||||
@@ -167,7 +172,7 @@ public class IotFleetIndexingService {
|
||||
* and version as sent) and the last thing returned, so a page continues after that thing
|
||||
* whatever was deleted before it. It also carries a checksum, so an edited token is invalid.
|
||||
*/
|
||||
public IotService.Page<ObjectNode> searchIndex(JsonNode request, String region) {
|
||||
public IotService.Page<ObjectNode> searchIndex(JsonNode request, String accountId, String region) {
|
||||
if (!request.isObject()) {
|
||||
throw serializationError("request body", JsonNodeType.OBJECT);
|
||||
}
|
||||
@@ -216,6 +221,7 @@ public class IotFleetIndexingService {
|
||||
Predicate<JsonNode> query = IotFleetIndexQuery.parse(queryString, indexing);
|
||||
String parameters = pageParameters(requestedIndexName, queryVersion, queryString);
|
||||
String after = pageAfter(nextToken, parameters);
|
||||
boolean connectivityIndexed = "STATUS".equals(indexing.thingConnectivityIndexingMode());
|
||||
Map<String, List<String>> thingGroupNames = thingGroupNames(region);
|
||||
List<ObjectNode> matches = new ArrayList<>();
|
||||
for (Thing thing : iotService.listThings(region)) {
|
||||
@@ -224,6 +230,12 @@ public class IotFleetIndexingService {
|
||||
continue;
|
||||
}
|
||||
ObjectNode document = document(thing, thingGroupNames.getOrDefault(thingName, List.of()));
|
||||
if (connectivityIndexed) {
|
||||
document.set("connectivity", mqttBrokerService.connectivity(accountId, region, thingName)
|
||||
.map(state -> connectivity(state, thingName))
|
||||
.orElseGet(() -> JsonNodeFactory.instance.objectNode()
|
||||
.put("clientId", thingName).put("connected", false).put("timestamp", 0)));
|
||||
}
|
||||
if (query.test(document)) {
|
||||
matches.add(document);
|
||||
if (matches.size() > pageSize) {
|
||||
@@ -306,6 +318,18 @@ public class IotFleetIndexingService {
|
||||
return document;
|
||||
}
|
||||
|
||||
private static ObjectNode connectivity(Connectivity state, String clientId) {
|
||||
ObjectNode connectivity = JsonNodeFactory.instance.objectNode()
|
||||
.put("connected", state.connected())
|
||||
.put("timestamp", state.timestamp());
|
||||
if (state.disconnectReason() != null) {
|
||||
connectivity.put("disconnectReason", state.disconnectReason());
|
||||
}
|
||||
return connectivity.put("keepAliveDuration", state.keepAliveDuration())
|
||||
.put("cleanSession", state.cleanSession())
|
||||
.put("clientId", clientId);
|
||||
}
|
||||
|
||||
/** The schema of the named index, null while it is disabled. */
|
||||
private static String schema(String indexName, IotIndexingConfiguration configuration) {
|
||||
return switch (indexName) {
|
||||
|
||||
@@ -123,8 +123,8 @@ public class IotMqttBrokerService implements Resettable {
|
||||
static final String CONNECTION_LOST = "CONNECTION_LOST";
|
||||
static final String MQTT_KEEP_ALIVE_TIMEOUT = "MQTT_KEEP_ALIVE_TIMEOUT";
|
||||
static final String PRESENCE_TOPIC_PREFIX = "$aws/events/presence/";
|
||||
private static final String DUPLICATE_CLIENTID = "DUPLICATE_CLIENTID";
|
||||
private static final String API_INITIATED_DISCONNECT = "API_INITIATED_DISCONNECT";
|
||||
static final String DUPLICATE_CLIENTID = "DUPLICATE_CLIENTID";
|
||||
static final String API_INITIATED_DISCONNECT = "API_INITIATED_DISCONNECT";
|
||||
private static final String CLIENT_ERROR = "CLIENT_ERROR";
|
||||
private static final long KEEP_ALIVE_SLACK_NANOS = TimeUnit.MILLISECONDS.toNanos(250);
|
||||
|
||||
@@ -145,6 +145,8 @@ public class IotMqttBrokerService implements Resettable {
|
||||
private final Object sessionLock = new Object();
|
||||
/** The last lifecycle event versionNumber per client id; neither a state reset nor a broker restart clears it. */
|
||||
private final Map<String, Long> presenceVersions = new ConcurrentHashMap<>();
|
||||
/** How a client id's last session in an account and region ended, for fleet indexing; a state reset clears it. */
|
||||
private final Map<HistoryKey, Connectivity> lastDisconnects = new ConcurrentHashMap<>();
|
||||
private final AtomicInteger pendingRuleEvaluations = new AtomicInteger();
|
||||
private final AtomicBoolean ruleEvaluationsThrottled = new AtomicBoolean();
|
||||
/**
|
||||
@@ -219,11 +221,14 @@ public class IotMqttBrokerService implements Resettable {
|
||||
}
|
||||
|
||||
/**
|
||||
* The broker keeps nothing in Floci storage; a reset only suspends rules, in
|
||||
* {@link #beforeReset()}.
|
||||
* The broker keeps nothing in Floci storage; a reset forgets how earlier sessions ended, and
|
||||
* suspends rules in {@link #beforeReset()}. Live sessions stay connected.
|
||||
*/
|
||||
@Override
|
||||
public void clear() {
|
||||
synchronized (sessionLock) {
|
||||
lastDisconnects.clear();
|
||||
}
|
||||
}
|
||||
|
||||
synchronized void startIfEnabled() {
|
||||
@@ -405,6 +410,25 @@ public class IotMqttBrokerService implements Resettable {
|
||||
return Optional.of(new ConnectionInfo(session.clientId(), session.sourceIp(), session.sourcePort()));
|
||||
}
|
||||
|
||||
/**
|
||||
* A client id's connection as fleet indexing reports it in an account and region: its live
|
||||
* session, else how its last one ended. Empty when it has not connected there since the last
|
||||
* reset. A plaintext session counts in the default account and region, as the broker's shadow
|
||||
* topics do; a TLS session in its certificate's. Read under the session lock, so a session
|
||||
* being ended is never reported connected after its disconnect is recorded; the lock is never
|
||||
* held across endpoint calls, so liveness is the session's own ended flag.
|
||||
*/
|
||||
Optional<Connectivity> connectivity(String accountId, String region, String clientId) {
|
||||
synchronized (sessionLock) {
|
||||
ClientSession session = sessionsByClient.get(clientId);
|
||||
if (session != null && !session.ended().get()
|
||||
&& accountId.equals(session.accountId()) && region.equals(session.region())) {
|
||||
return Optional.of(session.connected());
|
||||
}
|
||||
return Optional.ofNullable(lastDisconnects.get(new HistoryKey(accountId, region, clientId)));
|
||||
}
|
||||
}
|
||||
|
||||
List<String> listSubscriptions(String clientId) {
|
||||
return subscriptionsByClient.getOrDefault(clientId, Map.of()).keySet().stream()
|
||||
.sorted()
|
||||
@@ -425,10 +449,10 @@ public class IotMqttBrokerService implements Resettable {
|
||||
SocketAddress remoteAddress = endpoint.remoteAddress();
|
||||
String sourceIp = remoteAddress == null ? null : remoteAddress.host();
|
||||
int sourcePort = remoteAddress == null ? -1 : remoteAddress.port();
|
||||
String principal = null;
|
||||
IotService.RegisteredDevice device = null;
|
||||
if (verifyDevice) {
|
||||
principal = admittedDevice(endpoint, clientId, sourceIp);
|
||||
if (principal == null) {
|
||||
device = admittedDevice(endpoint, clientId, sourceIp);
|
||||
if (device == null) {
|
||||
endpoint.reject(endpoint.protocolVersion() == 5
|
||||
? MqttConnectReturnCode.CONNECTION_REFUSED_NOT_AUTHORIZED_5
|
||||
: MqttConnectReturnCode.CONNECTION_REFUSED_NOT_AUTHORIZED);
|
||||
@@ -447,7 +471,7 @@ public class IotMqttBrokerService implements Resettable {
|
||||
return;
|
||||
}
|
||||
}
|
||||
admit(endpoint, principal, sourceIp, sourcePort, connectNanos);
|
||||
admit(endpoint, device, sourceIp, sourcePort, connectNanos);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -489,15 +513,18 @@ public class IotMqttBrokerService implements Resettable {
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code principal} is the certificate id a TLS client was admitted with, null otherwise.
|
||||
* {@code device} is the registered device a TLS client was admitted as, null otherwise; its
|
||||
* certificate id is the session's principal, and its account and region the session's.
|
||||
* {@code clientIp} and {@code clientPort} are the address the client connected from: the
|
||||
* socket's, or for a WebSocket client the one the bridge recorded at the upgrade, as the
|
||||
* bridge's own socket is loopback. {@code connectNanos} is when the CONNECT arrived, which
|
||||
* the keep-alive runs from.
|
||||
*/
|
||||
private void admit(MqttEndpoint endpoint, String principal, String clientIp, int clientPort, long connectNanos) {
|
||||
private void admit(MqttEndpoint endpoint, IotService.RegisteredDevice device, String clientIp, int clientPort,
|
||||
long connectNanos) {
|
||||
String clientId = endpoint.clientIdentifier();
|
||||
boolean cleanSession = endpoint.isCleanSession();
|
||||
String principal = device == null ? null : device.certificate().getCertificateId();
|
||||
ClientSession session;
|
||||
ClientSession replaced = null;
|
||||
synchronized (sessionLock) {
|
||||
@@ -512,7 +539,11 @@ public class IotMqttBrokerService implements Resettable {
|
||||
principal,
|
||||
versionNumber,
|
||||
new AtomicBoolean(),
|
||||
new AtomicLong(connectNanos));
|
||||
new AtomicLong(connectNanos),
|
||||
device == null ? config.defaultAccountId() : device.accountId(),
|
||||
device == null ? config.defaultRegion() : device.region(),
|
||||
System.currentTimeMillis(),
|
||||
endpoint.keepAliveTimeSeconds());
|
||||
ClientSession previous = sessionsByClient.put(clientId, session);
|
||||
if (previous != null && previous.endpoint() != endpoint) {
|
||||
endSession(previous, DUPLICATE_CLIENTID);
|
||||
@@ -553,12 +584,12 @@ public class IotMqttBrokerService implements Resettable {
|
||||
}
|
||||
|
||||
/**
|
||||
* The certificate id of the device behind the connection when it may connect, otherwise null.
|
||||
* The registered device behind the connection when it may connect, otherwise null.
|
||||
* A failure while deciding refuses the client rather than leaving the CONNECT unanswered. A
|
||||
* refusal is the client's own doing and reaches it as the CONNACK, so it is logged at debug
|
||||
* only: the CONNECT is reachable by anyone.
|
||||
*/
|
||||
private String admittedDevice(MqttEndpoint endpoint, String clientId, String sourceIp) {
|
||||
private IotService.RegisteredDevice admittedDevice(MqttEndpoint endpoint, String clientId, String sourceIp) {
|
||||
try {
|
||||
Optional<IotService.RegisteredDevice> device = presentedDevice(endpoint);
|
||||
if (device.isEmpty()) {
|
||||
@@ -570,7 +601,7 @@ public class IotMqttBrokerService implements Resettable {
|
||||
LOG.debugv("IoT MQTT TLS client {0} refused: iot:Connect is not allowed for {1}", clientId, certificateId);
|
||||
return null;
|
||||
}
|
||||
return certificateId;
|
||||
return device.get();
|
||||
} catch (RuntimeException e) {
|
||||
LOG.warnv(e, "IoT MQTT TLS client {0} refused: device verification failed: {1}", clientId, e.getMessage());
|
||||
return null;
|
||||
@@ -784,14 +815,16 @@ public class IotMqttBrokerService implements Resettable {
|
||||
|
||||
/**
|
||||
* Ends the session once: the first reason reported wins, and only that one publishes the
|
||||
* disconnected event and gets true. The versionNumber counts up only while the session is still
|
||||
* the client id's current one, so a session replaced by a newer connection leaves it alone.
|
||||
* disconnected event, records how the session ended for fleet indexing, and gets true. The
|
||||
* versionNumber counts up only while the session is still the client id's current one, so a
|
||||
* session replaced by a newer connection leaves it alone.
|
||||
*/
|
||||
private boolean endSession(ClientSession session, String reason) {
|
||||
synchronized (sessionLock) {
|
||||
if (!session.ended().compareAndSet(false, true)) {
|
||||
return false;
|
||||
}
|
||||
lastDisconnects.put(session.historyKey(), session.disconnected(reason));
|
||||
if (sessionsByClient.remove(session.clientId(), session)) {
|
||||
presenceVersions.computeIfPresent(session.clientId(), (id, version) -> version + 1);
|
||||
}
|
||||
@@ -906,7 +939,26 @@ public class IotMqttBrokerService implements Resettable {
|
||||
String principalIdentifier,
|
||||
long versionNumber,
|
||||
AtomicBoolean ended,
|
||||
AtomicLong lastPacketNanos) {
|
||||
AtomicLong lastPacketNanos,
|
||||
String accountId,
|
||||
String region,
|
||||
long connectedAt,
|
||||
int keepAliveDuration) {
|
||||
|
||||
HistoryKey historyKey() {
|
||||
return new HistoryKey(accountId, region, clientId);
|
||||
}
|
||||
|
||||
Connectivity connected() {
|
||||
return new Connectivity(true, connectedAt, null, keepAliveDuration, cleanSession);
|
||||
}
|
||||
|
||||
Connectivity disconnected(String reason) {
|
||||
return new Connectivity(false, System.currentTimeMillis(), reason, keepAliveDuration, cleanSession);
|
||||
}
|
||||
}
|
||||
|
||||
private record HistoryKey(String accountId, String region, String clientId) {
|
||||
}
|
||||
|
||||
private record Subscription(String topicFilter, int qos) {
|
||||
@@ -914,4 +966,9 @@ public class IotMqttBrokerService implements Resettable {
|
||||
|
||||
record ConnectionInfo(String clientId, String address, int port) {
|
||||
}
|
||||
|
||||
/** Timestamps are epoch milliseconds: the connect while connected, the disconnect after. */
|
||||
record Connectivity(boolean connected, long timestamp, String disconnectReason, int keepAliveDuration,
|
||||
boolean cleanSession) {
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user