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
19 changes: 19 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -43,3 +43,22 @@ jobs:
TOKEN: ${{ secrets.OTFABRIC_READ_TOKEN }}
run: git config --global url."https://x-access-token:${TOKEN}@github.com/".insteadOf "https://github.com/"
- run: make coverage-pkg-check

# The bundled codec examples are generated (AGENTS.md hard rule 6): regenerate them and
# fail on any difference from the committed files (TEST-011).
generated:
name: Generated codec examples
runs-on: ubuntu-latest
env:
GOPRIVATE: github.com/otfabric/*
steps:
- uses: actions/checkout@v7
- uses: actions/setup-go@v7
with:
go-version-file: go.mod
- name: Configure private module access
shell: bash
env:
TOKEN: ${{ secrets.OTFABRIC_READ_TOKEN }}
run: git config --global url."https://x-access-token:${TOKEN}@github.com/".insteadOf "https://github.com/"
- run: make generate-check
10 changes: 6 additions & 4 deletions ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,20 +28,22 @@ main.go
| `internal/simulator/control.go` | The optional HTTP control API: `/reset`, `/reload`, `/healthz` |
| `internal/simulator/server.go` | `Run`: wires the above and blocks until the context is cancelled |
| `schemas` | The fixture and trace JSON Schemas, embedded |
| `internal/leakcheck` | Test-only goroutine leak check (`TESTING.md`) |

## Request flow

`Run` validates the fixture, builds the `Store`, opens the trace file if one was asked for, and starts a go-modbus server with a `Handler`. All devices share one listener and are routed by Unit ID.

For each request, `Handler.serve` first evaluates configured exception and fault rules, then takes `commitMu` and, in one step, applies the state operation, assigns `seq` and writes the trace record. The rule evaluation order is specified in `REQUIREMENTS.md`, Rule evaluation order.
For each request, `Handler.serve` first evaluates configured exception and fault rules, then takes `commitMu` and, in one step, applies the state operation, assigns `seq` and writes the trace record. When a reload replaced the store in between (the store counts its generations), the unit, broadcast and exception checks are made again against the new fixture under `commitMu`; a `timeout` or `connectionClose` fault that already acted is kept, and a `delay` is not waited again. The rule evaluation order is specified in `REQUIREMENTS.md`, Rule evaluation order.

## Concurrency and ownership

- go-modbus runs the client connections and calls the handler concurrently.
- `Handler.commitMu` makes a state operation, its `seq` and its trace record one step, so the trace lists requests in the order in which they took effect. `ResetState` and `ReplaceStore` take the same lock.
- `Store.mu` guards the device state. `JSONLWriter.mu` guards the trace; every record is flushed as it is written, and the first write error is sticky and reported by `Close`.
- The control API runs in one goroutine started by `Run` and is closed when `Run` returns. `control.mu` allows one control request at a time. It has no authentication: bind it to a loopback address.
- `cmd` cancels the context on SIGINT or SIGTERM. `Run` then stops the server and closes the trace.
- `Store.mu` guards the device state. `JSONLWriter.mu` guards the trace; every record is flushed as it is written, and the first write error is sticky and reported by `Close`. The handler reports that first error once while it runs (a warning line, `/healthz`).
- The control API runs in one goroutine started by `Run`; `Run` shuts it down and waits for that goroutine before it returns. `control.mu` allows one control request at a time. It has no authentication and refuses requests with an `Origin` header: bind it to a loopback address.
- `cmd` cancels the context on SIGINT or SIGTERM and then restores the default handling, so a second signal ends the process. `Run` shuts down the control API, then the Modbus server, waiting at most 10 s in all for the requests in progress, and then closes the trace. When the time runs out it returns an error and leaves the trace file to the requests still running.
- `internal/leakcheck` is test-only: the goroutine leak check of the `internal/simulator` and `cmd` tests.

## Extending it

Expand Down
23 changes: 16 additions & 7 deletions Makefile
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# Ignore any go.work in a parent directory.
export GOWORK := off

.PHONY: help all run test soak fuzz coverage cover compile lint lint-ci fmt fmt-check vuln vet build build-nocheck build-all release-all install clean check generate-codec-examples coverage-pkg-check
.PHONY: help all run test soak fuzz coverage cover compile lint lint-ci fmt fmt-check vuln vet build build-nocheck build-all release-all install clean check generate-codec-examples generate-check coverage-pkg-check

help: ## This help
@awk 'BEGIN {FS = ":.*?## "} /^[a-zA-Z0-9_-]+:.*?## / {printf "\033[36m%-30s\033[0m %s\n", $$1, $$2}' $(MAKEFILE_LIST)
Expand Down Expand Up @@ -45,11 +45,16 @@ soak: ## Loop the chaos and stress tests under the race detector for SOAKTIME ea
@echo "Soaking chaos and stress tests (SOAKTIME=$(SOAKTIME))"
@MODBUS_SIMULATOR_SOAK=$(SOAKTIME) go test -count=1 -race -timeout=0 -run 'TestChaos_|TestStress_' ./internal/simulator/

fuzz: ## Run every fuzz target for FUZZTIME (default 30s)
@for target in FuzzValidateFixture FuzzExpectation FuzzHandlerRequests; do \
echo "Fuzzing $$target (FUZZTIME=$(FUZZTIME))"; \
go test -run '^$$' -fuzz "^$$target\$$" -fuzztime $(FUZZTIME) ./internal/simulator/ || exit 1; \
done
fuzz: ## Run every fuzz target (found with go test -list) for FUZZTIME (default 30s)
@n=0; for pkg in $$(go list ./...); do \
for target in $$(go test -list '^Fuzz' $$pkg | grep '^Fuzz'); do \
echo "Fuzzing $$pkg $$target (FUZZTIME=$(FUZZTIME))"; \
go test -run '^$$' -fuzz "^$$target\$$" -fuzztime $(FUZZTIME) $$pkg || exit 1; \
n=$$((n+1)); \
done; \
done; \
if [ $$n -eq 0 ]; then echo "no fuzz targets found"; exit 1; fi; \
echo "$$n fuzz target(s) run"

# tools/ is a generator run by hand, not part of the binary (TESTING.md).
COVER_PKGS := $(shell go list ./... | grep -v '/tools')
Expand Down Expand Up @@ -160,4 +165,8 @@ clean: ## Clean the build artifacts

generate-codec-examples: ## Regenerate bundled codec example fixtures
@echo "Generating codec example fixtures"
@go run ./tools/generate-codec-examples
@go run ./tools/generate-codec-examples

generate-check: generate-codec-examples ## Fail when the bundled codec examples differ from what the generator writes
@git diff --exit-code -- examples/ || { echo "examples/ is out of date: run make generate-codec-examples and commit the result"; exit 1; }
@test -z "$$(git status --porcelain -- examples/)" || { git status --porcelain -- examples/; echo "examples/ has files that are not committed"; exit 1; }
14 changes: 9 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,9 @@ modbus-simulator validate device.json --format json

### `run`

Start the stateful Modbus TCP simulator from a fixture. Runs until interrupted (SIGINT/SIGTERM).
Start the stateful Modbus TCP simulator from a fixture. Runs until interrupted (SIGINT/SIGTERM). It then waits at most 10 s for the requests in progress and exits with code `4` when they have not finished; a second Ctrl+C ends it at once. A trace record that cannot be written is reported with one warning line on stderr, and `run` exits with code `4` at the end.

An environment variable that does not hold a valid value for its flag (for example `MODBUS_SIMULATOR_MAX_CLIENTS=1O` or `MODBUS_SIMULATOR_TRACE_RAW=yes`) is a usage error (exit `2`) naming the variable, unless the flag is also given on the command line.

#### Flags

Expand Down Expand Up @@ -306,6 +308,7 @@ Discover IDs with `modbus-simulator codecs list`. Validation runs JSON Schema pl

- **FC22 (mask write)** sets the register to `(current AND andMask) OR (orMask AND NOT andMask)`.
- **FC23 (read/write multiple)** makes the write first, then the read, as one step. If either is not allowed, nothing is written.
- **FC43 (device identification)** answers an individual read of an object id that the fixture does not configure with `illegal_data_address`, and traces it so. Identity values are at most 244 bytes (UTF-8), the most one response can carry; `validate` refuses longer ones.

All devices in a fixture share one listener and are routed by unit ID (`1–247`). A request for a unit ID that is not in the fixture is answered with an `illegal_function` exception.

Expand All @@ -324,16 +327,16 @@ With `run --control <host:port>` a running simulator also takes commands over HT
|---------|--------|
| `POST /reset` | Restore every unit to the fixture values, for all clients |
| `POST /reset?unit=N` | Restore one unit (`404` when it is not in the fixture) |
| `POST /reload` | Read the fixture file again and serve it from then on. A fixture that is not valid is refused with `422` and the simulator carries on unchanged |
| `GET /healthz` | `200` while the simulator runs |
| `POST /reload` | Read the fixture file again and serve it from then on, also to a request that a delay rule of the old fixture is holding. A fixture that is not valid is refused with `422` and the simulator carries on unchanged |
| `GET /healthz` | `200` while the simulator runs; `503` with the error once a trace record could not be written |

```bash
modbus-simulator run --fixture device.json --control 127.0.0.1:5021 &
curl -X POST http://127.0.0.1:5021/reset
curl -X POST http://127.0.0.1:5021/reload
```

Replies are JSON (`{"ok":true}`, or `{"ok":false,"error":"…"}`). The control API has **no authentication**: bind it to a loopback address. Resets and reloads are not written to the trace; `seq` simply continues.
Replies are JSON (`{"ok":true}`, or `{"ok":false,"error":"…"}`). The control API has **no authentication**: bind it to a loopback address. It refuses any request with an `Origin` header (`403`), which browsers add to the requests of a web page; `curl` and test scripts do not send one. Resets and reloads are not written to the trace; `seq` simply continues.

## Fault injection

Expand Down Expand Up @@ -425,10 +428,11 @@ make help # list targets
make test # unit + race tests (includes example fixtures)
make check # fmt, lint, vet, test, coverage
make soak # loop the chaos and stress tests (SOAKTIME=2m)
make fuzz # run the fuzz targets (FUZZTIME=30s each)
make fuzz # run every fuzz target go test -list finds (FUZZTIME=30s each)
make build # build bin/modbus-simulator
make build-all # cross-compile release binaries
make generate-codec-examples # regenerate bundled codec fixtures
make generate-check # fail when examples/ differs from what the generator writes (CI)
```

Shell completion setup is documented under [`completion`](#completion).
Expand Down
33 changes: 33 additions & 0 deletions RELEASE.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,38 @@
# modbus-simulator Releases

## v1.6.0

**Date:** 2026-11-15
**Previous release:** v1.5.6

The trace and `/healthz` report what the simulator does, files and settings that cannot be served as written are refused, and `run` stops within a bound.

### Breaking

- **Identity values longer than 244 bytes are refused.** `validate` and `run` exit with code `3` for a fixture whose `vendorName`, `productCode`, `majorMinorRevision` or an `objects[].value` is longer than 244 bytes in UTF-8, the most one FC43 response can carry. Such a fixture was accepted before, but an FC43 read that reached the value was answered with a *Server Device Failure* exception on the wire, and traced as `ok: true`. Way back: shorten the value to at most 244 bytes.
- **FC43: an individual read of an object id that is not configured is traced as an exception.** The client received `illegal_data_address` before as now; the trace said `ok: true` and now says `ok: false`, `exceptionCode: "illegal_data_address"`. Way back: an expectation that matched such a read with `response: {"ok": true}` matches it with `response: {"ok": false, "exceptionCode": "illegal_data_address"}`.
- **A `float32` codec value beyond the float32 range is refused** (exit `3`), instead of being served as an infinity. Values that round to the largest float32, such as `3.4028235e38`, are accepted. Way back: to serve an infinity, use raw register points that hold its bits (+Inf is `0x7F800000`) in the word order the client expects.
- **An environment variable that does not parse is a usage error** (exit `2`) naming the variable: `MODBUS_SIMULATOR_MAX_CLIENTS` (a decimal that fits the platform's `uint`), `MODBUS_SIMULATOR_TRACE_RAW` and `MODBUS_SIMULATOR_TRACE_DECODED` (`true`, `false`, `1`, `0` and the other forms of Go's `strconv.ParseBool`). Such a value was replaced by the default without a word before: `MODBUS_SIMULATOR_MAX_CLIENTS=1O` meant no client limit. Way back: unset the variable or give it a valid value; a flag on the command line takes precedence over the variable, as before.
- **An expectation matcher may only name fields of the trace.** A key in `request`, `response` or `stateChange` that the trace record does not have is a validation error (exit `3`) of `assert-trace`. Such a key never matched before, so `notContains` and `count` with `equals: 0` or `atMost` passed whatever the trace held. Way back: correct the key to the field meant; an assertion that relied on never matching can be removed, with the result it had.
- **`GET /healthz` answers `503`** with `{"ok": false, "error": "trace file not written: …"}` once a trace record could not be written; `run` also prints one warning line to stderr. It answered `200` until `run` ended with exit `4`. Requests are still served. Way back: a script that only needs to know that the simulator is up can accept `503` as well as `200`.
- **The control API refuses requests with an `Origin` header** (`403`), on every path. Browsers send that header with the requests of a web page; `curl` and test scripts do not. Way back: a client outside a browser that sets `Origin` itself leaves the header out. A web page can no longer drive the control API.
- **`run` stops within 10 s.** After SIGINT or SIGTERM it waits at most 10 s for the control API and the requests in progress; when they have not finished (for example a trace write that does not return), `run` exits with code `4` and leaves the trace file unclosed, where it used to wait without end. A second signal ends the process at once; it was ignored before. Records already written are in the file: each one is flushed as it is written. Way back: send one signal and wait for `run` to end.
- **A request held across a reload is answered from the new fixture.** A request that a `delay` rule held while `POST /reload` replaced the fixture was answered with the old fixture's rules and the new fixture's state; its unit, broadcast and exception rules now come from the new fixture, and `matchedRule` names a rule of the new fixture or none (REQUIREMENTS.md, Control API: a reload takes effect between two requests). A `timeout` or `connectionClose` fault that already acted is kept. Way back: none; to keep a delayed request on the old fixture, let it finish before the reload.

### Changed

- The control API closes keep-alive connections that are idle for 30 s (they were kept for as long as the client wanted). HTTP clients open a new connection for the next request.
- SECURITY.md lists the resource limits: clients, frames, idle and TLS handshake timeouts, per-connection state, fault delays, the trace file, the control API, shutdown and the files read.

### Tests

- The shutdown test with requests in flight waits until every request is in progress, by the handler's count, and checks that each one has its trace record.
- A goroutine leak check that compares goroutines by id runs after the tests of `internal/simulator` and `cmd` and after the stress, chaos and lifecycle tests (`internal/leakcheck`).
- `make fuzz` runs every fuzz target that `go test -list` finds, and fails when it finds none.
- CI regenerates the bundled codec examples and fails when they differ from the committed files (`make generate-check`).

---

## v1.5.6

**Date:** 2026-11-15
Expand Down
Loading
Loading