Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 18 additions & 3 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -165,9 +165,12 @@ jobs:
timeout 300s "$integration/check_version_skew.sh" "$GITHUB_WORKSPACE/json-install" \
"$GITHUB_WORKSPACE/skew" "$config_tool"

# Pinned: FastDDS 2.14 does not build with GCC 15 (its headers use
# uint8_t without <cstdint>), which ubuntu-latest ships since it moved
# past Ubuntu 24.04.
fastdds:
name: ubuntu-latest (FastDDS ${{ matrix.fastdds }})
runs-on: ubuntu-latest
name: ubuntu-24.04 (FastDDS ${{ matrix.fastdds }})
runs-on: ubuntu-24.04
strategy:
fail-fast: false
matrix:
Expand All @@ -186,12 +189,24 @@ jobs:
sudo apt-get update
sudo apt-get install -y libasio-dev libtinyxml2-dev libssl-dev ninja-build nlohmann-json3-dev

# FastDDS links the system's tinyxml2 and OpenSSL, so a cached build
# only works on the same OS release with the same library versions.
# runner.os alone stays "Linux" when ubuntu-latest moves to a newer
# Ubuntu, which once restored a build whose libtinyxml2 was gone.
- name: Fingerprint system libraries
id: system
run: |
. /etc/os-release
libs=$(dpkg-query -W -f='${Package}=${Version} ' libtinyxml2-dev libssl-dev)
echo "$ID $VERSION_ID: $libs"
echo "key=$ID-$VERSION_ID-$(echo "$libs" | sha256sum | cut -c1-12)" >> "$GITHUB_OUTPUT"

- name: Cache FastDDS
id: cache-deps
uses: actions/cache@v4
with:
path: ${{ env.DEPS_PREFIX }}
key: fastdds-${{ runner.os }}-${{ matrix.fastdds }}-${{ matrix.fastcdr }}-v1
key: fastdds-${{ steps.system.outputs.key }}-${{ matrix.fastdds }}-${{ matrix.fastcdr }}-v1

- name: Build FastDDS from source
if: steps.cache-deps.outputs.cache-hit != 'true'
Expand Down
23 changes: 23 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,29 @@ each minor release may break the API and the ABI: the shared libraries carry
the minor version in their soname (`libpuppet_master.so.0.4`), and
`find_package(PuppetMaster 0.4)` accepts only 0.4.x.

## Unreleased

### Added

