diff --git a/components/rtps/README.md b/components/rtps/README.md index b06624f706..4a387a3185 100644 --- a/components/rtps/README.md +++ b/components/rtps/README.md @@ -205,6 +205,22 @@ wire. The announced lease must comfortably exceed the announcement period a remote lease cap below a peer's announcement period drops that peer while it is alive. +A participant's GUID prefix on an ESP target is its MAC, the participant id, +the vendor id, the domain id and two incarnation bytes drawn when the Domain +is constructed (`rtps::Domain::guidIncarnation()`), so a board that reboots - +or an application that recreates its Domain - is a new participant to its +peers: what RTPS requires, since every writer of the restarted board numbers +its samples from 1 again and a peer still holding the old incarnation would +ignore them until its lease ran out. The previous incarnation is kept in RTC +memory (`.noinit` RAM on chips without it), which survives a software reset, +and is disposed, as that incarnation, on the first announce cycles, so such +peers forget it at once (after a power-on there is nothing to dispose; the +old incarnation then expires with its lease). A peer +that does reuse a prefix across a restart - this engine's boards never do, but +a stack that derives its prefix from stable hardware identifiers would - is +recognised by the sequence number of its announcements falling far below what +it had reached, and rediscovered on the spot. + ### Per-limit capacity overrides Every capacity cap in the profile headers can be raised (or lowered) diff --git a/components/rtps/include/rtps/config_esp32.hpp b/components/rtps/include/rtps/config_esp32.hpp index b063c7f11e..a1eeca37da 100644 --- a/components/rtps/include/rtps/config_esp32.hpp +++ b/components/rtps/include/rtps/config_esp32.hpp @@ -59,8 +59,15 @@ const VendorId_t VENDOR_ID = {13, 37}; // Fallback only: Domain::generateGuidPrefix() builds the prefix from the // Ethernet or Wi-Fi MAC (bytes 0-5) and uses this template only when neither // MAC can be read. Bytes 6-9 are always overwritten with the participant id, -// VENDOR_ID and DOMAIN_ID, so two boards that both fall back share bytes 0-5 -// and 10-11 and would collide on a domain. +// VENDOR_ID and DOMAIN_ID, so two boards that both fall back share bytes 0-9 +// and collide on a domain unless their incarnations differ (2^-16 odds of +// matching). Bytes 10-11 are the boot's incarnation +// (Domain::guidIncarnation(), a nonce drawn once per boot): a board that +// reboots is a NEW participant to its peers, which is what RTPS requires - a +// peer that still held the old incarnation would otherwise ignore the +// restarted writers (their sequence numbers start at 1 again) until the lease +// ran out. The previous boot's incarnation survives a software reset in RTC +// memory and is disposed before the first announcement (SPDPAgent). const GuidPrefix_t BASE_GUID_PREFIX{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 13}; // DDS domain id (the ROS_DOMAIN_ID equivalent; 0..232 with UDP). The port base diff --git a/components/rtps/include/rtps/discovery/ParticipantProxyData.hpp b/components/rtps/include/rtps/discovery/ParticipantProxyData.hpp index 50bd50969a..f98a2e111d 100644 --- a/components/rtps/include/rtps/discovery/ParticipantProxyData.hpp +++ b/components/rtps/include/rtps/discovery/ParticipantProxyData.hpp @@ -67,6 +67,11 @@ class ParticipantProxyData : public espp::BaseComponent { // When this proxy entered the remote-participant pool (eviction prefers the // oldest unused one and spares one still completing endpoint discovery). std::chrono::time_point m_discoveredTimestamp; + // The highest sequence number seen from this participant's SPDP writer. A + // later announcement numbered far below it (SPDPAgent::isRestart) means the + // peer restarted with the same GUID prefix - its writers all start again at + // 1 - and must be rediscovered, not refreshed. + SequenceNumber_t m_lastSpdpSn{0, 0}; void reset(); /// Parses the SPDP PL_CDR parameter list starting at `buffer`'s current diff --git a/components/rtps/include/rtps/discovery/SPDPAgent.hpp b/components/rtps/include/rtps/discovery/SPDPAgent.hpp index 5fc9929c3e..f1a916737d 100644 --- a/components/rtps/include/rtps/discovery/SPDPAgent.hpp +++ b/components/rtps/include/rtps/discovery/SPDPAgent.hpp @@ -69,6 +69,24 @@ class SPDPAgent : public espp::BaseComponent { /// scheduler at SPDP_RESEND_PERIOD_MS cadence instead of a dedicated /// broadcast thread. void announce(); + /// `announced` is the sequence number of the announcement just received from + /// a known participant whose highest so far is `last`. A number far below + /// the highest (at most half of it, once the peer has announced at least + /// three times) is not a reordered or duplicated datagram but a peer that + /// restarted with the same GUID prefix and numbers its new SPDP writer from + /// 1 again; such a peer is forgotten and rediscovered (its SEDP and user + /// writers restarted too, and the stateful readers' proxies would keep + /// waiting for the old numbers). Edges: a peer seen fewer than three times + /// is never judged (a reordered second announcement must not tear down a + /// participant just discovered); a restarted peer whose first + /// announcements were lost is caught as long as its number is still at most + /// half of what was seen before, else its lease decides; number 0 never + /// qualifies (not a valid RTPS sequence number). This engine's own boards + /// never reuse a prefix (Domain::guidIncarnation), so this guards against + /// stacks that do. Security: a spoofed low-numbered announcement can tear + /// down and re-add a healthy peer - no more than a spoofed dispose, which + /// the protocol has always allowed from any multicast sender. + static bool isRestart(const SequenceNumber_t &announced, const SequenceNumber_t &last); std::recursive_mutex m_mutex; private: @@ -94,6 +112,9 @@ class SPDPAgent : public espp::BaseComponent { /// else GUIDPREFIX_UNKNOWN. For a dispose that carries the key in its /// payload rather than inline. static GuidPrefix_t participantPrefixInPayload(const uint8_t *data, DataSize_t size); + /// Parse the announcement in m_inputBuffer into m_proxyDataBuffer. The + /// parser stops at the GUID of a participant that is already known. + bool parseAnnouncement(); /// Participants that disposed themselves lately: the prefix, the dispose's /// sequence number and when it came. An announcement of such a prefix with /// a lower number is a delayed or duplicated copy from before the dispose @@ -112,7 +133,18 @@ class SPDPAgent : public espp::BaseComponent { size_t m_nextDisposed = 0; void rememberDispose(const GuidPrefix_t &prefix, const SequenceNumber_t &sn); bool isFromBeforeDispose(const GuidPrefix_t &prefix, const SequenceNumber_t &sn) const; - void processProxyData(); + /// Send the dispose of the participant we were in the previous boot, AS that + /// participant: an RTPS message whose header prefix and SPDP writer are the + /// old incarnation's, with its participant GUID as key hash + payload and + /// a sequence number above anything it could have sent (every stack's SPDP + /// reader takes a participant's own dispose; one from another writer + /// naming it is refused by Cyclone DDS, Fast DDS and this engine alike). + /// Sent on the first PREVIOUS_INCARNATION_DISPOSES announce cycles - best + /// effort, multicast, a lost datagram costs a peer one lease. + void sendPreviousIncarnationDispose(); + static constexpr uint8_t PREVIOUS_INCARNATION_DISPOSES = 3; + uint8_t m_previousIncarnationDisposesLeft = 0; + void processProxyData(const SequenceNumber_t &announcementSn); bool addProxiesForBuiltInEndpoints(); void addInlineQos(CdrWriter &writer); diff --git a/components/rtps/include/rtps/entities/Domain.hpp b/components/rtps/include/rtps/entities/Domain.hpp index 44667d86d0..0a85d3167c 100644 --- a/components/rtps/include/rtps/entities/Domain.hpp +++ b/components/rtps/include/rtps/entities/Domain.hpp @@ -38,6 +38,7 @@ Author: i11 - Embedded Software, RWTH Aachen University #include "task.hpp" #include #include +#include #include namespace rtps { @@ -98,6 +99,26 @@ class Domain : public espp::BaseComponent { void stop(); Participant *createParticipant(); + + /// Bytes 10-11 of every GUID prefix this Domain generates. On ESP targets + /// a nonce drawn when the Domain is constructed, so a board that reboots - + /// or an application that recreates its Domain - comes back as a NEW + /// participant to every peer (RTPS requires a GUID never to be reused; a + /// peer that still holds the old incarnation would otherwise ignore the + /// restarted writers, whose sequence numbers start at 1 again, until the + /// lease ran out). Host builds return 0: their prefixes are random per + /// process already (or the configured template, for tests). The static + /// form reports the most recently constructed Domain's value. + uint16_t guidIncarnation() const { return m_incarnation; } + static uint16_t currentGuidIncarnation(); + /// The incarnation before this Domain's, when known: ESP targets keep the + /// last one in RTC memory across a software reset (not a power cycle), so + /// it is the previous boot's after a reboot and the previous Domain's after + /// a recreation. The SPDP agent disposes that incarnation's participant on + /// its first announce cycles, so peers drop it at once. nullopt on host + /// builds and after a power-on. + std::optional previousGuidIncarnation() const { return m_previousIncarnation; } + static std::optional currentPreviousGuidIncarnation(); Writer *createWriter(Participant &part, const char *topicName, const char *typeName, bool reliable, bool enforceUnicast = false, const EndpointOptions &options = {}); @@ -235,6 +256,9 @@ class Domain : public espp::BaseComponent { bool m_initComplete = false; bool m_transportSetupOk = true; + uint16_t m_incarnation = 0; + std::optional m_previousIncarnation{}; + void drawGuidIncarnation(); std::recursive_mutex m_mutex; void receiveCallback(const PacketInfo &packet); diff --git a/components/rtps/include/rtps/entities/Participant.hpp b/components/rtps/include/rtps/entities/Participant.hpp index 7b2c8f2db1..45bb7476d8 100644 --- a/components/rtps/include/rtps/entities/Participant.hpp +++ b/components/rtps/include/rtps/entities/Participant.hpp @@ -50,6 +50,13 @@ class Participant : public espp::BaseComponent { public: GuidPrefix_t m_guidPrefix; ParticipantId_t m_participantId; + /// The GUID prefix this participant had in the previous boot, when the + /// Domain could tell (ESP targets keep the prefix's incarnation bytes + /// across a software reset: Domain::generateGuidPrefix). The SPDP agent + /// disposes it before the first announcement, so peers forget the old + /// incarnation at once instead of when its lease runs out. + bool m_hasPreviousIncarnation = false; + GuidPrefix_t m_previousIncarnationPrefix{}; Ip4AddressBytes m_localIpAddress{{0, 0, 0, 0}}; /// Prefix length (CIDR bits) of the local network, used to tell which of a /// peer's announced unicast locators is reachable (see @@ -137,6 +144,18 @@ class Participant : public espp::BaseComponent { const ParticipantProxyData *findRemoteParticipant(const GuidPrefix_t &prefix); void refreshRemoteParticipantLiveliness(const GuidPrefix_t &prefix); + /// What an SPDP announcement from `prefix`, numbered `sn`, means for the + /// remote participant we may know by that prefix - decided and recorded in + /// one step under the participant mutex (the lease sweep removes entries + /// concurrently). + enum class AnnouncementVerdict : uint8_t { + Unknown, ///< no such participant: discover it + Known, ///< a known participant; its lease and highest SPDP number were refreshed + Restart, ///< a known participant restarted with this prefix (SPDPAgent::isRestart): + ///< forget it and discover it afresh; nothing was refreshed + }; + AnnouncementVerdict noteRemoteParticipantAnnouncement(const GuidPrefix_t &prefix, + const SequenceNumber_t &sn); uint32_t getRemoteParticipantCount(); MessageReceiver *getMessageReceiver(); bool checkAndResetHeartbeats(); diff --git a/components/rtps/include/rtps/entities/StatelessWriter.hpp b/components/rtps/include/rtps/entities/StatelessWriter.hpp index 2ad8f58c1a..f56dd765c3 100644 --- a/components/rtps/include/rtps/entities/StatelessWriter.hpp +++ b/components/rtps/include/rtps/entities/StatelessWriter.hpp @@ -65,6 +65,13 @@ class StatelessWriter : public Writer { EsppTransport *m_transport; +public: + /// The transport this writer sends on and the source port it sends from + /// (SPDPAgent sends the previous incarnation's dispose through them). + EsppTransport *getTransport() const { return m_transport; } + Ip4Port_t getSourcePort() const { return m_srcPort; } + +private: SimpleHistoryCache m_history; }; diff --git a/components/rtps/interop/README.md b/components/rtps/interop/README.md index 4ddd52cedf..6308f68266 100644 --- a/components/rtps/interop/README.md +++ b/components/rtps/interop/README.md @@ -27,6 +27,7 @@ touched. | golden | wire-format bytes unchanged (see `pc/tests/rtps_golden.cpp`) | | locator_subnet | of the unicast locators a peer on several networks announces (SEDP and SPDP), the one on our subnet is kept (see `pc/tests/rtps_locator_subnet.cpp`) | | sedp_inline_qos_dispose | a peer's dispose of an endpoint (SEDP) or of its participant (SPDP) - a DATA whose inline QoS carries `PID_STATUS_INFO` + `PID_KEY_HASH`, as Fast DDS, Cyclone DDS and espp write it, in each of the three forms - unmatches the endpoint / forgets the participant at once instead of at lease expiry (see `pc/tests/rtps_sedp_inline_qos_dispose.cpp`) | +| participant_restart | a peer that restarts with the GUID prefix its peers still hold (every writer numbers from 1 again) is rediscovered at once: an announcement numbered far below the peer's highest (`SPDPAgent::isRestart`) forgets and rediscovers it (a single reordered or duplicated announcement does not); a rebooted board of this engine instead comes back with new incarnation bytes and first disposes its previous incarnation as that incarnation (old prefix, its SPDP writer, a number above anything it sent), which every stack honours as the participant's own dispose - the old one goes at once, a stale announcement of it is ignored, a dispose naming a participant from any other prefix is still refused (see `pc/tests/rtps_participant_restart.cpp`) | | sedp_history_ring, sedp_history_overflow | the SEDP writers never overwrite a live endpoint announcement when their history is full: a sent dispose is given up first, else the announcement is refused and the endpoint creation fails loudly (the ring policy on a static ring, `pc/tests/rtps_sedp_history_ring.cpp`, a unit that links no engine object); a refused creation gives its pooled endpoint back, and an endpoint whose announcement is gone can still be deleted with its slot reused (`pc/tests/rtps_sedp_history_overflow.cpp`) | | facade_matched_counts | `RtpsParticipant::matched_writers()` / `matched_readers()` over a loopback: one remote writer counts once across two local readers on the topic, and removing the writer (which announces the SEDP dispose) brings the count to zero within a couple of seconds, not at lease expiry (`pc/tests/rtps_facade_matched_counts.cpp`) | | gap_before_data | a reliable reader applies a GAP only for sequence numbers the writer has announced (HEARTBEAT lastSN or a DATA): Fast DDS sends its SEDP readers a GAP for the next number after an endpoint deletion and then writes that number for the next announcement, which used to leave a publisher-churning peer unmatched after its first deletion (`pc/tests/rtps_gap_before_data.cpp`; the churn case is the live check) | @@ -84,6 +85,7 @@ cd .. && ./run_qemu.sh | device_boot, device_ping | the engine comes up on lwIP over the emulated OpenCores MAC | | device_pub->ros2_echo, ros2_pub->device_sub (+ best-effort pair) | delivery both ways, FastDDS and CycloneDDS | | ros2_pub->device_sub_liveliness | samples still arriving 24-34 s in, past the remote lease | +| restart_fastdds_rediscovered_by_ros2_sub, restart_cyclone_rediscovered_by_ros2_sub, restart_device_sub_receives, restart_fastdds_old_incarnation_dropped, restart_cyclone_old_incarnation_dropped, restart_previous_incarnation_remembered | the device restarts its participant on one "RESTART" trigger (it recreates its Domain - what a board's reboot looks like to its peers; a software reset of QEMU's emulated chip panics inside ESP-IDF's startup, so the chip is not rebooted). The restart is done ONCE for the whole run, with BOTH a FastDDS peer and a CycloneDDS peer watching that single restart, so each stack is proven to honour the dispose without a second recreate: the espp participant is recreated in-process to "reboot", which fragments internal RAM, so the first recreate is reliable and a second is not yet (a teardown/fragmentation follow-up); the espp host engine's own side is covered by `pc/tests/rtps_participant_restart.cpp`. Both a ROS 2 subscriber per stack and a ROS 2 publisher stay up. The device announces a 30 s lease for itself in `sdkconfig.ci.defaults`, so the old incarnation cannot expire during the restart: each stack's subscriber must receive the restarted publisher's first samples ("qemu 0".."qemu 9") and the rebooted device the ROS 2 publisher's samples within seconds. The GUID prefix carries a per-Domain incarnation (bytes 10-11, `Domain::guidIncarnation`); the previous one is kept in RTC memory (`RTPSTEST incarnation cur= prev=`, `restart_previous_incarnation_remembered`) and disposed as that participant on the first announce cycles, so each RMW daemon's count of publishers on the device's topic drops back to one within seconds instead of after the 30 s lease (`restart_fastdds_old_incarnation_dropped`, `restart_cyclone_old_incarnation_dropped`) | | many_participants_late_joiner | twelve unrelated participants first, the needed one last, against the pool raised to 24 by `CONFIG_RTPS_LIMIT_SPDP_MAX_NUMBER_FOUND_PARTICIPANTS` | | ros2_pub->device_sub_frag_30k | 30 KB samples reassembled from DATA_FRAG over lwIP | | participant_pool_overflow_recovers | 28 participants against a pool of 24 (and proxy pools of 20), then all leave: discovery keeps going, every one is forgotten after the capped lease, the next publisher is received | diff --git a/components/rtps/interop/qemu/main/rtps_qemu.cpp b/components/rtps/interop/qemu/main/rtps_qemu.cpp index 75e3c0ddb3..d3e712d11c 100644 --- a/components/rtps/interop/qemu/main/rtps_qemu.cpp +++ b/components/rtps/interop/qemu/main/rtps_qemu.cpp @@ -7,39 +7,16 @@ // host side and asserts on the "RTPSTEST ..." lines this firmware logs: // // RTPSTEST ready ip= participant started -// RTPSTEST pub_matched/sub_matched a writer / reader gained a remote peer -// RTPSTEST tx reliable publisher sent "qemu " -// RTPSTEST rx reliable subscriber received -// RTPSTEST be_rx best-effort subscriber received -// RTPSTEST big_rx len= fragmented-sample subscriber received n bytes -// RTPSTEST srv += service request served -// RTPSTEST status up= tx= rx= be_rx= big_rx= heap= min_heap= -// int= int_min= int_largest= psram= -// stack_min= stack_min_task= -// stack_min_worker= -// stack_min: the smallest stack high-water mark (bytes never used) over the -// engine's tasks (rtps_* and the action servers' exec_* workers) since boot, -// and the task; stack_min_worker: the same over the receive workers alone -// (rtps_worker_*: they run every reader and matched callback on top of the -// engine's deepest path, and rtps_worker_0 overflowed once on the eviction -// path with a few hundred bytes of margin). The harness fails -// device_stack_margin below 1024 bytes. -// every 2 s, for the soak and memory checks -// RTPSTEST mem sizeof domain= participant= stateful_writer= stateless_writer= -// stateful_reader= stateless_reader= facade= -// the engine's compile-time-sized objects (bytes) -// RTPSTEST mem heap internal= internal_min= internal_largest= psram= psram_largest= -// at boot, started, endpoints: the memory suite's deltas -// -// Topics (ROS 2 names: "rt/" prefix stripped, std_msgs/msg/String): -// rt/qemu_tx reliable, device publishes "qemu " every 200 ms -// rt/qemu_rx reliable, device subscribes -// rt/qemu_be_tx best-effort, device publishes "qemu_be " every 200 ms -// rt/qemu_be_rx best-effort, device subscribes -// rt/qemu_big reliable, device subscribes (fragmented samples) -// /qemu_add_two_ints example_interfaces/srv/AddTwoInts service the device serves -// /qemu_fibonacci example_interfaces/action/Fibonacci action the device serves -// (one execute worker: the memory suite reads its cost) +// RTPSTEST incarnation cur= prev= the GUID prefix incarnation of +// this boot and, after a software reset, of the +// previous one (which the engine disposes first) +// RTPSTEST restart the restart case called /qemu_add_two_ints with a +// magic request: the firmware tears its participant +// down and creates a new one (a new GUID incarnation, +// which first disposes the previous one). Not +// esp_restart: QEMU's emulated chip panics in +// ESP-IDF startup after a software reset. Ignored in +// the first 5 s of a participant. #include #include @@ -88,6 +65,10 @@ void log_mem_heap(espp::Logger &logger, const char *stage) { heap_caps_get_free_size(MALLOC_CAP_SPIRAM), heap_caps_get_largest_free_block(MALLOC_CAP_SPIRAM)); } +// The restart case calls /qemu_add_two_ints with this magic request to ask the +// device to recreate its participant (see the service handler in run_participant). +constexpr int64_t kRestartMagicA = 424242; +constexpr int64_t kRestartMagicB = 0; } // namespace using namespace std::chrono_literals; @@ -123,6 +104,12 @@ static std::string ip4_to_string(esp_ip4_addr_t ip) { return buf; } +// One participant lifetime: endpoints, timers, the status loop. Returns when a +// RESTART sample asks for a new participant (the restart case); everything it +// owns is destroyed on the way out, and app_main builds the next one. +static void run_participant(espp::Logger &logger, const std::string &interface_address, + const std::string &interface_netmask); + extern "C" void app_main(void) { espp::Logger logger({.tag = "rtps_qemu", .level = espp::Logger::Verbosity::INFO}); logger.info("Starting the RTPS QEMU interop firmware"); @@ -166,6 +153,16 @@ extern "C" void app_main(void) { esp_netif_get_ip_info(esp_netif_get_handle_from_ifkey("ETH_DEF"), &ip_info); const std::string interface_netmask = ip4_to_string(ip_info.netmask); + while (true) { + run_participant(logger, interface_address, interface_netmask); + logger.info("RTPSTEST participant torn down, starting a new one"); + } +} + +static void run_participant(espp::Logger &logger, const std::string &interface_address, + const std::string &interface_netmask) { + const auto boot_time = std::chrono::steady_clock::now(); + std::atomic restart_requested{false}; // Counters for the status line (the callbacks run on the engine's threads) std::atomic tx_count{0}; std::atomic rx_count{0}; @@ -259,6 +256,25 @@ extern "C" void app_main(void) { .handler = [&](const AddReq &r) { logger.info("RTPSTEST srv {}+{}={}", r.a, r.b, r.a + r.b); + // The restart case triggers through this reliable, + // already-matched request/reply channel (a topic + // sample to a freshly-matched reliable reader is + // not reliably delivered on every RMW). The magic + // request restarts the participant AFTER the reply + // goes out (the status loop tears down ~2 s later); + // ignored in the participant's first 5 s so an + // in-flight retry does not restart the new one. + if (r.a == kRestartMagicA && r.b == kRestartMagicB) { + const auto up_s = std::chrono::duration_cast( + std::chrono::steady_clock::now() - boot_time) + .count(); + if (up_s < 5) { + logger.info("RTPSTEST restart ignored (participant {} s old)", + up_s); + } else if (!restart_requested.exchange(true)) { + logger.info("RTPSTEST restart"); + } + } return AddResp{r.a + r.b}; }, }); @@ -326,6 +342,16 @@ extern "C" void app_main(void) { }); logger.info("RTPSTEST ready ip={}", interface_address); + { + // The prefix incarnation (bytes 10-11 of every GUID prefix this boot) and + // the previous one (the previous boot's, kept across a software reset, or + // the previous participant's after a RESTART): the engine disposes that + // incarnation on its first announce cycles, so peers that still held it + // forget it at once. + const auto prev = rtps::Domain::currentPreviousGuidIncarnation(); + logger.info("RTPSTEST incarnation cur={:04x} prev={}", rtps::Domain::currentGuidIncarnation(), + prev ? fmt::format("{:04x}", *prev) : std::string{"none"}); + } // The engine's tasks' stack margin: the smallest high-water mark (bytes of // stack never touched since the task started) over the rtps_* tasks (receive @@ -358,7 +384,7 @@ extern "C" void app_main(void) { // Status line every 2 s: the soak and leak checks read heap and min_heap const auto t0 = std::chrono::steady_clock::now(); - while (true) { + while (!restart_requested) { std::this_thread::sleep_for(2s); const auto up = std::chrono::duration_cast(std::chrono::steady_clock::now() - t0) diff --git a/components/rtps/interop/qemu/sdkconfig.ci.defaults b/components/rtps/interop/qemu/sdkconfig.ci.defaults index 7b96fd2214..0415ef91a7 100644 --- a/components/rtps/interop/qemu/sdkconfig.ci.defaults +++ b/components/rtps/interop/qemu/sdkconfig.ci.defaults @@ -19,6 +19,13 @@ CONFIG_RTPS_LIMIT_SPDP_MAX_NUMBER_FOUND_PARTICIPANTS=24 CONFIG_RTPS_LIMIT_NUM_WRITER_PROXIES_PER_READER=20 CONFIG_RTPS_LIMIT_NUM_READER_PROXIES_PER_WRITER=20 +# The device announces a 30 s lease for itself (the embedded profile's 5 s +# would expire during the restart case's reboot and hide what it tests: that +# a peer still holding the device's previous incarnation drops it on the +# dispose the restarted device sends, and discovers the new one, well before +# the old lease runs out). +CONFIG_RTPS_SPDP_DEFAULT_REMOTE_LEASE_DURATION_S=30 + # Every ros2 CLI invocation the harness makes is a participant that announces # a 20 s lease (FastDDS) and then exits; left to the announced lease, the dead # ones pile up in the pool across cases. Cap what the device honours (the diff --git a/components/rtps/interop/run_qemu_interop.sh b/components/rtps/interop/run_qemu_interop.sh index b0001c6ba2..0c7ee3b81f 100755 --- a/components/rtps/interop/run_qemu_interop.sh +++ b/components/rtps/interop/run_qemu_interop.sh @@ -181,6 +181,127 @@ source "/opt/ros/${ROS_DISTRO:-jazzy}/setup.bash" export ROS_DOMAIN_ID=0 # matches the engine's Config::DOMAIN_ID run_matrix() { +# The device restarts its participant (triggered through its /qemu_add_two_ints +# service with a magic request, see rtps_qemu.cpp; a software reset of the +# emulated chip trips a QEMU startup bug, so the firmware recreates its Domain +# instead, which is what a board's reboot does to its peers) while a ROS 2 +# subscriber and a ROS 2 publisher stay up. Called once per boot (FastDDS); a +# real DDS stack honouring the standard participant dispose the device sends is +# what this proves, and the host test covers the receive side for every peer. Its GUID prefix is MAC-based, so before the fix it +# came back as the participant the peers still held, with every writer +# numbered from 1 again: the peers' readers rejected those numbers and nothing +# moved until the old lease (30 s in sdkconfig.ci.defaults, so a restart cannot +# hide behind it) ran out. Now the prefix carries a per-Domain incarnation +# (bytes 10-11), so the restarted device is a new participant, and it disposes +# the previous incarnation - as that incarnation - on its first announce +# cycles, so the peers drop the old one at once instead of holding it for the +# lease. +# This runs ONCE, with BOTH a FastDDS and a CycloneDDS peer watching the single +# restart, so each stack is proven to honour the dispose without a second device +# reboot. Recreating the espp participant in-process is how the device "reboots" +# here (a chip reset trips a QEMU startup bug); that recreate frees and +# reallocates the engine's FreeRTOS task stacks in internal RAM, which fragments +# it - the FIRST recreate is reliable, a SECOND one eventually fails a stack +# allocation and the device aborts (a teardown/fragmentation follow-up). So the +# restart is done exactly once and both RMW stacks observe it together. +# Results: restart__rediscovered_by_ros2_sub (that stack's subscriber +# receives the restarted publisher's first samples, "qemu 0".."qemu 9", well +# inside the old 30 s lease - daemon-independent proof the new incarnation is +# accepted at once), restart__old_incarnation_dropped (that stack's ROS 2 +# daemon, up throughout, counts ONE publisher on the device's topic again +# within ~15 s - without the dispose it would hold two for the full lease), +# restart_device_sub_receives (the ROS 2 publisher's samples reach the rebooted +# device), restart_previous_incarnation_remembered (the new Domain found the +# previous incarnation in the RTC record). +device_restart_case() { # (args unused; runs once, watching both stacks) + local m rc=0 n=0 i t0 + # CycloneDDS peers get the same discovery config the cyclone pass uses, and + # its daemon is warmed so its topic-info view of /qemu_tx is populated (the + # FastDDS daemon is already warm from this pass). Both echoes run across the + # restart; the cyclone echo discovers the device directly, independent of its + # daemon, so the rediscovery proof does not depend on the daemon at all. + local cyc='60' + RMW_IMPLEMENTATION=rmw_cyclonedds_cpp CYCLONEDDS_URI="$cyc" ros2 daemon start > /dev/null 2>&1 + timeout 150 ros2 topic echo /qemu_tx std_msgs/msg/String > "/tmp/fastdds_restart_echo.log" 2>&1 & + local echo_fd=$! + RMW_IMPLEMENTATION=rmw_cyclonedds_cpp CYCLONEDDS_URI="$cyc" \ + timeout 150 ros2 topic echo /qemu_tx std_msgs/msg/String > "/tmp/cyclone_restart_echo.log" 2>&1 & + local echo_cy=$! + timeout 150 ros2 topic pub -r 5 /qemu_rx std_msgs/msg/String "data: 'across restart'" > /dev/null 2>&1 & + local pub=$! + sleep 15 # both stacks matched and flowing, and both daemons know the device + local fd_pre cy_pre + fd_pre=$(timeout 10 ros2 topic info -v /qemu_tx 2>/dev/null | grep -c 'Endpoint type: PUBLISHER') + cy_pre=$(RMW_IMPLEMENTATION=rmw_cyclonedds_cpp CYCLONEDDS_URI="$cyc" \ + timeout 10 ros2 topic info -v /qemu_tx 2>/dev/null | grep -c 'Endpoint type: PUBLISHER') + echo " before the restart: FastDDS daemon sees ${fd_pre:-?} publisher(s), CycloneDDS daemon sees ${cy_pre:-?}" + m=$(mark) + # Trigger the restart through the already-matched service (a topic sample to + # a freshly-matched reliable reader is not reliably delivered on every RMW); + # the magic request restarts the device after it replies (rtps_qemu.cpp). + timeout 20 ros2 service call /qemu_add_two_ints example_interfaces/srv/AddTwoInts \ + "{a: 424242, b: 0}" > /dev/null 2>&1 + if ! wait_for_marker_since "$m" "RTPSTEST restart" 20; then + echo " the device did not take the restart"; rc=1 + fi + local boot; boot=$(mark) + if [ $rc -eq 0 ] && ! wait_for_marker_since "$boot" "RTPSTEST ready" 60; then + echo " the device's new participant did not come up"; rc=1 + fi + local n_fd=0 n_cy=0 pubs_fd=2 pubs_cy=2 + if [ $rc -eq 0 ]; then + # the restarted publisher counts from 0 again: its first samples at each + # subscriber are the proof it was rediscovered (the old lease is 30 s) + t0=$(date +%s) + for i in $(seq 1 30); do + n_fd=$(grep -c -E '^data: qemu [0-9]$' "/tmp/fastdds_restart_echo.log") + n_cy=$(grep -c -E '^data: qemu [0-9]$' "/tmp/cyclone_restart_echo.log") + [ "$n_fd" -ge 3 ] && [ "$n_cy" -ge 3 ] && break + sleep 1 + done + echo " $(( $(date +%s) - t0 )) s after the restart, first samples reached: FastDDS sub $n_fd, CycloneDDS sub $n_cy" + # The reverse direction re-matches a beat later than the device's own + # publisher (whose samples above arrive at once), so poll for it rather than + # sampling once: the across-restart publisher stays up and keeps sending at + # 5 Hz, so the new incarnation's reader fills in within seconds of re-match. + for i in $(seq 1 25); do + n=$(count_since "$boot" "RTPSTEST rx across restart") + [ "$n" -ge 5 ] && break + sleep 1 + done + echo " rebooted device received $n from the ROS 2 publisher $(( $(date +%s) - t0 )) s after the restart" + since "$boot" | grep -o "RTPSTEST incarnation.*" | head -1 | sed 's/^/ /' + since "$boot" | grep -q "RTPSTEST incarnation cur=[0-9a-f]* prev=[0-9a-f]" + result "restart_previous_incarnation_remembered" $? + # each daemon's view of /qemu_tx: two publishers while it still holds the old + # incarnation, one once the dispose took it. Kept well under the 30 s lease + # (short query timeouts, <=12 rounds) so a lingering old one still reads two. + for i in $(seq 1 12); do + pubs_fd=$(timeout 6 ros2 topic info -v /qemu_tx 2>/dev/null | grep -c 'Endpoint type: PUBLISHER') + pubs_cy=$(RMW_IMPLEMENTATION=rmw_cyclonedds_cpp CYCLONEDDS_URI="$cyc" \ + timeout 6 ros2 topic info -v /qemu_tx 2>/dev/null | grep -c 'Endpoint type: PUBLISHER') + [ "${pubs_fd:-2}" -le 1 ] && [ "${pubs_cy:-2}" -le 1 ] && break + sleep 1 + done + echo " $(( $(date +%s) - t0 )) s after the restart: FastDDS daemon counts ${pubs_fd:-?} publisher(s), CycloneDDS daemon ${pubs_cy:-?}" + fi + stop_pids $echo_fd $echo_cy $pub + RMW_IMPLEMENTATION=rmw_cyclonedds_cpp CYCLONEDDS_URI="$cyc" ros2 daemon stop > /dev/null 2>&1 + [ $rc -eq 0 ] && [ "$n_fd" -ge 3 ]; result "restart_fastdds_rediscovered_by_ros2_sub" $? + [ $rc -eq 0 ] && [ "$n_cy" -ge 3 ]; result "restart_cyclone_rediscovered_by_ros2_sub" $? + [ $rc -eq 0 ] && [ "$n" -ge 5 ]; result "restart_device_sub_receives" $? + # the dispose proof needs the daemon to have had a baseline (it saw the live + # publisher before the restart); require that too so a daemon that never + # discovered cannot read as a trivial pass. + [ $rc -eq 0 ] && [ "${fd_pre:-0}" -ge 1 ] && [ "${pubs_fd:-2}" -le 1 ]; result "restart_fastdds_old_incarnation_dropped" $? + [ $rc -eq 0 ] && [ "${cy_pre:-0}" -ge 1 ] && [ "${pubs_cy:-2}" -le 1 ]; result "restart_cyclone_old_incarnation_dropped" $? +} +wait_for_marker_since() { # mark marker timeout_s + local i + for i in $(seq 1 "$3"); do [ "$(count_since "$1" "$2")" -ge 1 ] && return 0; sleep 1; done + return 1 +} + # --- the ROS 2 cases, run once per rmw ----------------------------------------------- ros2_cases() { # prefix log-tag local p="$1" t="$2" m @@ -231,6 +352,20 @@ ros2_cases() { # prefix log-tag tail -2 "/tmp/${t}_srv.log"; result "${p}ros2_client->device_service" $rc settle + # Restart the device's participant ONCE for the whole run, on the FastDDS + # pass, with BOTH a FastDDS and a CycloneDDS peer watching that single restart + # (device_restart_case), so each stack is proven to honour the dispose without + # a second in-process recreate - which is not yet reliable, because recreating + # the espp participant fragments internal RAM and a later stack allocation + # eventually fails (a teardown/fragmentation follow-up). The espp-host engine's + # own handling of a restarted peer is covered by + # pc/tests/rtps_participant_restart.cpp. + if [ "$t" = fastdds ]; then + note "${p}the device restarts within its lease: both the FastDDS and the CycloneDDS peer drop the old incarnation and talk to the new one" + device_restart_case + settle + fi + note "${p}twelve other participants on the domain, then the publisher the device needs joins last" local crowd=() i for i in $(seq 1 12); do @@ -362,6 +497,11 @@ note "device publisher -> espp host subscriber (reliable, /qemu_tx)" rc=$?; tail -2 /tmp/hostsub.log; result "device_pub->espp_host_sub" $rc settle +# NOTE: the device restarts its participant once per boot, on the FastDDS pass +# above (recreating it repeatedly in one QEMU boot is not yet robust - see +# device_restart_case). The espp host engine's handling of a restarted peer is +# covered by pc/tests/rtps_participant_restart.cpp. + note "espp host publisher -> device subscriber, 30 KB samples as DATA_FRAG (1400-byte fragments, /qemu_big)" # The ROS 2 peers send a 30 KB sample as one IP-fragmented UDP datagram (lwIP # reassembly); the host engine with a fragment size sends RTPS DATA_FRAG diff --git a/components/rtps/src/discovery/ParticipantProxyData.cpp b/components/rtps/src/discovery/ParticipantProxyData.cpp index 746fd061b1..e5fe9c1add 100644 --- a/components/rtps/src/discovery/ParticipantProxyData.cpp +++ b/components/rtps/src/discovery/ParticipantProxyData.cpp @@ -50,6 +50,7 @@ void ParticipantProxyData::reset() { m_guid = Guid_t{GUIDPREFIX_UNKNOWN, ENTITYID_UNKNOWN}; m_manualLivelinessCount = Count_t{1}; m_expectsInlineQos = false; + m_lastSpdpSn = SequenceNumber_t{0, 0}; onAliveSignal(); onDiscovered(); for (int i = 0; i < Config::SPDP_MAX_NUM_LOCATORS; ++i) { diff --git a/components/rtps/src/discovery/SPDPAgent.cpp b/components/rtps/src/discovery/SPDPAgent.cpp index 82e9538704..dc32c848f6 100644 --- a/components/rtps/src/discovery/SPDPAgent.cpp +++ b/components/rtps/src/discovery/SPDPAgent.cpp @@ -25,17 +25,22 @@ Author: i11 - Embedded Software, RWTH Aachen University #include "rtps/discovery/SPDPAgent.hpp" +#include "rtps/communication/EsppTransport.hpp" #include "rtps/discovery/ParticipantProxyData.hpp" #include "rtps/entities/Participant.hpp" #include "rtps/entities/Reader.hpp" +#include "rtps/entities/StatelessWriter.hpp" #include "rtps/entities/Writer.hpp" +#include "rtps/messages/MessageFactory.hpp" #include "rtps/messages/MessageTypes.hpp" +#include "rtps/storages/PayloadBuffer.hpp" #include "rtps/utils/Log.hpp" #include "rtps/utils/udpUtils.hpp" #include #include #include +#include #include #include @@ -52,9 +57,94 @@ void SPDPAgent::init(Participant &participant, BuiltInEndpoints &endpoints) { m_buildInEndpoints.spdpReader->registerCallback(receiveCallback, this); addParticipantParameters(); + if (participant.m_hasPreviousIncarnation) { + m_previousIncarnationDisposesLeft = PREVIOUS_INCARNATION_DISPOSES; + } initialized = true; } +void SPDPAgent::sendPreviousIncarnationDispose() { + if (mp_participant == nullptr || !mp_participant->m_hasPreviousIncarnation) { + return; + } + auto *writer = static_cast(m_buildInEndpoints.spdpWriter); + EsppTransport *transport = writer ? writer->getTransport() : nullptr; + if (transport == nullptr) { + return; + } + const GuidPrefix_t &old = mp_participant->m_previousIncarnationPrefix; + + // The change: inline QoS (the old participant's key hash, STATUS_INFO + // disposed|unregistered as Fast DDS writes it) and a PL_CDR payload naming + // the same GUID, for a peer that reads the key from the payload. + PayloadBuffer change; + { + std::array buffer{}; + CdrSink sink{asWritableBytes(buffer.data(), buffer.size())}; + CdrWriter cdr(sink); + cdr.write(ParameterId::PID_KEY_HASH); + cdr.write(16); + writeBytes(cdr, old.id.data(), sizeof(GuidPrefix_t::id)); + writeBytes(cdr, ENTITYID_BUILD_IN_PARTICIPANT.entityKey.data(), sizeof(EntityId_t::entityKey)); + cdr.write(static_cast(ENTITYID_BUILD_IN_PARTICIPANT.entityKind)); + cdr.write(ParameterId::PID_STATUS_INFO); + cdr.write(4); + cdr.write(0); + cdr.write(0); + cdr.write(0); + cdr.write(3); + endCurrentList(cdr); + writeBytes(cdr, rtps::SMElement::SCHEME_PL_CDR_LE.data(), + rtps::SMElement::SCHEME_PL_CDR_LE.size()); + cdr.write(0); // options + cdr.write(ParameterId::PID_PARTICIPANT_GUID); + cdr.write(16); + writeBytes(cdr, old.id.data(), sizeof(GuidPrefix_t::id)); + writeBytes(cdr, ENTITYID_BUILD_IN_PARTICIPANT.entityKey.data(), sizeof(EntityId_t::entityKey)); + cdr.write(static_cast(ENTITYID_BUILD_IN_PARTICIPANT.entityKind)); + endCurrentList(cdr); + change.append(buffer.data(), static_cast(sink.size())); + } + + // The message, as the old incarnation: its prefix in the header, its SPDP + // writer as the source, a number its writer cannot have reached (a + // best-effort reader rejects a number at or below the last it took from + // that writer), to the SPDP multicast locator every peer listens on. + PayloadBuffer message; + MessageFactory::addHeader(message, old); + MessageFactory::addSubMessageTimeStamp(message); + const SequenceNumber_t sn{std::numeric_limits::max(), + std::numeric_limits::max()}; + MessageFactory::addSubMessageData(message, change, /*containsInlineQos=*/true, sn, + ENTITYID_SPDP_BUILTIN_PARTICIPANT_WRITER, + ENTITYID_SPDP_BUILTIN_PARTICIPANT_READER); + + const LocatorIPv4 multicast(getBuiltInMulticastLocator()); + PacketInfo info; + info.srcPort = writer->getSourcePort(); + info.destAddr = multicast.getIp4AddressBytes(); + info.destPort = static_cast(multicast.port); + info.payload = std::move(message.bytes); + transport->sendPacket(info); + logger_.info("Disposed the previous incarnation {:02x}{:02x} of this participant (now " + "{:02x}{:02x}), as that participant", + old.id[10], old.id[11], mp_participant->m_guidPrefix.id[10], + mp_participant->m_guidPrefix.id[11]); +} + +bool SPDPAgent::isRestart(const SequenceNumber_t &announced, const SequenceNumber_t &last) { + if (!(announced < last) || announced.high < 0 || last.high < 0) { + return false; + } + const uint64_t a = + (static_cast(static_cast(announced.high)) << 32) | announced.low; + const uint64_t l = (static_cast(static_cast(last.high)) << 32) | last.low; + if (a == 0 || l < 3) { + return false; // 0 is not a sequence number; too few announcements to judge + } + return a * 2 <= l; +} + void SPDPAgent::start() { m_running = true; } void SPDPAgent::stop() { m_running = false; } @@ -65,6 +155,12 @@ void SPDPAgent::announce() { // here when this was a dedicated thread body). const DataSize_t size = static_cast(m_outputSize); const uint8_t *payload = m_outputBuffer.data(); + if (m_previousIncarnationDisposesLeft > 0) { + // before our own announcement, so a peer that still holds the previous + // incarnation drops it first and discovers us as new + --m_previousIncarnationDisposesLeft; + sendPreviousIncarnationDispose(); + } // StatelessWriter drops already-sent history; enqueue a fresh SPDP sample // for each announce cycle. m_buildInEndpoints.spdpWriter->newChange(ChangeKind_t::ALIVE, payload, size); @@ -104,20 +200,9 @@ void SPDPAgent::handleSPDPPackage(const ReaderCacheChange &cacheChange) { SPDP_LOG("Announcement from before the participant's dispose, ignored"); return; } - // The payload's endianness is selected by the encapsulation identifier - // (first two bytes); endianness doesn't matter for reading those since - // they are single bytes. - const std::endian endianness = (m_inputBuffer[0] == SMElement::SCHEME_PL_CDR_LE[0] && - m_inputBuffer[1] == SMElement::SCHEME_PL_CDR_LE[1]) - ? std::endian::little - : std::endian::big; - CdrReader buffer(asBytes(m_inputBuffer.data(), m_inputBuffer.size()), endianness); - // Skip the encapsulation identifier and options (2 + 2 bytes) - skipBytes(buffer, 4); - volatile bool success = m_proxyDataBuffer.readFromBuffer(buffer, mp_participant); - if (success) { + if (parseAnnouncement()) { // TODO In case we store the history we can free the history mutex here - processProxyData(); + processProxyData(cacheChange.sn); } else { SPDP_LOG("ParticipantProxyData deserialization failed"); } @@ -128,7 +213,9 @@ void SPDPAgent::handleSPDPPackage(const ReaderCacheChange &cacheChange) { // peer that leaves the hash out carries the GUID in the payload. // Only the peer's own SPDP writer may dispose it, and only itself: a // DATA from another writer, or naming another participant, is malformed - // (or hostile) and must not remove anyone. + // (or hostile) and must not remove anyone. (A restarted board disposes + // its previous incarnation AS that incarnation - sendPreviousIncarnationDispose + // - so it passes this rule like any participant's own dispose.) if (!(cacheChange.writerGuid.entityId == ENTITYID_SPDP_BUILTIN_PARTICIPANT_WRITER)) { return; } @@ -161,6 +248,20 @@ void SPDPAgent::handleSPDPPackage(const ReaderCacheChange &cacheChange) { } } +bool SPDPAgent::parseAnnouncement() { + // The payload's endianness is selected by the encapsulation identifier + // (first two bytes); endianness doesn't matter for reading those since + // they are single bytes. + const std::endian endianness = (m_inputBuffer[0] == SMElement::SCHEME_PL_CDR_LE[0] && + m_inputBuffer[1] == SMElement::SCHEME_PL_CDR_LE[1]) + ? std::endian::little + : std::endian::big; + CdrReader buffer(asBytes(m_inputBuffer.data(), m_inputBuffer.size()), endianness); + // Skip the encapsulation identifier and options (2 + 2 bytes) + skipBytes(buffer, 4); + return m_proxyDataBuffer.readFromBuffer(buffer, mp_participant); +} + rtps::GuidPrefix_t SPDPAgent::participantPrefixInPayload(const uint8_t *data, DataSize_t size) { // A PL_CDR parameter list behind the 4-byte encapsulation header, in the // byte order the header selects (as the ALIVE path reads it); only @@ -225,7 +326,7 @@ bool SPDPAgent::isFromBeforeDispose(const GuidPrefix_t &prefix, const SequenceNu return false; } -void SPDPAgent::processProxyData() { +void SPDPAgent::processProxyData(const SequenceNumber_t &announcementSn) { if (m_proxyDataBuffer.m_guid.prefix.id == mp_participant->m_guidPrefix.id) { return; // Our own packet } @@ -233,13 +334,35 @@ void SPDPAgent::processProxyData() { SPDP_LOG("Message from GUID = {} {} {} {}", m_proxyDataBuffer.m_guid.prefix.id[4], m_proxyDataBuffer.m_guid.prefix.id[5], m_proxyDataBuffer.m_guid.prefix.id[6], m_proxyDataBuffer.m_guid.prefix.id[7]); - const rtps::ParticipantProxyData *remote_part; - remote_part = mp_participant->findRemoteParticipant(m_proxyDataBuffer.m_guid.prefix); - if (remote_part != nullptr) { + using Verdict = Participant::AnnouncementVerdict; + const Verdict verdict = mp_participant->noteRemoteParticipantAnnouncement( + m_proxyDataBuffer.m_guid.prefix, announcementSn); + if (verdict == Verdict::Known) { SPDP_LOG("Not adding this participant"); - mp_participant->refreshRemoteParticipantLiveliness(m_proxyDataBuffer.m_guid.prefix); - return; // Already in our list + return; // Already in our list, lease refreshed + } + if (verdict == Verdict::Restart) { + // The peer restarted with the prefix we know it by (see isRestart): + // everything we hold of it - its builtin proxies, its endpoints and their + // proxies at our readers and writers - belongs to the old incarnation, + // whose writers' sequence numbers our stateful proxies expect to continue. + // Forget it and discover it afresh below. Lock order as for a dispose: + // this agent's mutex, then the SEDP agent's and the participant's inside + // removeRemoteParticipant. + const auto &p = m_proxyDataBuffer.m_guid.prefix; + logger_.warn("Remote participant {:02x}{:02x}{:02x}{:02x}... restarted with the same GUID " + "prefix (SPDP sequence {} far below what it had reached): rediscovering it", + p.id[0], p.id[1], p.id[2], p.id[3], announcementSn.low); + mp_participant->removeRemoteParticipant(p); + // The parser stops at the GUID of a participant it already knows (nothing + // but the lease was refreshed): now that it is forgotten, parse the + // announcement in full for its locators and builtin endpoints. + if (!parseAnnouncement()) { + SPDP_LOG("ParticipantProxyData deserialization failed"); + return; + } } + m_proxyDataBuffer.m_lastSpdpSn = announcementSn; // A newcomer without a usable metatraffic unicast locator could never be // matched (addProxiesForBuiltInEndpoints() refuses it below): check that diff --git a/components/rtps/src/entities/Domain.cpp b/components/rtps/src/entities/Domain.cpp index 6116600c42..1e027ef324 100644 --- a/components/rtps/src/entities/Domain.cpp +++ b/components/rtps/src/entities/Domain.cpp @@ -27,12 +27,16 @@ Author: i11 - Embedded Software, RWTH Aachen University #include "rtps/utils/Log.hpp" #include "rtps/utils/udpUtils.hpp" #include +#include #include #include #include #if defined(ESP_PLATFORM) +#include "esp_attr.h" #include "esp_mac.h" +#include "esp_random.h" +#include "soc/soc_caps.h" #endif #if DOMAIN_VERBOSE && RTPS_GLOBAL_VERBOSE @@ -45,12 +49,78 @@ Author: i11 - Embedded Software, RWTH Aachen University using rtps::Domain; +namespace { +#if defined(ESP_PLATFORM) +// The last GUID prefix incarnation drawn (by this boot's Domains or the +// previous boot's). The record lives in RTC memory (where the chip has it), +// which a software reset (esp_restart, a panic reboot, deep sleep) preserves +// and a power-on leaves with arbitrary contents: the magic + complement check +// tells the two apart. Each Domain draws its incarnation from esp_random and +// records it here (Domain::drawGuidIncarnation). +struct IncarnationRecord { + uint32_t magic; + uint16_t incarnation; + uint16_t check; // ~incarnation +}; +#if SOC_RTC_FAST_MEM_SUPPORTED || SOC_RTC_SLOW_MEM_SUPPORTED +RTC_NOINIT_ATTR IncarnationRecord s_incarnationRecord; +#else +// No RTC memory on this chip: .noinit DRAM also survives a software reset +// (esp_restart, a panic reboot), just not deep sleep. +__NOINIT_ATTR IncarnationRecord s_incarnationRecord; +#endif +constexpr uint32_t kIncarnationMagic = 0x52545049; // 'RTPI' + +// The most recently constructed Domain's incarnation and its predecessor, for +// the static accessors (a firmware logs them without holding the Domain). +std::atomic s_currentIncarnation{0}; +std::atomic s_currentPrevious{-1}; // -1: none +#endif +} // namespace + +void Domain::drawGuidIncarnation() { +#if defined(ESP_PLATFORM) + const bool valid = + s_incarnationRecord.magic == kIncarnationMagic && + s_incarnationRecord.check == static_cast(~s_incarnationRecord.incarnation); + if (valid) { + m_previousIncarnation = s_incarnationRecord.incarnation; + } + do { + m_incarnation = static_cast(esp_random()); + } while (m_previousIncarnation && m_incarnation == *m_previousIncarnation); + s_incarnationRecord = + IncarnationRecord{kIncarnationMagic, m_incarnation, static_cast(~m_incarnation)}; + s_currentIncarnation = m_incarnation; + s_currentPrevious = m_previousIncarnation ? static_cast(*m_previousIncarnation) : -1; +#endif +} + +uint16_t Domain::currentGuidIncarnation() { +#if defined(ESP_PLATFORM) + return s_currentIncarnation.load(); +#else + return 0; +#endif +} + +std::optional Domain::currentPreviousGuidIncarnation() { +#if defined(ESP_PLATFORM) + const int32_t p = s_currentPrevious.load(); + if (p >= 0) { + return static_cast(p); + } +#endif + return std::nullopt; +} + Domain::Domain(const rtps::Ip4AddressBytes &localIpAddress, const DomainConfig &config) : espp::BaseComponent("RtpsDomain", espp::Logger::Verbosity::WARN) , m_defaultTransport(&Domain::datagramJumppad, this, config.transport) , m_transport(&m_defaultTransport) , m_localIpAddress(localIpAddress) , m_config(config) { + drawGuidIncarnation(); m_transportSetupOk = initializeTransport(); } @@ -61,6 +131,7 @@ Domain::Domain(rtps::EsppTransport &transport, const rtps::Ip4AddressBytes &loca , m_transport(&transport) , m_localIpAddress(localIpAddress) , m_config(config) { + drawGuidIncarnation(); m_transportSetupOk = initializeTransport(); } @@ -368,6 +439,15 @@ rtps::Participant *Domain::createParticipant() { auto &entry = m_participants[slot]; entry.reuse(generateGuidPrefix(candidate), candidate, m_localIpAddress, m_config.local_prefix_length); + if (const auto previous = m_previousIncarnation; previous.has_value()) { + // The same board, participant id, vendor and domain with the previous + // boot's incarnation bytes: what peers still hold if we came back within + // our lease. Disposed by the SPDP agent before the first announcement. + entry.m_previousIncarnationPrefix = entry.m_guidPrefix; + entry.m_previousIncarnationPrefix.id[10] = static_cast(*previous >> 8); + entry.m_previousIncarnationPrefix.id[11] = static_cast(*previous & 0xFF); + entry.m_hasPreviousIncarnation = true; + } if (!createBuiltinWritersAndReaders(entry)) { // Pool exhaustion (see createBuiltinWritersAndReaders): the slot was never // published, so only the probed ports need unwinding for a clean failure @@ -1015,8 +1095,11 @@ rtps::GuidPrefix_t Domain::generateGuidPrefix(ParticipantId_t id) const { prefix.id[7] = Config::VENDOR_ID.vendorId[0]; prefix.id[8] = Config::VENDOR_ID.vendorId[1]; prefix.id[9] = Config::DOMAIN_ID; - prefix.id[10] = 0xA5; - prefix.id[11] = 0x5A; + // Bytes 10-11: this boot's incarnation (see guidIncarnation()). Everything + // before it is stable across boots, which is what lets the SPDP agent + // dispose the previous incarnation and peers tell the two apart. + prefix.id[10] = static_cast(m_incarnation >> 8); + prefix.id[11] = static_cast(m_incarnation & 0xFF); return prefix; } #endif diff --git a/components/rtps/src/entities/Participant.cpp b/components/rtps/src/entities/Participant.cpp index 75b7cc7ab7..4470c100ab 100644 --- a/components/rtps/src/entities/Participant.cpp +++ b/components/rtps/src/entities/Participant.cpp @@ -56,6 +56,8 @@ Participant::~Participant() { m_spdpAgent.stop(); } void Participant::reuse(const GuidPrefix_t &guidPrefix, ParticipantId_t participantId, const Ip4AddressBytes &localIpAddress, uint8_t localPrefixLength) { + m_hasPreviousIncarnation = false; + m_previousIncarnationPrefix = GuidPrefix_t{}; m_guidPrefix = guidPrefix; m_participantId = participantId; m_localIpAddress = localIpAddress; @@ -554,6 +556,30 @@ const rtps::ParticipantProxyData *Participant::findRemoteParticipant(const GuidP return m_remoteParticipants.find(thunk, &isElementToFind); } +Participant::AnnouncementVerdict +Participant::noteRemoteParticipantAnnouncement(const GuidPrefix_t &prefix, + const SequenceNumber_t &sn) { + std::lock_guard lock(m_mutex); + auto isElementToFind = [&](const ParticipantProxyData &proxy) { + return proxy.m_guid.prefix == prefix; + }; + auto thunk = [](void *arg, const ParticipantProxyData &value) { + return (*static_cast(arg))(value); + }; + auto remoteParticipant = m_remoteParticipants.find(thunk, &isElementToFind); + if (remoteParticipant == nullptr) { + return AnnouncementVerdict::Unknown; + } + if (SPDPAgent::isRestart(sn, remoteParticipant->m_lastSpdpSn)) { + return AnnouncementVerdict::Restart; + } + remoteParticipant->onAliveSignal(); + if (remoteParticipant->m_lastSpdpSn < sn) { + remoteParticipant->m_lastSpdpSn = sn; + } + return AnnouncementVerdict::Known; +} + void Participant::refreshRemoteParticipantLiveliness(const GuidPrefix_t &prefix) { std::lock_guard lock(m_mutex); auto isElementToFind = [&](const ParticipantProxyData &proxy) { diff --git a/components/rtps/src/entities/StatelessReader.cpp b/components/rtps/src/entities/StatelessReader.cpp index 975f2390a7..77971b9c13 100644 --- a/components/rtps/src/entities/StatelessReader.cpp +++ b/components/rtps/src/entities/StatelessReader.cpp @@ -76,7 +76,10 @@ void StatelessReader::newChange(const ReaderCacheChange &cacheChange) { // match are lost either way; the matched ones that follow arrive in order. // The builtin readers are exempt (the only stateless one is the SPDP // reader): participant announcements come from writers that are, by - // definition, not matched yet. + // definition, not matched yet. (The SPDP reader never holds a writer proxy, + // so the ordering rule never applies to announcements; a peer that restarts + // with the prefix we know it by is caught by the SPDP agent instead - + // SPDPAgent::isRestart.) // // The claim and the callbacks are one operation under m_delivery_mutex (as // in StatefulReader::newChange()): receive workers for different sockets diff --git a/pc/tests/rtps_participant_restart.cpp b/pc/tests/rtps_participant_restart.cpp new file mode 100644 index 0000000000..5e707dc943 --- /dev/null +++ b/pc/tests/rtps_participant_restart.cpp @@ -0,0 +1,406 @@ +// A peer that restarts is rediscovered at once, not when its lease runs out. +// +// The GUID prefix of an embedded participant is built from the board's MAC, +// so a board that rebooted within its lease used to come back with the prefix +// its peers still held - and every one of its writers numbering its samples +// from 1 again. Its announcements only refreshed the known participant's +// lease, the stateful readers kept waiting for the old numbers and a +// best-effort reader ignored the restarted writer (RTPS 2.5 8.4.12.1), so +// nothing moved until the lease sweep forgot the old incarnation (5 s for an +// ESP peer, 100 s for a host one). This test drives the receiving side of the +// fix with hand-crafted datagrams fed to a real participant, as the dispose +// tests do: +// +// 1. Restart detection: an announcement from a known participant numbered +// far below its highest (SPDPAgent::isRestart) forgets the participant +// and rediscovers it; its writers get fresh proxies, and a best-effort +// reader receives the restarted writer's samples from 1 again. +// 2. A reordered or duplicated announcement (last - 1) is NOT a restart: +// nothing is forgotten, a sample numbered after the ones delivered still +// arrives. +// 3. Incarnation: a rebooted board of this engine comes back with new +// incarnation bytes (10-11) and first disposes its previous incarnation +// AS that incarnation (old prefix, its SPDP writer, a sequence number +// above anything it sent): the old participant goes at once, the new one +// is discovered, and a stale announcement of the old one still in flight +// is ignored. A dispose naming a participant from any other prefix is +// refused, as before. +// +// Exits 0 on success, 1 on the first failed check. + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "rtps/entities/Domain.hpp" +#include "rtps/entities/Reader.hpp" +#include "rtps/entities/Writer.hpp" +#include "rtps/messages/MessageTypes.hpp" + +namespace { + +constexpr rtps::Ip4AddressBytes kIp{127, 0, 0, 1}; +const std::array kVendor = rtps::Config::VENDOR_ID.vendorId; // an espp-shaped peer + +#define CHECK(cond, msg) \ + do { \ + if (!(cond)) { \ + std::printf("FAIL: %s (line %d)\n", msg, __LINE__); \ + return false; \ + } \ + } while (0) + +void push_u16(std::vector &p, uint16_t v) { + p.push_back(static_cast(v & 0xFF)); + p.push_back(static_cast(v >> 8)); +} + +void push_u32(std::vector &p, uint32_t v) { + for (int i = 0; i < 4; ++i) { + p.push_back(static_cast((v >> (8 * i)) & 0xFF)); + } +} + +void push_entity_id(std::vector &p, const rtps::EntityId_t &id) { + p.insert(p.end(), id.entityKey.begin(), id.entityKey.end()); + p.push_back(static_cast(id.entityKind)); +} + +void push_guid(std::vector &p, const rtps::Guid_t &guid) { + p.insert(p.end(), guid.prefix.id.begin(), guid.prefix.id.end()); + push_entity_id(p, guid.entityId); +} + +void push_param(std::vector &p, rtps::SMElement::ParameterId pid, + const std::vector &value) { + push_u16(p, static_cast(pid)); + push_u16(p, static_cast(value.size())); + p.insert(p.end(), value.begin(), value.end()); +} + +void push_sentinel(std::vector &p) { + push_param(p, rtps::SMElement::ParameterId::PID_SENTINEL, {}); +} + +std::vector guid_value(const rtps::Guid_t &guid) { + std::vector v; + push_guid(v, guid); + return v; +} + +std::vector string_value(const char *s) { + std::vector v; + const auto len = static_cast(std::strlen(s) + 1); + push_u32(v, len); + v.insert(v.end(), s, s + len); + while (v.size() % 4 != 0) { + v.push_back(0); + } + return v; +} + +std::vector locator_value(uint32_t port) { + std::vector v; + push_u32(v, static_cast(rtps::LocatorKind_t::LOCATOR_KIND_UDPv4)); + push_u32(v, port); + for (int i = 0; i < 12; ++i) { + v.push_back(0); + } + v.insert(v.end(), kIp.begin(), kIp.end()); + return v; +} + +std::vector encapsulation() { + std::vector p(rtps::SMElement::SCHEME_PL_CDR_LE.begin(), + rtps::SMElement::SCHEME_PL_CDR_LE.end()); + push_u16(p, 0); + return p; +} + +std::vector spdp_payload(const rtps::GuidPrefix_t &prefix) { + using rtps::SMElement::ParameterId; + std::vector p = encapsulation(); + push_param(p, ParameterId::PID_PROTOCOL_VERSION, + {rtps::PROTOCOLVERSION.major, rtps::PROTOCOLVERSION.minor, 0, 0}); + push_param(p, ParameterId::PID_VENDORID, {kVendor[0], kVendor[1], 0, 0}); + push_param(p, ParameterId::PID_PARTICIPANT_GUID, + guid_value(rtps::Guid_t{prefix, rtps::ENTITYID_BUILD_IN_PARTICIPANT})); + push_param(p, ParameterId::PID_METATRAFFIC_UNICAST_LOCATOR, locator_value(7410)); + push_param(p, ParameterId::PID_DEFAULT_UNICAST_LOCATOR, locator_value(7411)); + { + std::vector lease; + push_u32(lease, 100); + push_u32(lease, 0); + push_param(p, ParameterId::PID_PARTICIPANT_LEASE_DURATION, lease); + } + { + std::vector set; + push_u32(set, rtps::SMElement::DISC_BIE_PARTICIPANT_ANNOUNCER | + rtps::SMElement::DISC_BIE_PARTICIPANT_DETECTOR | + rtps::SMElement::DISC_BIE_PUBLICATION_ANNOUNCER | + rtps::SMElement::DISC_BIE_PUBLICATION_DETECTOR | + rtps::SMElement::DISC_BIE_SUBSCRIPTION_ANNOUNCER | + rtps::SMElement::DISC_BIE_SUBSCRIPTION_DETECTOR); + push_param(p, ParameterId::PID_BUILTIN_ENDPOINT_SET, set); + } + push_sentinel(p); + return p; +} + +std::vector sedp_payload(const rtps::Guid_t &endpoint, const char *topic, const char *type, + bool reliable) { + using rtps::SMElement::ParameterId; + std::vector p = encapsulation(); + push_param(p, ParameterId::PID_ENDPOINT_GUID, guid_value(endpoint)); + push_param(p, ParameterId::PID_TOPIC_NAME, string_value(topic)); + push_param(p, ParameterId::PID_TYPE_NAME, string_value(type)); + { + std::vector rel; + push_u32(rel, static_cast(reliable ? rtps::ReliabilityKind_t::RELIABLE + : rtps::ReliabilityKind_t::BEST_EFFORT)); + push_u32(rel, 0); + push_u32(rel, 0); + push_param(p, ParameterId::PID_RELIABILITY, rel); + } + push_param(p, ParameterId::PID_UNICAST_LOCATOR, locator_value(7411)); + push_sentinel(p); + return p; +} + +// A DATA submessage in one RTPS message from `prefix`, with optional inline +// QoS and payload. +std::vector data_message(const rtps::GuidPrefix_t &prefix, const rtps::EntityId_t &writer, + const rtps::EntityId_t &reader, uint32_t sn, + const std::vector &inline_qos, + const std::vector &payload) { + std::vector m{ + 'R', 'T', 'P', 'S', rtps::PROTOCOLVERSION.major, rtps::PROTOCOLVERSION.minor, + kVendor[0], kVendor[1]}; + m.insert(m.end(), prefix.id.begin(), prefix.id.end()); + uint8_t flags = rtps::FLAG_LITTLE_ENDIAN; + if (!inline_qos.empty()) { + flags |= rtps::FLAG_INLINE_QOS; + } + if (!payload.empty()) { + flags |= rtps::FLAG_DATA_PAYLOAD; + } + m.push_back(static_cast(rtps::SubmessageKind::DATA)); + m.push_back(flags); + push_u16(m, static_cast(2 + 2 + 4 + 4 + 8 + inline_qos.size() + payload.size())); + push_u16(m, 0); // extraFlags + push_u16(m, 16); // octetsToInlineQos + push_entity_id(m, reader); + push_entity_id(m, writer); + push_u32(m, 0); // SequenceNumber_t.high + push_u32(m, sn); // SequenceNumber_t.low + m.insert(m.end(), inline_qos.begin(), inline_qos.end()); + m.insert(m.end(), payload.begin(), payload.end()); + return m; +} + +// Inline QoS of a participant dispose: the key hash of the disposed +// participant and STATUS_INFO disposed|unregistered, as Fast DDS writes it and +// as this engine's SPDPAgent::sendPreviousIncarnationDispose does. +std::vector participant_dispose_qos(const rtps::GuidPrefix_t &disposed) { + using rtps::SMElement::ParameterId; + std::vector q; + push_param(q, ParameterId::PID_KEY_HASH, + guid_value(rtps::Guid_t{disposed, rtps::ENTITYID_BUILD_IN_PARTICIPANT})); + push_param(q, ParameterId::PID_STATUS_INFO, {0, 0, 0, 3}); + push_sentinel(q); + return q; +} + +// A user sample: CDR_LE encapsulation + 4 bytes of payload. +std::vector sample_payload(uint32_t value) { + std::vector p{0x00, 0x01, 0x00, 0x00}; + push_u32(p, value); + return p; +} + +void feed(rtps::Participant *part, const std::vector &message) { + part->newMessage(message.data(), static_cast(message.size())); +} + +constexpr const char *kTopic = "restart_topic"; +constexpr const char *kType = "RestartType"; + +std::atomic g_received{0}; +std::atomic g_last_value{0}; + +void on_sample(void *, const rtps::ReaderCacheChange &change) { + uint8_t buf[8] = {0}; + if (change.copyInto(buf, sizeof(buf))) { + uint32_t v = 0; + std::memcpy(&v, buf + 4, sizeof(v)); + g_last_value = v; + } + ++g_received; +} + +// A simulated peer: its SPDP writer, its SEDP publications writer and one +// user writer, each numbering its DATAs independently - like a real stack. +struct Peer { + rtps::GuidPrefix_t prefix; + uint32_t spdp_sn = 0; + uint32_t sedp_sn = 0; + uint32_t data_sn = 0; + rtps::Guid_t writer_guid() const { + return {prefix, {{0x00, 0x00, 0x01}, rtps::EntityKind_t::USER_DEFINED_WRITER_WITHOUT_KEY}}; + } + void announce(rtps::Participant *part) { + feed(part, data_message(prefix, rtps::ENTITYID_SPDP_BUILTIN_PARTICIPANT_WRITER, + rtps::ENTITYID_SPDP_BUILTIN_PARTICIPANT_READER, ++spdp_sn, {}, + spdp_payload(prefix))); + } + // An announcement that repeats an earlier number (a duplicated or reordered datagram). + void announce_with(rtps::Participant *part, uint32_t sn) const { + feed(part, data_message(prefix, rtps::ENTITYID_SPDP_BUILTIN_PARTICIPANT_WRITER, + rtps::ENTITYID_SPDP_BUILTIN_PARTICIPANT_READER, sn, {}, + spdp_payload(prefix))); + } + void announce_writer(rtps::Participant *part) { + feed(part, data_message(prefix, rtps::ENTITYID_SEDP_BUILTIN_PUBLICATIONS_WRITER, + rtps::ENTITYID_SEDP_BUILTIN_PUBLICATIONS_READER, ++sedp_sn, {}, + sedp_payload(writer_guid(), kTopic, kType, false))); + } + void publish(rtps::Participant *part, uint32_t value) { + feed(part, data_message(prefix, writer_guid().entityId, rtps::ENTITYID_UNKNOWN, ++data_sn, {}, + sample_payload(value))); + } + // Dispose `disposed` from this peer's SPDP writer, numbered `sn`. + void dispose(rtps::Participant *part, const rtps::GuidPrefix_t &disposed, uint32_t sn) const { + feed(part, data_message(prefix, rtps::ENTITYID_SPDP_BUILTIN_PARTICIPANT_WRITER, + rtps::ENTITYID_SPDP_BUILTIN_PARTICIPANT_READER, sn, + participant_dispose_qos(disposed), {})); + } + // The peer rebooted: every writer starts at 1 again. + void reboot() { spdp_sn = sedp_sn = data_sn = 0; } +}; + +bool run_checks() { + rtps::Domain domain(kIp); + rtps::Participant *part = domain.createParticipant(); + CHECK(part != nullptr, "createParticipant"); + rtps::Reader *reader = + domain.createReader(*part, kTopic, kType, /*reliable=*/false, {0, 0, 0, 0}); + CHECK(reader != nullptr, "createReader"); + reader->registerCallback(on_sample, nullptr); + + // An ESP-style prefix: MAC, participant id, this engine's vendor id, domain, + // incarnation (the layout Domain::generateGuidPrefix produces on a board). + const auto vid = rtps::Config::VENDOR_ID.vendorId; + Peer peer{{{0x24, 0x6f, 0x28, 0xaa, 0xbb, 0xcc, 0, vid[0], vid[1], 0, 0x11, 0x22}}}; + + // --- discovered, matched, delivering ------------------------------------------------- + for (int i = 0; i < 6; ++i) { + peer.announce(part); // SPDP 1..6: a peer that has been around a while + } + CHECK(part->getRemoteParticipantCount() == 1, "peer discovered"); + peer.announce_writer(part); + CHECK(reader->getProxiesCount() == 1, "peer writer matched"); + for (uint32_t v = 1; v <= 3; ++v) { + peer.publish(part, v); // DATA 1..3 + } + CHECK(g_received == 3, "three samples delivered"); + CHECK(g_last_value == 3, "the last one is sample 3"); + + // --- 2. a duplicated / reordered announcement is not a restart -------------------------- + peer.announce_with(part, 5); // 5 after 6: one datagram late + CHECK(part->getRemoteParticipantCount() == 1, "late announcement: participant kept"); + CHECK(reader->getProxiesCount() == 1, "late announcement: writer proxy kept"); + peer.publish(part, 4); // DATA 4 continues the stream + CHECK(g_received == 4, "stream continues after a late announcement"); + peer.announce_with(part, 3); // half of 6: this one IS below the restart threshold + // ... and that is a restart by the rule (3 * 2 <= 6); the peer is rediscovered + // from this announcement, so its writer must be announced again - a real + // restarted peer does exactly that. Check the proxy went, then re-announce. + CHECK(part->getRemoteParticipantCount() == 1, "restart threshold: rediscovered participant"); + CHECK(reader->getProxiesCount() == 0, "restart threshold: the old writer proxy is gone"); + peer.sedp_sn = 0; + peer.data_sn = 0; + peer.announce_writer(part); + CHECK(reader->getProxiesCount() == 1, "restart threshold: writer matched again"); + peer.publish(part, 10); + CHECK(g_received == 5 && g_last_value == 10, "restart threshold: sample 1 of the new stream"); + // bring the peer's number up again for the next case + peer.spdp_sn = 3; + for (int i = 0; i < 6; ++i) { + peer.announce(part); // 4..9 + } + for (uint32_t v = 11; v <= 13; ++v) { + peer.publish(part, v); // DATA 2..4 + } + CHECK(g_received == 8 && g_last_value == 13, "stream continues: samples 2..4"); + + // --- 1. the peer reboots with the same prefix, no dispose --------------------------------- + peer.reboot(); + peer.announce(part); // SPDP 1 after 9 + CHECK(part->getRemoteParticipantCount() == 1, "rebooted peer: still exactly one participant"); + CHECK(reader->getProxiesCount() == 0, "rebooted peer: the old writer proxy is gone"); + peer.announce_writer(part); // SEDP 1 + CHECK(reader->getProxiesCount() == 1, "rebooted peer: its writer matched again"); + for (uint32_t v = 21; v <= 23; ++v) { + peer.publish(part, v); // DATA 1..3 again - these used to be dropped + } + CHECK(g_received == 11, "rebooted peer: its samples 1..3 delivered"); + CHECK(g_last_value == 23, "rebooted peer: the last one is sample 3 of the new stream"); + + // --- 3. the board reboots into a new incarnation and disposes the old one ----------------- + // What a rebooted board of this engine sends first (SPDPAgent:: + // sendPreviousIncarnationDispose): a dispose of the OLD participant, as the + // old participant - its prefix, its SPDP writer - with a sequence number + // above anything that writer reached. Then the new incarnation announces. + Peer next = peer; + next.reboot(); + next.prefix.id[10] = 0x33; // the incarnation bytes change, nothing else + next.prefix.id[11] = 0x44; + // a dispose from an unrelated prefix naming the peer: refused, as always + Peer stranger{{{0x24, 0x6f, 0x28, 0x01, 0x02, 0x03, 0, vid[0], vid[1], 0, 0x11, 0x22}}}; + stranger.dispose(part, peer.prefix, 1); + CHECK(part->getRemoteParticipantCount() == 1, "dispose from a stranger: refused"); + // ... and from the next incarnation's own writer naming the old one: another + // prefix is another participant, refused too (the engine does not send that) + next.dispose(part, peer.prefix, 1); + CHECK(part->getRemoteParticipantCount() == 1, "dispose from another prefix: refused"); + CHECK(reader->getProxiesCount() == 1, "refused disposes change nothing"); + // the old incarnation's own dispose, numbered beyond its last announcement + peer.dispose(part, peer.prefix, std::numeric_limits::max()); + CHECK(part->getRemoteParticipantCount() == 0, "the previous incarnation's dispose: honoured"); + CHECK(reader->getProxiesCount() == 0, "previous incarnation: the old writer proxy is gone"); + next.announce(part); + CHECK(part->getRemoteParticipantCount() == 1, "next incarnation discovered"); + next.announce_writer(part); + CHECK(reader->getProxiesCount() == 1, "next incarnation: its writer matched"); + for (uint32_t v = 31; v <= 33; ++v) { + next.publish(part, v); + } + CHECK(g_received == 14 && g_last_value == 33, "next incarnation: samples delivered"); + // a stale announcement of the old incarnation still in flight (a delayed + // datagram, numbered below the dispose) must not bring the dead participant + // back next to the new one + peer.announce_with(part, 9); + CHECK(part->getRemoteParticipantCount() == 1, "stale old-incarnation announcement: ignored"); + CHECK(reader->getProxiesCount() == 1, "stale old-incarnation announcement: new proxy kept"); + next.publish(part, 34); + CHECK(g_received == 15 && g_last_value == 34, "new incarnation keeps delivering"); + + domain.stop(); + return true; +} + +} // namespace + +int main() { + if (!run_checks()) { + return 1; + } + std::printf("PASS\n"); + return 0; +}