- **Service commands in the topic tool.** `puppet_master_topic service list
--system FILE` shows each service the system declares, who serves and
calls it, and whether its server is up, from the presence topic alone.
`service call SERVICE --system FILE` sends one request (`--data TEXT` or
`--hex HEX`) through an ordinary client and prints the reply, or exits
with 1 and the call's status. Both work on shared memory and, when built
with it, FastDDS. See [Services](docs/launcher.md#services).
- `shm::ReadNewestMessage(domain, endpoint)` reads the newest message of a
topic from its segment without attaching, so no writer or reader notices.
`service list` uses it on shared memory to tell a server that said goodbye
(`stopped`) from one whose heartbeats stopped without one (`down`, with
its last heartbeat's age), also when the server stopped before the tool
started. See [Segment Lifetime](docs/shm-transport.md#segment-lifetime).
- **Typed service calls.** `service call --field TYPE:VALUE` builds a
portable-codec request field by field (`bool`, `i8`-`i64`, `u8`-`u64`,
`f32`, `f64`, `string`, with `[]` for a vector or `[N]` for an array), and
`--reply-fields TYPE,...` decodes the reply into one line per field. See
[Typed Requests](docs/launcher.md#typed-requests).

## 0.4.0

Rebuild everything that links PuppetMaster: the soname is now
Expand Down
89 changes: 87 additions & 2 deletions docs/launcher.md
Original file line number Diff line number Diff line change
Expand Up @@ -186,8 +186,9 @@ In C++, `configuration::Supervisor` in

`puppet_master_topic` looks at the shared-memory topics of a running system,
and its FastDDS topics when built with that adapter (see
[FastDDS Topics](#fastdds-topics)). It is built and installed with the JSON
and shared-memory adapters.
[FastDDS Topics](#fastdds-topics)), and at its services (see
[Services](#services)). It is built and installed with the JSON and
shared-memory adapters.

```bash
puppet_master_topic list
Expand Down Expand Up @@ -248,6 +249,90 @@ The tool also records and replays topics:

See [Recordings](recording.md).

### Services

The tool also looks at a system's services and calls them. Both commands
need `--system FILE`; `--domain N` picks the domain as for topics.

```bash
puppet_master_topic service list --system system.json
puppet_master_topic service call /map/query --system system.json --data "a b" --text
puppet_master_topic service call /map/query --system system.json --hex "01 00 2a"
```

| Command | Effect |
|---|---|
| `service list` | each service the manifest's nodes declare: request and reply types, transport, which components serve and call it, and whether a server is up, with its instance id and the age of its newest heartbeat |
| `service call SERVICE` | send one request, the bytes of `--data TEXT`, of `--hex HEX`, of `--field TYPE:VALUE`s (see [Typed Requests](#typed-requests)), or none, and print the reply's size, round trip, and bytes (in hex, or `--text`; all of them unless `--bytes N`), or its fields with `--reply-fields` |

`service list` reads each service's presence topic only, so it creates no
client and no reply topic. It listens for three heartbeat intervals (at
least 1 s on FastDDS, for discovery), or `--timeout-ms N`. When no heartbeat
arrives in that time, on shared memory it reads the last presence message
left in the topic's segment (`shm::ReadNewestMessage`, without attaching):

| `server:` | Meaning |
|---|---|
| `up, instance ID, heartbeat N ms ago` | a heartbeat within three intervals |
| `stopped (instance ID said goodbye N ms ago)` | the server closed in order |
| `down (instance ID stopped without a goodbye; last heartbeat N ms ago)` | its heartbeats stopped: a crash, a kill, or a server too busy to keep its interval |
| `down (no heartbeat in N ms)` | nothing to read: never started, on FastDDS, or on Windows after its last process closed the topic |

Clients send no heartbeats, so `clients` lists the components that declare
the service, not the processes running.

`service call` uses an ordinary `service::Client`, so the server handles the
request like any other. It waits up to `--timeout-ms N` (2000 by default)
for a server and its reply, then exits with 1 and the call's status, such as
`unavailable` (no live server), `deadline_exceeded`, or the handler's own
error and message.

#### Typed Requests

For a service whose messages use the [portable codec](typed-messages.md#portable-codec),
`--field TYPE:VALUE` builds the request field by field, in the order of the
type's `PortableFields`, and `--reply-fields TYPE,...` decodes the reply the
same way. The tool has no C++ types of its own, so the field list is yours to
match:

```bash
# struct PoseQuery { std::string frame; std::uint32_t id; std::vector<double> weights; };
# struct Pose { double x, y; std::string frame; std::array<float, 2> covariance; bool valid; };
puppet_master_topic service call /map/pose --system system.json \
--field string:map --field u32:7 --field "f64[]:1, 2.5" \
--reply-fields "f64,f64,string,f32[2],bool"
```

```text
call /map/pose: server 7763ad3f9789659a, request 31 B
reply 32 B in 0.6 ms
1 f64: 10.5
2 f64: 3.5
3 string: "map"
4 f32[2]: [0.25, -1]
5 bool: true
```

| Type | Value |
|---|---|
| `bool` | `true`, `false`, `1`, or `0` |
| `i8` `i16` `i32` `i64`, `u8` `u16` `u32` `u64` | decimal or `0x` hex, within the type's range |
| `f32`, `f64` | a decimal number, such as `1.5` or `-3e2` |
| `string` | the rest of the argument, as it is |
| `T[]` | a vector: elements separated by commas; empty for none |
| `T[N]` | an array of exactly N elements |

A field of a nested type is its own fields in order, so list those. Enums are
their underlying integer type. String elements of a vector cannot contain a
comma.

A request missing a field comes back as the server's decode error
(`data_loss: ...: message ends inside a field`). A reply that does not match
`--reply-fields` exits with 1, names the first field that failed or the bytes
left over, and prints the reply's bytes so the list can be corrected. A
change to a message's fields also changes its version, so check the
`request` and `reply` versions `service list` shows.

## Library Helpers

These are in the core library and need no JSON:
Expand Down
3 changes: 3 additions & 0 deletions docs/services.md
Original file line number Diff line number Diff line change
Expand Up @@ -349,6 +349,9 @@ configured request or reply descriptor that differs from the types' codecs,
naming both versions.

`--describe` lists services and which components serve and call them.
`puppet_master_topic service list` shows the same for a running system,
with whether each server is up, and `service call` sends a request from the
command line; see [Topic Tool](launcher.md#services).
`validate --system` checks them across processes like topics: the same
contract (types, versions, encoding, transport) everywhere, exactly one
serving process, which is how a second server is caught before it runs, and
Expand Down
7 changes: 7 additions & 0 deletions docs/shm-transport.md
Original file line number Diff line number Diff line change
Expand Up @@ -203,6 +203,13 @@ shares it with processes started later. The same operations are available
in C++ as `shm::ListSegments` and `shm::RemoveUnusedSegments`. On Windows they
return `Unsupported`, since there is nothing left over to clean.

`shm::ReadNewestMessage(domain, endpoint)` returns the newest message of one
topic, read from its segment the same way: without attaching, so no writer
or reader notices, and readers created later still start after it. Tools use
it for the last word of a writer that may have stopped, such as a service's
final heartbeat or goodbye. On Linux the segment, and so the message, outlive
their processes; on Windows only while some process has the topic open.

## Limits

- Same host only. Use the FastDDS adapter across hosts.
Expand Down
11 changes: 11 additions & 0 deletions include/puppet_master/transport/shm/shm_transport.h
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,17 @@ PUPPET_MASTER_API const char* ToString(SegmentInfo::State state) noexcept;
PUPPET_MASTER_API core::Result<std::vector<SegmentInfo>> ListSegments(
std::optional<core::DomainId> domain_id = std::nullopt);

// The newest message written to a topic on this host, read from its segment
// without attaching, so no running process notices: for tools that want the
// last word of a writer that may have stopped. Its sequence and source
// timestamp are the writer's (the steady clock, which every process on the
// host shares); reception_timestamp is when it was read. Empty if nothing was
// written yet. NotFound if the topic has no segment, which on Windows means
// no process has it open; InvalidArgument if the segment carries another
// message descriptor than `endpoint`.
PUPPET_MASTER_API core::Result<std::optional<Message>> ReadNewestMessage(
core::DomainId domain_id, const EndpointConfig& endpoint);

// Removes the listed segments that no live process uses (kUnused,
// kUninitialized, kIncompatible) and returns them. Segments in use are never
// removed. A process that attaches between the check and the removal keeps
Expand Down
2 changes: 1 addition & 1 deletion src/transport/shm/platform.h
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ class SharedRegion {
static core::Status Remove(const std::string& name);

// Maps an existing region read-only, for inspection. NotFound if it does
// not exist. Unsupported on Windows.
// not exist. On Windows a region exists only while a process has it open.
static core::Result<std::unique_ptr<SharedRegion>> OpenReadOnly(const std::string& name);

// Names of the regions this layer created in `domain` (every domain if
Expand Down
27 changes: 24 additions & 3 deletions src/transport/shm/platform_windows.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -109,10 +109,31 @@ core::Status SharedRegion::Remove(const std::string& /*name*/)
return core::Status::Ok();
}

core::Result<std::unique_ptr<SharedRegion>> SharedRegion::OpenReadOnly(const std::string& /*name*/)
core::Result<std::unique_ptr<SharedRegion>> SharedRegion::OpenReadOnly(const std::string& name)
{
return core::Result<std::unique_ptr<SharedRegion>>::FromStatus(
core::Status::Unsupported("shm segment inspection is not supported on Windows"));
using ResultType = core::Result<std::unique_ptr<SharedRegion>>;
HANDLE mapping = OpenFileMappingW(FILE_MAP_READ, FALSE, Widen(name).c_str());
if (mapping == nullptr) {
if (GetLastError() == ERROR_FILE_NOT_FOUND) {
return ResultType::FromStatus(core::Status::NotFound("no shared region " + name));
}
return ResultType::FromStatus(core::Status::Unavailable(LastErrorMessage("OpenFileMappingW")));
}
void* data = MapViewOfFile(mapping, FILE_MAP_READ, 0, 0, 0);
if (data == nullptr) {
auto status = core::Status::Unavailable(LastErrorMessage("MapViewOfFile"));
CloseHandle(mapping);
return ResultType::FromStatus(std::move(status));
}
// The view is the whole mapping, rounded up to whole pages.
MEMORY_BASIC_INFORMATION info {};
if (VirtualQuery(data, &info, sizeof(info)) == 0) {
auto status = core::Status::Unavailable(LastErrorMessage("VirtualQuery"));
UnmapViewOfFile(data);
CloseHandle(mapping);
return ResultType::FromStatus(std::move(status));
}
return ResultType(std::unique_ptr<SharedRegion>(new SharedRegion(data, info.RegionSize, false, mapping)));
}

core::Result<std::vector<std::string>> SharedRegion::List(std::optional<core::DomainId> /*domain*/)
Expand Down
88 changes: 76 additions & 12 deletions src/transport/shm/segment.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -490,32 +490,29 @@ void Segment::ReclaimDeadParticipants() noexcept
}
}

core::Result<SegmentInspection> InspectSegment(const std::string& name)
namespace {

SegmentInspection Inspect(const SharedRegion& region)
{
using ResultType = core::Result<SegmentInspection>;
auto region = SharedRegion::OpenReadOnly(name);
if (!region.ok()) {
return ResultType::FromStatus(region.status());
}
SegmentInspection inspection;
inspection.size = region.value()->size();
inspection.size = region.size();
if (inspection.size < HeaderSize()) {
inspection.state = inspection.size == 0 ? SegmentInspection::State::kUninitialized
: SegmentInspection::State::kIncompatible;
inspection.problem = inspection.size == 0 ? "never sized" : "smaller than a segment header";
return ResultType(std::move(inspection));
return inspection;
}
const auto& header = *static_cast<const SegmentHeader*>(region.value()->data());
const auto& header = *static_cast<const SegmentHeader*>(region.data());
if (header.magic.load(std::memory_order_acquire) != kMagic) {
inspection.state = SegmentInspection::State::kUninitialized;
inspection.problem = "header never published";
return ResultType(std::move(inspection));
return inspection;
}
if (header.layout_version != kLayoutVersion || header.header_size != HeaderSize()) {
inspection.state = SegmentInspection::State::kIncompatible;
inspection.problem = "layout version " + std::to_string(header.layout_version) + ", expected "
+ std::to_string(kLayoutVersion);
return ResultType(std::move(inspection));
return inspection;
}
inspection.topic = LoadName(header.topic_name);
inspection.descriptor = StoredDescriptor(header);
Expand All @@ -528,7 +525,74 @@ core::Result<SegmentInspection> InspectSegment(const std::string& name)
inspection.participants.push_back(ProcessIdentity {
entry.pid.load(std::memory_order_relaxed), entry.start_time.load(std::memory_order_relaxed)});
}
return ResultType(std::move(inspection));
return inspection;
}

// The newest committed message, by the reader's seqlock protocol. A slot the
// writers overwrite while it is copied is retried a few times, then given up.
std::optional<Message> ReadNewest(const SharedRegion& region, const SegmentInspection& inspection)
{
const auto& geometry = inspection.geometry;
const auto stride = SlotStride(geometry.slot_payload_size);
const auto size = SegmentSize(geometry);
if (stride == 0 || geometry.slot_count == 0 || size == 0 || region.size() < size) {
return std::nullopt;
}
const auto& header = *static_cast<const SegmentHeader*>(region.data());
const auto* slots = static_cast<const unsigned char*>(region.data()) + HeaderSize();
for (int attempt = 0; attempt < 16; ++attempt) {
const std::uint64_t newest = header.write_seq.load(std::memory_order_acquire);
if (newest == 0) {
return std::nullopt;
}
const unsigned char* slot = slots + static_cast<std::size_t>(newest % geometry.slot_count) * stride;
const auto* slot_header = reinterpret_cast<const SlotHeader*>(slot);
const std::uint64_t before = slot_header->seq.load(std::memory_order_acquire);
if (before != newest) {
continue; // a writer moved on; take the new newest
}
const std::uint64_t payload_size = slot_header->payload_size.load(std::memory_order_relaxed);
const std::int64_t timestamp = slot_header->source_timestamp_ns.load(std::memory_order_relaxed);
if (payload_size > geometry.slot_payload_size) {
continue;
}
Message message;
message.payload.resize(static_cast<std::size_t>(payload_size));
CopyFromShared(message.payload.data(), slot + kSlotPayloadOffset, static_cast<std::size_t>(payload_size));
std::atomic_thread_fence(std::memory_order_acquire);
if (slot_header->seq.load(std::memory_order_relaxed) != before) {
continue;
}
message.metadata.sequence = newest;
message.metadata.source_timestamp = core::TimePoint(core::Nanoseconds(timestamp));
return message;
}
return std::nullopt;
}

} // namespace

core::Result<SegmentInspection> InspectSegment(const std::string& name)
{
auto region = SharedRegion::OpenReadOnly(name);
if (!region.ok()) {
return core::Result<SegmentInspection>::FromStatus(region.status());
}
return core::Result<SegmentInspection>(Inspect(*region.value()));
}

core::Result<NewestMessage> ReadNewestInSegment(const std::string& name)
{
auto region = SharedRegion::OpenReadOnly(name);
if (!region.ok()) {
return core::Result<NewestMessage>::FromStatus(region.status());
}
NewestMessage newest;
newest.inspection = Inspect(*region.value());
if (newest.inspection.state == SegmentInspection::State::kValid) {
newest.message = ReadNewest(*region.value(), newest.inspection);
}
return core::Result<NewestMessage>(std::move(newest));
}

} // namespace puppet_master::transport::shm::detail
Loading
Loading