You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@trafficserver.apache.org by dm...@apache.org on 2026/03/13 09:18:45 UTC
(trafficserver) branch 11-Dev updated: ATS Configuration Reload with observability/tracing - Token model (#12892)
This is an automated email from the ASF dual-hosted git repository.
dmeden pushed a commit to branch 11-Dev
in repository https://gitbox.apache.org/repos/asf/trafficserver.git
The following commit(s) were added to refs/heads/11-Dev by this push:
new 5bab268cb4 ATS Configuration Reload with observability/tracing - Token model (#12892)
5bab268cb4 is described below
commit 5bab268cb4c22e338d63a81f5da621a6b90776e6
Author: Damian Meden <dm...@apache.org>
AuthorDate: Fri Mar 13 10:18:39 2026 +0100
ATS Configuration Reload with observability/tracing - Token model (#12892)
ATS Configuration Reload with observability/tracing — Token model
Replace the fire-and-forget configuration reload mechanism with a new
token-based, observable reload framework. Every reload operation is now
assigned a unique token, tracked through a task tree, and queryable via
CLI or JSONRPC at any point after submission.
Core components introduced:
- ConfigRegistry: centralized singleton for config file registration,
filename records, trigger records, and reload handlers. Replaces the
scattered registration across AddConfigFilesHere.cc and individual
modules.
- ReloadCoordinator: manages reload session lifecycle including token
generation, concurrency control (--force to override), timeout
detection, and rolling history.
- ConfigReloadTask: tracks a single reload as a tree of sub-tasks with
per-handler status, timings, and logs.
- ConfigContext: lightweight context passed to handlers providing
in_progress(), complete(), fail(), log(), supplied_yaml(), and
add_dependent_ctx(). Safe no-op at startup when no reload is active.
- ConfigReloadProgress: periodic checker that detects stuck tasks and
marks them as TIMEOUT.
New traffic_ctl commands:
- config reload [-m] [-t <token>] [-d @file] [--force]
- config status [-t <token>] [-c all]
All commands support --format json for automation and CI pipelines.
New JSONRPC APIs:
- admin_config_reload: unified file-based or inline reload with token,
force, and configs parameters.
- get_reload_config_status: query reload status by token or get the
last N reloads.
Migrated config handlers to ConfigRegistry: ip_allow, cache_control,
cache_hosting, parent_proxy, split_dns, remap, logging,
ssl_client_coordinator (with sni.yaml and ssl_multicert.config as
dependencies), ssl_ticket_key, records, and pre-warm. Static configs
(storage, volume, plugin, socks, jsonrpc) registered as inventory-only.
Removed legacy ConfigUpdateHandler/ConfigUpdateContinuation from
ConfigProcessor.h. Removed AddConfigFilesHere.cc in favor of
per-module self-registration.
Fixed duplicate handler execution for configs with multiple trigger
records (e.g. ssl_client_coordinator) by deduplicating against the
ConfigReloadTask subtask tree.
Added RecFlushConfigUpdateCbs() to synchronously fire pending record
callbacks after rereadConfig(), ensuring all subtasks are registered
before the first status poll.
New configuration records:
- proxy.config.admin.reload.timeout (default: 1h)
- proxy.config.admin.reload.check_interval (default: 2s)
Backward compatible: existing `traffic_ctl config reload` works as
before; internally it now uses the new framework with automatic token
assignment and tracking.
---
doc/appendices/command-line/traffic_ctl.en.rst | 397 ++++++++++-
doc/developer-guide/config-reload-framework.en.rst | 722 +++++++++++++++++++++
doc/developer-guide/index.en.rst | 1 +
doc/developer-guide/jsonrpc/jsonrpc-api.en.rst | 304 ++++++++-
include/iocore/dns/SplitDNSProcessor.h | 7 +-
include/iocore/eventsystem/ConfigProcessor.h | 46 --
include/iocore/net/QUICMultiCertConfigLoader.h | 2 +-
include/iocore/net/SSLSNIConfig.h | 2 +-
include/iocore/net/quic/QUICConfig.h | 2 +-
include/mgmt/config/ConfigContext.h | 195 ++++++
include/mgmt/config/ConfigRegistry.h | 344 ++++++++++
include/mgmt/config/ConfigReloadErrors.h | 53 ++
.../mgmt/config/ConfigReloadExecutor.h | 28 +-
include/mgmt/config/ConfigReloadTrace.h | 367 +++++++++++
include/mgmt/config/FileManager.h | 10 +-
include/mgmt/config/ReloadCoordinator.h | 124 ++++
include/mgmt/rpc/handlers/config/Configuration.h | 33 +
include/proxy/CacheControl.h | 3 +-
include/proxy/IPAllow.h | 4 +-
include/proxy/ParentSelection.h | 2 +-
include/proxy/ReverseProxy.h | 3 +-
include/proxy/http/PreWarmConfig.h | 7 +-
include/proxy/logging/LogConfig.h | 6 +-
include/records/RecCore.h | 11 +-
include/records/YAMLConfigReloadTaskEncoder.h | 69 ++
include/shared/rpc/yaml_codecs.h | 5 +-
include/tscore/ArgParser.h | 2 +
src/cripts/CMakeLists.txt | 2 +-
src/iocore/aio/CMakeLists.txt | 2 +-
src/iocore/cache/Cache.cc | 21 +-
src/iocore/cache/CacheHosting.cc | 9 -
src/iocore/cache/P_CacheHosting.h | 38 +-
src/iocore/dns/SplitDNS.cc | 21 +-
src/iocore/eventsystem/CMakeLists.txt | 4 +-
src/iocore/eventsystem/RecProcess.cc | 3 +-
src/iocore/hostdb/CMakeLists.txt | 6 +-
src/iocore/net/P_SSLClientCoordinator.h | 8 +-
src/iocore/net/P_SSLConfig.h | 6 +-
src/iocore/net/QUICMultiCertConfigLoader.cc | 4 +-
src/iocore/net/SSLClientCoordinator.cc | 52 +-
src/iocore/net/SSLConfig.cc | 25 +-
src/iocore/net/SSLSNIConfig.cc | 5 +-
src/iocore/net/quic/QUICConfig.cc | 3 +-
src/mgmt/config/AddConfigFilesHere.cc | 81 ---
src/mgmt/config/CMakeLists.txt | 6 +-
src/mgmt/config/ConfigContext.cc | 159 +++++
src/mgmt/config/ConfigRegistry.cc | 492 ++++++++++++++
src/mgmt/config/ConfigReloadExecutor.cc | 102 +++
src/mgmt/config/ConfigReloadTrace.cc | 397 +++++++++++
src/mgmt/config/FileManager.cc | 42 +-
src/mgmt/config/ReloadCoordinator.cc | 270 ++++++++
src/mgmt/rpc/CMakeLists.txt | 4 +-
src/mgmt/rpc/handlers/config/Configuration.cc | 209 +++++-
src/proxy/CMakeLists.txt | 4 +-
src/proxy/CacheControl.cc | 39 +-
src/proxy/IPAllow.cc | 48 +-
src/proxy/ParentSelection.cc | 28 +-
src/proxy/ReverseProxy.cc | 72 +-
src/proxy/hdrs/CMakeLists.txt | 9 +-
src/proxy/http/PreWarmConfig.cc | 12 +-
src/proxy/http/remap/unit-tests/CMakeLists.txt | 24 +-
src/proxy/http2/CMakeLists.txt | 4 +-
src/proxy/logging/LogConfig.cc | 26 +-
src/records/CMakeLists.txt | 10 +-
src/records/P_RecCore.cc | 6 +
src/records/RecCore.cc | 12 +-
src/records/RecordsConfig.cc | 6 +
src/records/unit_tests/test_ConfigRegistry.cc | 207 ++++++
src/records/unit_tests/test_ConfigReloadTask.cc | 148 +++++
src/traffic_ctl/CtrlCommands.cc | 369 ++++++++++-
src/traffic_ctl/CtrlCommands.h | 9 +
src/traffic_ctl/CtrlPrinters.cc | 285 +++++++-
src/traffic_ctl/CtrlPrinters.h | 47 +-
src/traffic_ctl/TrafficCtlStatus.h | 1 +
src/traffic_ctl/jsonrpc/CtrlRPCRequests.h | 56 +-
src/traffic_ctl/jsonrpc/ctrl_yaml_codecs.h | 101 +++
src/traffic_ctl/traffic_ctl.cc | 60 +-
src/traffic_logstats/CMakeLists.txt | 2 +-
src/traffic_server/CMakeLists.txt | 2 +-
src/traffic_server/RpcAdminPubHandlers.cc | 3 +
src/traffic_server/traffic_server.cc | 65 +-
src/tscore/ArgParser.cc | 14 +-
src/tscore/unit_tests/test_ArgParser.cc | 69 ++
tests/gold_tests/cache/cache_config_reload.test.py | 72 ++
tests/gold_tests/dns/splitdns_reload.test.py | 90 +++
.../ip_allow/ip_allow_reload_triggered.test.py | 256 ++++++++
tests/gold_tests/ip_allow/ip_category.test.py | 2 +-
.../gold_tests/jsonrpc/config_reload_dedup.test.py | 160 +++++
.../jsonrpc/config_reload_failures.test.py | 429 ++++++++++++
.../jsonrpc/config_reload_full_smoke.test.py | 165 +++++
.../jsonrpc/config_reload_reserve_subtask.test.py | 134 ++++
tests/gold_tests/jsonrpc/config_reload_rpc.test.py | 397 +++++++++++
.../jsonrpc/config_reload_tracking.test.py | 304 +++++++++
....json => admin_detached_config_reload_req.json} | 0
.../gold_tests/jsonrpc/jsonrpc_api_schema.test.py | 9 +-
.../parent_config/parent_config_reload.test.py | 86 +++
tests/gold_tests/remap/remap_reload.test.py | 4 +-
.../gold_tests/tls/tls_client_cert_plugin.test.py | 2 +-
.../traffic_ctl/traffic_ctl_config_reload.test.py | 192 ++++++
.../traffic_ctl/traffic_ctl_test_utils.py | 137 +++-
100 files changed, 8411 insertions(+), 486 deletions(-)
diff --git a/doc/appendices/command-line/traffic_ctl.en.rst b/doc/appendices/command-line/traffic_ctl.en.rst
index d8eea55221..d6f933188f 100644
--- a/doc/appendices/command-line/traffic_ctl.en.rst
+++ b/doc/appendices/command-line/traffic_ctl.en.rst
@@ -211,8 +211,274 @@ Display the current value of a configuration record.
configuration after any configuration file modification. If no configuration files have been
modified since the previous configuration load, this command is a no-op.
+ The reload is **asynchronous**: the command sends a JSONRPC request to |TS| and returns
+ immediately — it does not block until every config handler finishes. The actual reload work
+ runs on background threads (``ET_TASK``), where each registered config handler loads its
+ configuration and reports success or failure.
+
+ Every reload is assigned a **token** — a unique identifier for the reload operation. The token
+ is the handle you use to track, monitor, or query the reload after it starts. If no token is
+ provided via ``--token``, the server generates one automatically using a timestamp (e.g.
+ ``rldtk-1739808000000``). You can supply a custom token via ``--token`` (e.g.
+ ``-t deploy-v2.1``) to tag reloads with meaningful labels for CI pipelines, deploy scripts, or
+ post-mortem analysis.
+
+ Use the token to:
+
+ - **Monitor** a reload in real-time: ``traffic_ctl config reload -t <token> -m``
+ - **Query** the final status: ``traffic_ctl config status -t <token>``
+ - **Get detailed logs**: ``traffic_ctl config status -t <token> -l``
+
The timestamp of the last reconfiguration event (in seconds since epoch) is published in the
- `proxy.process.proxy.reconfigure_time` metric.
+ ``proxy.process.proxy.reconfigure_time`` metric.
+
+ **Behavior without options:**
+
+ When called without ``--monitor`` or ``--show-details``, the command sends the reload request
+ and immediately prints the assigned token along with suggested next-step commands:
+
+ .. code-block:: bash
+
+ $ traffic_ctl config reload
+ ✔ Reload scheduled [rldtk-1739808000000]
+
+ Monitor : traffic_ctl config reload -t rldtk-1739808000000 -m
+ Details : traffic_ctl config reload -t rldtk-1739808000000 -s -l
+
+ **When a reload is already in progress:**
+
+ Only one reload can be active at a time. If a reload is already running, the command does
+ **not** start a new one. Instead, it reports the in-progress reload's token and provides
+ options to monitor it or force a new one:
+
+ .. code-block:: bash
+
+ $ traffic_ctl config reload
+ ⟳ Reload in progress [rldtk-1739808000000]
+
+ Monitor : traffic_ctl config reload -t rldtk-1739808000000 -m
+ Details : traffic_ctl config status -t rldtk-1739808000000
+ Force : traffic_ctl config reload --force (may conflict with the running reload)
+
+ With ``--monitor``, it automatically switches to monitoring the in-progress reload instead of
+ failing. With ``--show-details``, it displays the current status of the in-progress reload.
+
+ **When a token already exists:**
+
+ If the token provided via ``--token`` was already used by a previous reload (even a completed
+ one), the command refuses to start a new reload to prevent ambiguity. Choose a different token
+ or omit ``--token`` to let the server generate a unique one:
+
+ .. code-block:: bash
+
+ $ traffic_ctl config reload -t my-deploy
+ ✗ Token 'my-deploy' already in use
+
+ Status : traffic_ctl config status -t my-deploy
+ Retry : traffic_ctl config reload
+
+ Supports the following options:
+
+ .. option:: --token, -t <token>
+
+ Assign a custom token to this reload. Tokens must be unique across the reload history — if
+ a reload (active or completed) already has this token, the command is rejected. When omitted,
+ the server generates a unique token automatically.
+
+ Custom tokens are useful for tagging reloads with deployment identifiers, ticket numbers,
+ or other meaningful labels that make it easier to query status later.
+
+ .. code-block:: bash
+
+ $ traffic_ctl config reload -t deploy-v2.1
+ ✔ Reload scheduled [deploy-v2.1]
+
+ .. option:: --monitor, -m
+
+ Start the reload and monitor its progress with a live progress bar until completion. The
+ progress bar updates in real-time showing the number of completed handlers, overall status,
+ and elapsed time.
+
+ Polls the server at regular intervals controlled by ``--refresh-int`` (default: every 0.5
+ seconds). Before the first poll, waits briefly (see ``--initial-wait``) to allow the server
+ time to dispatch work to all handlers.
+
+ If a reload is already in progress, ``--monitor`` automatically attaches to that reload and
+ monitors it instead of failing.
+
+ If both ``--monitor`` and ``--show-details`` are specified, ``--monitor`` is ignored and
+ ``--show-details`` takes precedence.
+
+ .. code-block:: bash
+
+ $ traffic_ctl config reload -t deploy-v2.1 -m
+ ✔ Reload scheduled [deploy-v2.1]
+ ✔ [deploy-v2.1] ████████████████████ 11/11 success (245ms)
+
+ Failed reload:
+
+ .. code-block:: bash
+
+ $ traffic_ctl config reload -t hotfix-cert -m
+ ✔ Reload scheduled [hotfix-cert]
+ ✗ [hotfix-cert] ██████████████░░░░░░ 9/11 fail (310ms)
+
+ Details : traffic_ctl config status -t hotfix-cert
+
+ .. note::
+
+ During a reload, all subtasks are pre-registered shortly after file processing
+ completes. However, the first file (typically ``records.yaml``) may briefly show as
+ ``1/1 success`` before record-triggered handlers are reserved by the flush. The
+ ``--initial-wait`` option (default: 2s) delays the first poll to reduce the chance
+ of observing this transient state.
+
+ .. option:: --show-details, -s
+
+ Start the reload and display a detailed status report. The command sends the reload request,
+ waits for the configured initial wait (see ``--initial-wait``, default: 2 seconds) to allow
+ handlers to start, then fetches and prints the full task tree with per-handler status and
+ durations.
+
+ If a reload is already in progress, shows the status of that reload immediately.
+
+ Combine with ``--include-logs`` to also show per-handler log messages.
+
+ .. code-block:: bash
+
+ $ traffic_ctl config reload -s -l
+ ✔ Reload scheduled [rldtk-1739808000000]. Waiting for details...
+
+ ✔ Reload [success] — rldtk-1739808000000
+ Started : 2025 Feb 17 12:00:00.123
+ Duration: 245ms
+
+ Tasks:
+ ✔ ip_allow.yaml ·························· 18ms
+ ✔ logging.yaml ··························· 120ms
+ ...
+
+ .. option:: --include-logs, -l
+
+ Include per-handler log messages in the output. Only meaningful together with
+ ``--show-details``. Log messages are set by handlers via ``ctx.log()`` and
+ ``ctx.fail()`` during the reload.
+
+ .. option:: --data, -d <source>
+
+ Supply inline YAML configuration content for the reload. The content is passed directly to
+ config handlers at runtime and is **not persisted to disk** — a server restart will revert
+ to the file-based configuration. A warning is printed after a successful inline reload to
+ remind the operator.
+
+ Accepts the following formats:
+
+ - ``@file.yaml`` — read content from a file
+ - ``@-`` — read content from stdin
+ - ``"yaml: content"`` — inline YAML string
+ - Multiple ``-d`` arguments can be provided — their content is merged, with later values
+ overriding earlier ones for the same key
+
+ The YAML content uses **registry keys** (e.g. ``ip_allow``, ``sni``) as top-level keys.
+ Each key maps to the full configuration content that the handler normally reads from its
+ config file. A single file can target multiple handlers:
+
+ .. code-block:: yaml
+
+ # reload_rules.yaml
+ # Each top-level key is a registry key.
+ # The value is the config content (inner data, not the file's top-level wrapper).
+ ip_allow:
+ - apply: in
+ ip_addrs: 0.0.0.0/0
+ action: allow
+ sni:
+ - fqdn: "*.example.com"
+ verify_client: NONE
+
+ .. code-block:: bash
+
+ # Reload from file
+ $ traffic_ctl config reload -d @reload_rules.yaml -t update-rules -m
+
+ # Reload from stdin
+ $ cat rules.yaml | traffic_ctl config reload -d @- -m
+
+ When used with ``-d``, only the handlers for the keys present in the YAML content are
+ invoked — other config handlers are not triggered.
+
+ .. note::
+
+ Inline YAML reload requires the target config handler to support
+ ``ConfigSource::FileAndRpc``. Handlers that only support ``ConfigSource::FileOnly``
+ will return an error for the corresponding key. The JSONRPC response will contain
+ per-key error details.
+
+ .. option:: --force, -F
+
+ Force a new reload even if one is already in progress. Without this flag, the server rejects
+ a new reload when one is active.
+
+ .. warning::
+
+ ``--force`` does **not** stop or cancel the running reload. It starts a second reload
+ alongside the first one. Handlers from both reloads may execute concurrently on separate
+ ``ET_TASK`` threads. This can lead to unpredictable behavior if handlers are not designed
+ for concurrent execution. Use this flag only for debugging or recovery situations.
+
+ .. option:: --refresh-int, -r <seconds>
+
+ Set the polling interval in seconds used with ``--monitor``. Accepts fractional values
+ (e.g. ``0.5`` for 500ms). Controls how often ``traffic_ctl`` queries the server for
+ updated reload status. Default: ``0.5``.
+
+ .. option:: --initial-wait, -w <seconds>
+
+ Initial wait in seconds before the first status poll. After scheduling a reload, the
+ server needs a brief moment to dispatch work to all handlers. This delay avoids polling
+ before any handler has started, which would show an empty or incomplete task tree.
+ Accepts fractional values (e.g. ``1.5``). Default: ``2``.
+
+ .. option:: --timeout, -T <duration>
+
+ Maximum time to wait for reload completion when using ``--monitor``. Accepts duration
+ strings (e.g. ``30s``, ``1m``, ``500ms``). If the reload does not reach a terminal state
+ within the specified duration, ``traffic_ctl`` stops monitoring and exits with
+ ``EX_TEMPFAIL`` (75). The reload itself continues on the server — use
+ ``traffic_ctl config status -t <token>`` to check its final status later.
+ Default: ``0`` (no timeout — wait indefinitely until the reload completes or is
+ interrupted). Requires ``--monitor``.
+
+ **Exit codes for config reload:**
+
+ The ``config reload`` command sets the process exit code to reflect the outcome of the
+ reload operation:
+
+ ``0``
+ Success. The reload was scheduled (without ``--monitor``) or completed successfully
+ (with ``--monitor``).
+
+ ``2``
+ Error. The reload reached a terminal failure state (``fail`` or ``timeout``), or an
+ RPC communication error occurred.
+
+ ``75``
+ Temporary failure (``EX_TEMPFAIL`` from ``sysexits.h``). A reload is already in
+ progress and the command could not start a new one, monitoring was interrupted
+ (e.g. Ctrl+C) before the reload reached a terminal state, or the ``--timeout``
+ duration was exceeded. The caller is invited to retry or monitor the operation later.
+
+ Example usage in scripts:
+
+ .. code-block:: bash
+
+ traffic_ctl config reload -m
+ rc=$?
+ case $rc in
+ 0) echo "Reload completed successfully" ;;
+ 2) echo "Reload failed" ;;
+ 75) echo "Reload still in progress, retry later" ;;
+ esac
.. program:: traffic_ctl config
.. option:: set RECORD VALUE
@@ -351,11 +617,112 @@ Display the current value of a configuration record.
.. program:: traffic_ctl config
.. option:: status
- :ref:`admin_lookup_records`
+ :ref:`get_reload_config_status`
+
+ Display the status of configuration reloads. This is a read-only command — it does not trigger
+ a reload, it only queries the server for information about past or in-progress reloads.
+
+ **Behavior without options:**
+
+ When called without ``--token`` or ``--count``, shows the most recent reload:
+
+ .. code-block:: bash
+
+ $ traffic_ctl config status
+ ✔ Reload [success] — rldtk-1739808000000
+ Started : 2025 Feb 17 12:00:00.123
+ Finished: 2025 Feb 17 12:00:00.368
+ Duration: 245ms
- Display detailed status about the Traffic Server configuration system. This includes version
- information, whether the internal configuration store is current and whether any daemon processes
- should be restarted.
+ ✔ 11 success ◌ 0 in-progress ✗ 0 failed (11 total)
+
+ Tasks:
+ ✔ logging.yaml ··························· 120ms
+ ✔ ip_allow.yaml ·························· 18ms
+ ...
+
+ **When no reloads have occurred:**
+
+ If the server has not performed any reloads since startup, the command reports that no reload
+ tasks were found.
+
+ **Querying a specific reload:**
+
+ Use ``--token`` to look up a specific reload by its token. If the token does not exist in
+ the history, an error is returned:
+
+ .. code-block:: bash
+
+ $ traffic_ctl config status -t nonexistent
+ ✗ Token 'nonexistent' not found
+
+ **Failed reload report:**
+
+ When a reload has failed handlers, the output shows which handlers succeeded and which failed,
+ along with durations for each:
+
+ .. code-block:: bash
+
+ $ traffic_ctl config status -t hotfix-cert
+ ✗ Reload [fail] — hotfix-cert
+ Started : 2025 Feb 17 14:30:10.500
+ Finished: 2025 Feb 17 14:30:10.810
+ Duration: 310ms
+
+ ✔ 9 success ◌ 0 in-progress ✗ 2 failed (11 total)
+
+ Tasks:
+ ✔ ip_allow.yaml ·························· 18ms
+ ✗ logging.yaml ·························· 120ms ✗ FAIL
+ ✗ ssl_client_coordinator ················· 85ms ✗ FAIL
+ ├─ ✔ sni.yaml ··························· 20ms
+ └─ ✗ ssl_multicert.config ··············· 65ms ✗ FAIL
+ ...
+
+ Supports the following options:
+
+ .. option:: --token, -t <token>
+
+ Show the status of a specific reload identified by its token. The token was either assigned
+ by the server (e.g. ``rldtk-<timestamp>``) or provided by the operator via
+ ``traffic_ctl config reload --token``.
+
+ Returns an error if the token is not found in the reload history.
+
+ .. option:: --count, -c <N|all>
+
+ Show the last ``N`` reload records from the history. Use ``all`` to display every reload
+ the server has recorded (up to the internal history limit).
+
+ When ``--count`` is provided, ``--token`` is ignored.
+
+ .. code-block:: bash
+
+ # Show full history
+ $ traffic_ctl config status -c all
+
+ # Show last 5 reloads
+ $ traffic_ctl config status -c 5
+
+ **JSON output:**
+
+ All ``config status`` commands support the global ``--format json`` option to output the raw
+ JSONRPC response as JSON instead of the human-readable format. This is useful for automation,
+ CI pipelines, monitoring tools, or any system that consumes structured output directly:
+
+ .. code-block:: bash
+
+ $ traffic_ctl config status -t deploy-v2.1 --format json
+ {
+ "tasks": [
+ {
+ "config_token": "deploy-v2.1",
+ "status": "success",
+ "description": "Main reload task - 2025 Feb 17 12:00:00",
+ "sub_tasks": [ ...]
+ }
+ ]
+ }
.. program:: traffic_ctl config
.. option:: registry
@@ -926,6 +1293,26 @@ Runroot needs to be configured in order to let `traffic_ctl` know where to find
and there is no change you have to do to interact with it, but make sure that you are not overriding the `dump_runroot=False`
when creating the ATS Process, otherwise the `runroot.yaml` will not be set.
+Exit Codes
+==========
+
+:program:`traffic_ctl` uses the following exit codes:
+
+``0``
+ Success. The requested operation completed successfully.
+
+``2``
+ Error. The operation failed. This may be returned when:
+
+ - The RPC communication with :program:`traffic_server` failed (e.g. socket not found or connection refused).
+ - The server response contains an error (e.g. invalid record name, malformed request).
+
+``3``
+ Unimplemented. The requested command is not yet implemented.
+
+``75``
+ Temporary failure (aligned with ``EX_TEMPFAIL`` from ``sysexits.h``). The caller is invited to retry later.
+
See also
========
diff --git a/doc/developer-guide/config-reload-framework.en.rst b/doc/developer-guide/config-reload-framework.en.rst
new file mode 100644
index 0000000000..53755c7b6a
--- /dev/null
+++ b/doc/developer-guide/config-reload-framework.en.rst
@@ -0,0 +1,722 @@
+.. Licensed to the Apache Software Foundation (ASF) under one
+ or more contributor license agreements. See the NOTICE file
+ distributed with this work for additional information
+ regarding copyright ownership. The ASF licenses this file
+ to you under the Apache License, Version 2.0 (the
+ "License"); you may not use this file except in compliance
+ with the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing,
+ software distributed under the License is distributed on an
+ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ KIND, either express or implied. See the License for the
+ specific language governing permissions and limitations
+ under the License.
+
+.. include:: ../common.defs
+
+.. _config-reload-framework:
+
+Configuration Reload Framework
+******************************
+
+This guide explains how to integrate a configuration module with the |TS| reload framework.
+It covers registering handlers, reporting progress through ``ConfigContext``, and the rules
+every handler must follow.
+
+Overview
+========
+
+When a reload is requested (via :program:`traffic_ctl config reload` or the
+:ref:`admin_config_reload` JSONRPC API), the server does not block the caller. Instead, it:
+
+1. **Assigns a token** to the reload — either auto-generated (e.g. ``rldtk-<timestamp>``) or
+ user-supplied via ``-t``.
+2. **Schedules the reload** on background threads (``ET_TASK``). Each registered config handler
+ runs, reports its status (``in_progress`` → ``success`` or ``fail``), and results are
+ aggregated into a task tree.
+3. **Returns the token** immediately so the caller can track progress via
+ :option:`traffic_ctl config status` or :ref:`get_reload_config_status`.
+
+The **token** is the unique identifier for a reload operation — it is the handle used to monitor
+progress, query final status, and retrieve per-handler logs.
+
+``ConfigRegistry`` is a centralized singleton that manages all configuration files, their reload
+handlers, trigger records, and file dependencies. It coordinates execution, tracks progress per
+handler, and records the result in a queryable history.
+
+Key capabilities:
+
+- **Traceability** — every reload gets a token. Each handler reports its status and the results
+ are aggregated into a task tree with per-handler timings and logs.
+- **Centralized registration** — one place for config files, filename records, trigger records, and
+ handlers.
+- **Inline YAML injection** — handlers that opt in can receive YAML content directly via the RPC,
+ without writing to disk.
+- **Coordinated reload sessions** — concurrency control, timeout detection, and history.
+
+
+Registration API
+================
+
+All registration calls are made during module startup, typically from a ``startup()`` method.
+
+register_config
+---------------
+
+Register a file-based configuration handler.
+
+.. code-block:: cpp
+
+ void ConfigRegistry::register_config(
+ const std::string &key, // unique registry key (e.g. "ip_allow")
+ const std::string &default_filename, // default filename (e.g. "ip_allow.yaml")
+ const std::string &filename_record, // record holding the filename, or "" if fixed
+ ConfigReloadHandler handler, // reload callback
+ ConfigSource source, // content source (FileOnly, FileAndRpc)
+ std::initializer_list<const char *> triggers = {}, // records that trigger reload (optional)
+ bool is_required = false // whether the file must exist on disk
+ );
+
+This is the primary registration method. It:
+
+1. Adds the entry to the registry.
+2. Registers the file with ``FileManager`` for mtime-based change detection.
+3. Wires ``RecRegisterConfigUpdateCb`` callbacks for each trigger record.
+
+**Example — ip_allow:**
+
+.. code-block:: cpp
+
+ config::ConfigRegistry::Get_Instance().register_config(
+ "ip_allow", // registry key
+ ts::filename::IP_ALLOW, // default filename
+ "proxy.config.cache.ip_allow.filename", // record holding the filename
+ [](ConfigContext ctx) { IpAllow::reconfigure(ctx); }, // handler
+ config::ConfigSource::FileOnly, // no inline content
+ {"proxy.config.cache.ip_allow.filename"}); // trigger records
+
+
+register_record_config
+----------------------
+
+Register a handler that has no config file — it only reacts to record changes.
+
+.. code-block:: cpp
+
+ void ConfigRegistry::register_record_config(
+ const std::string &key, // unique registry key
+ ConfigReloadHandler handler, // reload callback
+ std::initializer_list<const char *> triggers // records that trigger reload
+ );
+
+Use this for modules like ``SSLTicketKeyConfig`` that are reloaded via record changes and need
+visibility in the reload infrastructure, or for pure coordinator entries that own child file
+dependencies.
+
+**Example — ssl_client_coordinator (pure coordinator):**
+
+.. code-block:: cpp
+
+ config::ConfigRegistry::Get_Instance().register_record_config(
+ "ssl_client_coordinator",
+ [](ConfigContext ctx) { SSLClientCoordinator::reconfigure(ctx); },
+ {"proxy.config.ssl.client.cert.path",
+ "proxy.config.ssl.client.cert.filename",
+ "proxy.config.ssl.server.session_ticket.enable"});
+
+.. note::
+
+ When a config key has multiple trigger records, a change to **any** of them invokes the
+ handler **once** per reload cycle — not once per record. The framework deduplicates
+ internally: the first trigger creates a subtask for the config key; subsequent triggers
+ for the same key in the same cycle are skipped. Handlers do not need to guard against
+ duplicate invocations.
+
+
+register_static_file
+--------------------
+
+Register a non-reloadable config file for inventory purposes. Static files have no reload handler
+and no trigger records. This allows the registry to serve as the single source of truth for all
+known configuration files, so that RPC endpoints (e.g. ``filemanager.get_files_registry``) can
+expose this information.
+
+.. code-block:: cpp
+
+ void ConfigRegistry::register_static_file(
+ const std::string &key, // unique registry key (e.g. "storage")
+ const std::string &default_filename, // default filename (e.g. "storage.config")
+ const std::string &filename_record = {}, // record holding the filename (optional)
+ bool is_required = false // whether the file must exist on disk
+ );
+
+Internally this delegates to ``register_config()`` with a ``nullptr`` handler, no trigger records,
+and ``ConfigSource::FileOnly``. The file is registered with ``FileManager`` for mtime tracking
+but no reload callback is wired.
+
+**Example — startup-only files:**
+
+.. code-block:: cpp
+
+ auto ® = config::ConfigRegistry::Get_Instance();
+ reg.register_static_file("storage", ts::filename::STORAGE, {}, true);
+ reg.register_static_file("socks", ts::filename::SOCKS, "proxy.config.socks.socks_config_file");
+ reg.register_static_file("volume", ts::filename::VOLUME);
+ reg.register_static_file("plugin", ts::filename::PLUGIN);
+ reg.register_static_file("jsonrpc", ts::filename::JSONRPC, "proxy.config.jsonrpc.filename");
+
+
+attach
+------
+
+Add an additional trigger record to an existing config entry. Can be called from any module at
+any time after the entry has been registered.
+
+.. code-block:: cpp
+
+ int ConfigRegistry::attach(const std::string &key, const char *record_name);
+
+Returns ``0`` on success, ``-1`` if the key is not found.
+
+**Example:**
+
+.. code-block:: cpp
+
+ config::ConfigRegistry::Get_Instance().attach("ip_allow", "proxy.config.some.extra.record");
+
+
+add_file_dependency
+-------------------
+
+Register an auxiliary file that a config module depends on. When this file changes on disk,
+the parent config's handler is invoked.
+
+.. code-block:: cpp
+
+ int ConfigRegistry::add_file_dependency(
+ const std::string &key, // parent config key (must exist)
+ const char *filename_record, // record holding the filename
+ const char *default_filename, // default filename
+ bool is_required // whether the file must exist
+ );
+
+**Example — ip_categories as a dependency of ip_allow:**
+
+.. code-block:: cpp
+
+ config::ConfigRegistry::Get_Instance().add_file_dependency(
+ "ip_allow",
+ "proxy.config.cache.ip_categories.filename",
+ ts::filename::IP_CATEGORIES,
+ false);
+
+
+add_file_and_node_dependency
+----------------------------
+
+Like ``add_file_dependency()``, but also registers a **dependency key** so the RPC handler can
+route inline YAML content to the parent entry's handler.
+
+.. code-block:: cpp
+
+ int ConfigRegistry::add_file_and_node_dependency(
+ const std::string &key, // parent config key (must exist)
+ const std::string &dep_key, // unique dependency key for RPC routing
+ const char *filename_record, // record holding the filename
+ const char *default_filename, // default filename
+ bool is_required // whether the file must exist
+ );
+
+**Example — sni.yaml as a dependency of ssl_client_coordinator:**
+
+.. code-block:: cpp
+
+ config::ConfigRegistry::Get_Instance().add_file_and_node_dependency(
+ "ssl_client_coordinator", "sni",
+ "proxy.config.ssl.servername.filename",
+ ts::filename::SNI, false);
+
+
+ConfigContext API
+=================
+
+``ConfigContext`` is a lightweight value type passed to reload handlers. It provides methods to
+report progress and access inline YAML content.
+
+``ConfigContext`` is copyable (cheap — holds a ``weak_ptr`` and a ref-counted ``YAML::Node``).
+Move is intentionally suppressed: ``std::move(ctx)`` silently copies, keeping the original valid.
+
+in_progress(text)
+ Mark the task as in-progress. Accepts an optional message.
+
+log(text)
+ Append a log message to the task. These appear in
+ ``traffic_ctl config status -l`` output
+ and in :ref:`get_reload_config_status` JSONRPC responses.
+
+complete(text)
+ Mark the task as successfully completed.
+
+fail(reason) / fail(errata, summary)
+ Mark the task as failed. Accepts a plain string or a ``swoc::Errata`` with a summary.
+
+supplied_yaml()
+ Returns the YAML node supplied via the RPC ``-d`` flag or ``configs`` parameter. If no inline
+ content was provided, the returned node is undefined (``operator bool()`` returns ``false``).
+
+add_dependent_ctx(description)
+ Create a child sub-task. The parent aggregates status from all its children.
+
+All methods support ``swoc::bwprint`` format strings:
+
+.. code-block:: cpp
+
+ ctx.in_progress("Parsing {} rules", count);
+ ctx.fail(errata, "Failed to load {}", filename);
+
+
+.. _config-context-terminal-state:
+
+Terminal State Rule
+===================
+
+.. warning::
+
+ **Every** ``ConfigContext`` **must reach a terminal state** — either ``complete()`` or ``fail()``
+ — **before the handler returns.** This is the single most important rule of the framework.
+
+The entire tracing model depends on handlers reaching a terminal state. If a handler returns without
+calling ``complete()`` or ``fail()``:
+
+- The task stays **IN_PROGRESS** indefinitely.
+- The parent task (and the entire reload) cannot finish.
+- ``traffic_ctl config status`` will show the reload as stuck.
+- Eventually, the timeout checker will mark the task as **TIMEOUT**
+ (configurable via ``proxy.config.admin.reload.timeout``, default: 1 hour —
+ see :ref:`reload-framework-records` below).
+
+**Correct handler pattern:**
+
+.. code-block:: cpp
+
+ void MyConfig::reconfigure(ConfigContext ctx) {
+ ctx.in_progress("Loading myconfig");
+
+ auto [errata, config] = load_my_config();
+ if (!errata.is_ok()) {
+ ctx.fail(errata, "Failed to load myconfig");
+ return; // always return after fail
+ }
+
+ // ... apply config ...
+
+ ctx.complete("Loaded successfully");
+ }
+
+**Every code path must end in** ``complete()`` **or** ``fail()`` — including error paths, early
+returns, and exception handlers.
+
+**Child contexts follow the same rule.** If you call ``add_dependent_ctx()``, every child must
+also reach a terminal state:
+
+.. code-block:: cpp
+
+ void SSLClientCoordinator::reconfigure(ConfigContext ctx) {
+ ctx.in_progress();
+
+ SSLConfig::reconfigure(ctx.add_dependent_ctx("SSLConfig"));
+ SNIConfig::reconfigure(ctx.add_dependent_ctx("SNIConfig"));
+
+ ctx.complete("SSL configs reloaded");
+ }
+
+**Deferred handlers** — some handlers schedule work on other threads and return before completion.
+The ``ConfigContext`` they hold remains valid across threads. They must call ``ctx.complete()`` or
+``ctx.fail()`` from whatever thread finishes the work. If they don't, the timeout checker will mark
+the task as ``TIMEOUT``.
+
+.. note::
+
+ ``ctx.complete()`` and ``ctx.fail()`` are **thread-safe**. The underlying
+ ``ConfigReloadTask`` guards all state transitions with a ``std::shared_mutex``. Once a task
+ reaches a terminal state, subsequent calls are rejected (a warning is logged). This means
+ calling ``complete()`` or ``fail()`` from any thread — including a different ``ET_TASK``
+ thread or a callback — is safe.
+
+After ``ConfigRegistry::execute_reload()`` calls the handler, it checks whether the context reached
+a terminal state and emits a warning if not:
+
+.. code-block:: cpp
+
+ entry_copy.handler(ctx);
+ if (!ctx.is_terminal()) {
+ Warning("Config '%s' handler returned without reaching a terminal state. "
+ "If the handler deferred work to another thread, ensure ctx.complete() or "
+ "ctx.fail() is called when processing finishes.",
+ entry_copy.key.c_str());
+ }
+
+
+Parent Status Aggregation
+-------------------------
+
+Parent tasks derive their status from their children:
+
+- **Any child failed or timed out** → parent is ``FAIL``
+- **Any child still in progress** → parent stays ``IN_PROGRESS``
+- **All children succeeded** → parent is ``SUCCESS``
+
+This aggregation is recursive. A parent's ``complete()`` call sets its own status, but if any child
+later fails, the parent status will be downgraded accordingly.
+
+.. note::
+
+ During a file-based reload, subtasks are discovered in two phases: file-based handlers
+ complete synchronously inside ``rereadConfig()``, while record-triggered handlers are activated
+ by record callbacks. To ensure all subtasks are registered before the reload executor returns,
+ ``RecFlushConfigUpdateCbs()`` is called immediately after ``rereadConfig()``. This synchronously
+ fires all pending record callbacks, and each ``on_record_change()`` calls ``reserve_subtask()``
+ to pre-register a ``CREATED`` subtask on the main task. The total task count is therefore stable
+ from the first status poll.
+
+ As a safety net, ``add_sub_task()`` also calls ``aggregate_status()`` when the parent has
+ already reached ``SUCCESS``, reverting it to ``IN_PROGRESS``. This handles edge cases where a
+ subtask is registered after all previously known work has completed.
+
+
+ConfigSource
+============
+
+``ConfigSource`` declares what content sources a handler supports:
+
+``FileOnly``
+ The handler only reloads from its file on disk. This is the default for most configs.
+ Inline YAML via the RPC (:ref:`admin_config_reload`) is rejected.
+
+``RecordOnly``
+ The handler only reacts to record changes. It has no config file and no RPC content.
+ Used by ``register_record_config()`` implicitly.
+
+``FileAndRpc``
+ The handler can reload from file **or** from YAML content supplied via the RPC. The handler
+ checks ``ctx.supplied_yaml()`` to determine the source at runtime.
+
+
+ConfigType
+==========
+
+``ConfigType`` identifies the file format. It is **auto-detected** from the filename extension
+during registration:
+
+- ``.yaml``, ``.yml`` → ``ConfigType::YAML``
+- All others → ``ConfigType::LEGACY``
+
+You do not set this manually — ``register_config()`` infers it from the ``default_filename``.
+
+
+Adding a New Config Module
+==========================
+
+Step-by-step guide for adding a new configuration file to the reload framework.
+
+Step 1: Choose a Registry Key
+------------------------------
+
+Pick a short, lowercase, underscore-separated name that identifies the config. This key is used
+in ``traffic_ctl config status`` output, JSONRPC APIs, and inline YAML reload files.
+
+Examples: ``ip_allow``, ``logging``, ``cache_control``, ``ssl_ticket_key``, ``ssl_client_coordinator``
+
+For record-only configs (registered via ``register_record_config()``), the key identifies a group
+of records that share a handler — e.g. ``ssl_client_coordinator``.
+
+.. note::
+
+ Not all records support runtime reload. Records declared with ``RECU_DYNAMIC`` in
+ ``RecordsConfig.cc`` can trigger a handler at runtime. Records marked ``RECU_RESTART_TS``
+ require a server restart and are **not** affected by the reload framework. Only register
+ records that are ``RECU_DYNAMIC`` as trigger records for your handler.
+
+Step 2: Accept a ``ConfigContext`` Parameter
+--------------------------------------------
+
+Your handler function must accept a ``ConfigContext`` parameter. Use a default value so the
+handler can also be called at startup without a reload context:
+
+.. code-block:: cpp
+
+ // In the header — any function name is fine, "reconfigure" is the common convention:
+ static void reconfigure(ConfigContext ctx = {});
+
+A default-constructed ``ConfigContext{}`` is a **no-op context**: all status calls
+(``in_progress()``, ``complete()``, ``fail()``, ``log()``) are safe no-ops. This means the
+same handler works at startup (no active reload) and during a reload (with tracking).
+
+Step 3: Report Progress
+-----------------------
+
+Inside the handler, report progress through the context:
+
+.. code-block:: cpp
+
+ void MyConfig::reconfigure(ConfigContext ctx) {
+ ctx.in_progress();
+
+ // ... load and parse config ...
+
+ if (error) {
+ ctx.fail(errata, "Failed to load myconfig.yaml");
+ return;
+ }
+
+ ctx.log("Loaded {} rules", rule_count);
+ ctx.complete("Finished loading");
+ }
+
+.. warning::
+
+ Remember the :ref:`terminal state rule <config-context-terminal-state>`:
+ every code path must end with ``complete()`` or ``fail()``.
+
+Step 4: Register with ``ConfigRegistry``
+-----------------------------------------
+
+Call ``register_config()`` (or ``register_record_config()``) during your module's initialization
+— typically in a function you call at server startup. The function name is up to you; the
+convention in existing code is ``startup()``, but any name works.
+
+.. code-block:: cpp
+
+ void MyConfig::startup() { // or init(), or any name
+ config::ConfigRegistry::Get_Instance().register_config(
+ "myconfig", // registry key
+ "myconfig.yaml", // default filename
+ "proxy.config.mymodule.filename", // record holding filename
+ [](ConfigContext ctx) { MyConfig::reconfigure(ctx); }, // handler
+ config::ConfigSource::FileOnly, // content source
+ {"proxy.config.mymodule.filename"}); // triggers
+
+ // Initial load — ConfigContext{} is a no-op, so all ctx calls are safe
+ reconfigure();
+ }
+
+Step 5: Add File Dependencies (if needed)
+------------------------------------------
+
+If your config depends on auxiliary files, register them:
+
+.. code-block:: cpp
+
+ config::ConfigRegistry::Get_Instance().add_file_dependency(
+ "myconfig",
+ "proxy.config.mymodule.aux_filename",
+ "myconfig_aux.yaml",
+ false); // not required
+
+Step 6: Support Inline YAML (optional)
+---------------------------------------
+
+To accept YAML content via the RPC (``traffic_ctl config reload -d`` /
+:ref:`admin_config_reload` with ``configs``):
+
+1. Change the source to ``ConfigSource::FileAndRpc`` in the registration call.
+2. Check ``ctx.supplied_yaml()`` in the handler:
+
+.. code-block:: cpp
+
+ void MyConfig::reconfigure(ConfigContext ctx) {
+ ctx.in_progress();
+
+ YAML::Node root;
+ if (auto yaml = ctx.supplied_yaml()) {
+ // Inline mode: content from RPC. Not persisted to disk.
+ root = yaml;
+ } else {
+ // File mode: read from disk.
+ root = YAML::LoadFile(config_filename);
+ }
+
+ // ... parse and apply ...
+
+ ctx.complete("Loaded successfully");
+ }
+
+
+Composite Configs
+=================
+
+Some config modules coordinate multiple sub-configs. For example, ``SSLClientCoordinator`` owns
+``sni.yaml`` and ``ssl_multicert.config`` as children.
+
+Pattern:
+
+1. Register with ``register_record_config()`` (no primary file).
+2. Add file dependencies with ``add_file_and_node_dependency()`` for each child.
+3. In the handler, create child contexts with ``add_dependent_ctx()``.
+
+.. code-block:: cpp
+
+ void SSLClientCoordinator::startup() {
+ config::ConfigRegistry::Get_Instance().register_record_config(
+ "ssl_client_coordinator",
+ [](ConfigContext ctx) { SSLClientCoordinator::reconfigure(ctx); },
+ {"proxy.config.ssl.client.cert.path",
+ "proxy.config.ssl.server.session_ticket.enable"});
+
+ config::ConfigRegistry::Get_Instance().add_file_and_node_dependency(
+ "ssl_client_coordinator", "sni",
+ "proxy.config.ssl.servername.filename", "sni.yaml", false);
+
+ config::ConfigRegistry::Get_Instance().add_file_and_node_dependency(
+ "ssl_client_coordinator", "ssl_multicert",
+ "proxy.config.ssl.server.multicert.filename", "ssl_multicert.config", false);
+ }
+
+ void SSLClientCoordinator::reconfigure(ConfigContext ctx) {
+ ctx.in_progress();
+ SSLConfig::reconfigure(ctx.add_dependent_ctx("SSLConfig"));
+ SNIConfig::reconfigure(ctx.add_dependent_ctx("SNIConfig"));
+ SSLCertificateConfig::reconfigure(ctx.add_dependent_ctx("SSLCertificateConfig"));
+ ctx.complete("SSL configs reloaded");
+ }
+
+In :option:`traffic_ctl config status`, this renders as a tree:
+
+.. code-block:: text
+
+ ✔ ssl_client_coordinator ················· 35ms
+ ├─ ✔ SSLConfig ·························· 10ms
+ ├─ ✔ SNIConfig ·························· 12ms
+ └─ ✔ SSLCertificateConfig ·············· 13ms
+
+
+Startup vs. Reload
+==================
+
+A common pattern is to call the same handler at startup (initial config load) and during runtime
+reloads, but this is not mandatory — it is up to the developer. The only requirement is that the
+handler exposed to ``ConfigRegistry`` accepts a ``ConfigContext`` parameter.
+
+At startup there is no active reload task, so all ``ConfigContext`` methods are **safe no-ops** —
+they check the internal weak pointer and return immediately.
+
+This means the same handler code works in both cases without branching:
+
+.. code-block:: cpp
+
+ void MyConfig::reconfigure(ConfigContext ctx) {
+ ctx.in_progress(); // no-op at startup, tracks progress during reload
+ // ... load config ...
+ ctx.complete(); // no-op at startup, marks task as SUCCESS during reload
+ }
+
+
+Thread Model
+============
+
+All reload work runs on **ET_TASK** threads — never on the RPC thread or event-loop threads.
+
+1. **RPC thread** — receives the JSONRPC request (:ref:`admin_config_reload`), creates the reload
+ token and task via ``ReloadCoordinator::prepare_reload()``, schedules the actual work on
+ ``ET_TASK``, and returns immediately. The RPC response is sent back before any handler runs.
+
+2. **ET_TASK — file-based reload** — ``ReloadWorkContinuation`` fires on ``ET_TASK``. It calls
+ ``FileManager::rereadConfig()``, which walks every registered file and invokes
+ ``ConfigRegistry::execute_reload()`` for each changed config. Each handler runs synchronously.
+
+3. **ET_TASK — inline (RPC) reload** — ``ScheduledReloadContinuation`` fires on ``ET_TASK``.
+ It calls ``ConfigRegistry::execute_reload()`` directly for the targeted config key(s).
+
+4. **Deferred handlers** — some handlers schedule work on other threads and return before
+ completion. The ``ConfigContext`` remains valid across threads. The handler must call
+ ``ctx.complete()`` or ``ctx.fail()`` from whatever thread finishes the work.
+
+5. **Timeout checker** — ``ConfigReloadProgress`` is a per-reload continuation on ``ET_TASK``
+ that polls periodically and marks stuck tasks as ``TIMEOUT``.
+
+Handlers block ``ET_TASK`` while they run. A slow handler delays all subsequent handlers in the
+same reload cycle.
+
+
+Naming Conventions
+==================
+
+- **Registry keys** — lowercase, underscore-separated: ``ip_allow``, ``cache_control``,
+ ``ssl_ticket_key``, ``ssl_client_coordinator``.
+- **Filename records** — follow the existing ``proxy.config.<module>.filename`` convention.
+- **Trigger records** — any ``proxy.config.*`` record that should cause a reload when changed.
+
+
+What NOT to Register
+====================
+
+Not every config file needs a **reload handler**. Startup-only configs that are never reloaded at
+runtime (e.g. ``storage.config``, ``volume.config``, ``plugin.config``) should be registered via
+``register_static_file()`` — this gives them visibility in the registry and RPC endpoints, but
+does not wire any reload handler or trigger records. Do not use ``register_config()`` for files
+that have no runtime reload support.
+
+
+Logging Best Practices
+======================
+
+- Use ``ctx.log()`` for operational messages that appear in
+ ``traffic_ctl config status -l`` and :ref:`get_reload_config_status` responses.
+- Use ``ctx.fail(errata, summary)`` when you have a ``swoc::Errata`` with detailed error context.
+- Use ``ctx.fail(reason)`` for simple error strings.
+- Keep log messages concise — they are stored in memory and included in JSONRPC responses.
+
+See the :ref:`get_reload_config_status` response examples for how log messages appear in the
+task tree output.
+
+
+Testing
+========
+
+After registering a new handler:
+
+1. Start |TS| and verify your handler runs at startup (check logs for your config file).
+2. Modify the config file on disk and run :option:`traffic_ctl config reload` ``-m`` to observe the
+ live progress bar.
+3. Run :option:`traffic_ctl config status` to verify the handler appears in the task tree with
+ the correct status.
+4. Introduce a parse error in the config file and reload — verify the handler reports ``FAIL``.
+5. Use :option:`traffic_ctl config status` ``--format json`` to inspect the raw
+ :ref:`get_reload_config_status` response for automation testing.
+
+**Autests** — the project includes autest helpers for config reload testing. Use
+``AddJsonRPCClientRequest`` with ``Request.admin_config_reload()`` to trigger reloads, and
+``Testers.CustomJSONRPCResponse`` to validate responses programmatically. See the existing tests
+for examples:
+
+- ``tests/gold_tests/jsonrpc/config_reload_tracking.test.py`` — token generation, status
+ queries, history, force reload, duplicate token rejection.
+- ``tests/gold_tests/jsonrpc/config_reload_rpc.test.py`` — inline reload, multiple configs,
+ ``FileOnly`` rejection, large payloads.
+- ``tests/gold_tests/jsonrpc/config_reload_failures.test.py`` — error handling, broken configs,
+ handler failure reporting.
+
+
+.. _reload-framework-records:
+
+Configuration Records
+=====================
+
+The reload framework uses the following configuration records:
+
+.. ts:cv:: CONFIG proxy.config.admin.reload.timeout STRING 1h
+ :reloadable:
+
+ Maximum time a reload task can run before being marked as ``TIMEOUT``.
+ Supports duration strings: ``30s``, ``5min``, ``1h``. Set to ``0`` to disable.
+ Default: ``1h``.
+
+.. ts:cv:: CONFIG proxy.config.admin.reload.check_interval STRING 2s
+ :reloadable:
+
+ How often the progress checker polls for stuck tasks (minimum: ``1s``).
+ Supports duration strings: ``1s``, ``5s``, ``30s``.
+ Default: ``2s``.
diff --git a/doc/developer-guide/index.en.rst b/doc/developer-guide/index.en.rst
index 7a900585ca..e4f16a9ea7 100644
--- a/doc/developer-guide/index.en.rst
+++ b/doc/developer-guide/index.en.rst
@@ -49,6 +49,7 @@ duplicate bugs is encouraged, but not required.
plugins/index.en
cripts/index.en
config-vars.en
+ config-reload-framework.en
api/index.en
continuous-integration/index.en
documentation/index.en
diff --git a/doc/developer-guide/jsonrpc/jsonrpc-api.en.rst b/doc/developer-guide/jsonrpc/jsonrpc-api.en.rst
index e232a09e39..57aa835a9f 100644
--- a/doc/developer-guide/jsonrpc/jsonrpc-api.en.rst
+++ b/doc/developer-guide/jsonrpc/jsonrpc-api.en.rst
@@ -922,27 +922,67 @@ admin_config_reload
Description
~~~~~~~~~~~
-Instruct |TS| to start the reloading process. You can find more information about config reload here(add link TBC)
+Initiate a configuration reload. This method returns immediately — the actual reload runs
+asynchronously on background threads (``ET_TASK``). The response contains a **token** that the
+caller uses to track the reload's progress and query its final status via
+:ref:`get_reload_config_status`.
+
+This method supports two modes:
+
+- **File-based reload** (default) — re-reads all registered configuration files from disk and invokes
+ their handlers for any files whose modification time has changed.
+- **Inline reload** — when the ``configs`` parameter is present, the supplied YAML content is passed
+ directly to the targeted handler(s) at runtime. Inline content is **not persisted to disk** — a
+ server restart will revert to the file-based configuration.
+
+Each reload is assigned a **token** that can be used to query its status via
+:ref:`get_reload_config_status`. If no token is provided, the server generates one automatically.
+
+Only one reload can be active at a time. If a reload is already in progress, the request is rejected
+unless ``force`` is set to ``true``.
+
+For more information about the configuration reload framework, see
+:ref:`config-reload-framework`.
Parameters
~~~~~~~~~~
-* ``params``: Omitted
+All parameters are optional.
-.. note::
+=================== ============= ================================================================================================================
+Field Type Description
+=================== ============= ================================================================================================================
+``token`` |str| Custom token for this reload. Must be unique. If omitted, the server generates one (e.g. ``rldtk-<timestamp>``).
+``force`` ``bool`` Force a new reload even if one is in progress. Default: ``false``. Use with caution.
+``configs`` ``object`` YAML content for inline reload. Each key is a registry key (e.g. ``ip_allow``, ``sni``), and each value is the
+ full configuration content for that handler. When present, triggers an inline reload instead of a file-based one.
+=================== ============= ================================================================================================================
- There is no need to add any parameters here.
Result
~~~~~~
-A |str| with the success message indicating that the command was acknowledged by the server.
+On success, the response contains:
+
+=================== ============= ================================================================================================================
+Field Type Description
+=================== ============= ================================================================================================================
+``token`` |str| The token assigned to this reload (server-generated or the one provided in the request).
+``message`` ``array`` Human-readable status messages.
+``created_time`` |str| Timestamp when the reload task was created.
+=================== ============= ================================================================================================================
+
+If a reload is already in progress (and ``force`` is not set), the response includes an ``errors`` array
+with code ``RELOAD_IN_PROGRESS`` and the ``tasks`` array with the current reload's status.
+
Examples
~~~~~~~~
+**File-based reload (default):**
+
Request:
.. code-block:: json
@@ -951,18 +991,264 @@ Request:
{
"id": "89fc5aea-0740-11eb-82c0-001fc69cc946",
"jsonrpc": "2.0",
- "method": "admin_config_reload"
+ "method": "admin_config_reload",
+ "params": {
+ "token": "deploy-v2.1"
+ }
}
Response:
-The response will contain the default `success_response` or a proper rpc error, check :ref:`jsonrpc-node-errors` for mode details.
+.. code-block:: json
+ :linenos:
+
+ {
+ "jsonrpc": "2.0",
+ "result": {
+ "token": "deploy-v2.1",
+ "message": ["Reload task scheduled"],
+ "created_time": "2025 Feb 17 12:00:00"
+ },
+ "id": "89fc5aea-0740-11eb-82c0-001fc69cc946"
+ }
+
+
+**Inline reload (with ``configs``):**
+
+The ``configs`` parameter is a map where each key is a **registry key** (e.g. ``ip_allow``, ``sni``)
+and each value is the **config content** — the inner data, not the full file structure. For example,
+``ip_allow.yaml`` on disk wraps rules under an ``ip_allow:`` top-level key, but when injecting via
+RPC, you pass the rules array directly. The handler receives this content via
+``ctx.supplied_yaml()`` and is responsible for using it without the file's wrapper key.
+
+Request:
+
+.. code-block:: json
+ :linenos:
+
+ {
+ "id": "b1c2d3e4-0001-0001-0001-000000000001",
+ "jsonrpc": "2.0",
+ "method": "admin_config_reload",
+ "params": {
+ "token": "update-ip-and-sni",
+ "configs": {
+ "ip_allow": [
+ {
+ "apply": "in",
+ "ip_addrs": "0.0.0.0/0",
+ "action": "allow",
+ "methods": "ALL"
+ }
+ ],
+ "sni": [
+ {
+ "fqdn": "*.example.com",
+ "verify_client": "NONE"
+ }
+ ]
+ }
+ }
+ }
+
+Response:
+
+.. code-block:: json
+ :linenos:
+
+ {
+ "jsonrpc": "2.0",
+ "result": {
+ "token": "update-ip-and-sni",
+ "message": ["Inline reload scheduled"],
+ "created_time": "2025 Feb 17 14:30:10"
+ },
+ "id": "b1c2d3e4-0001-0001-0001-000000000001"
+ }
+
+.. note::
+
+ Inline reload requires the target config handler to support ``ConfigSource::FileAndRpc``.
+ Handlers that only support ``ConfigSource::FileOnly`` will return an error for the
+ corresponding key.
-Validation:
+**Reload already in progress:**
+
+.. code-block:: json
+ :linenos:
+
+ {
+ "jsonrpc": "2.0",
+ "result": {
+ "errors": [
+ {
+ "message": "Reload ongoing with token 'deploy-v2.1'",
+ "code": 1
+ }
+ ],
+ "tasks": []
+ },
+ "id": "89fc5aea-0740-11eb-82c0-001fc69cc946"
+ }
+
+
+.. _get_reload_config_status:
+
+get_reload_config_status
+------------------------
+
+|method|
+
+Description
+~~~~~~~~~~~
-You can request for the record `proxy.process.proxy.reconfigure_time` which will be updated with the time of the requested update.
+Query the status of configuration reloads. Can retrieve a specific reload by token, or the last
+``N`` reloads from the history.
+
+Each reload status includes an overall result, a task tree with per-handler status, durations,
+and optional log messages.
+
+
+Parameters
+~~~~~~~~~~
+
+All parameters are optional. If neither is provided, returns the most recent reload.
+
+=================== ============= ================================================================================================================
+Field Type Description
+=================== ============= ================================================================================================================
+``token`` |str| Token of the reload to query. Takes precedence over ``count`` if both are provided.
+``count`` ``number`` Number of recent reloads to return. Use ``0`` to return the full history. Default: ``1``.
+=================== ============= ================================================================================================================
+
+``traffic_ctl`` maps ``--count all`` to ``count: 0`` in the RPC request. The server keeps a
+rolling history of the last 100 reloads — when the limit is reached, the oldest entry is evicted
+to make room for new ones. ``count: 0`` returns the full history, most recent first.
+
+
+Result
+~~~~~~
+
+The response contains a ``tasks`` array. Each element represents a reload operation with the following
+structure:
+
+======================= ============= ===================================================================
+Field Type Description
+======================= ============= ===================================================================
+``config_token`` |str| The reload token.
+``status`` |str| Overall status: ``success``, ``fail``, ``in_progress``, ``timeout``.
+``description`` |str| Human-readable description.
+``config_key`` |str| Registry key used for deduplication (empty for main tasks).
+``filename`` |str| Associated filename (empty for the main task).
+``meta`` ``object`` Metadata: ``created_time_ms``, ``last_updated_time_ms``, ``main_task``.
+``log`` ``array`` Log messages from the handler.
+``sub_tasks`` ``array`` Nested sub-tasks (same structure, recursive).
+======================= ============= ===================================================================
+
+
+Examples
+~~~~~~~~
+
+
+**Query a specific reload by token:**
+
+Request:
+
+.. code-block:: json
+ :linenos:
+
+ {
+ "id": "f1e2d3c4-0001-0001-0001-000000000001",
+ "jsonrpc": "2.0",
+ "method": "get_reload_config_status",
+ "params": {
+ "token": "deploy-v2.1"
+ }
+ }
+
+Response:
+
+.. code-block:: json
+ :linenos:
+
+ {
+ "jsonrpc": "2.0",
+ "result": {
+ "tasks": [
+ {
+ "config_token": "deploy-v2.1",
+ "status": "success",
+ "description": "Main reload task - 2025 Feb 17 12:00:00",
+ "config_key": "",
+ "filename": "",
+ "meta": {
+ "created_time_ms": "1739808000123",
+ "last_updated_time_ms": "1739808000368",
+ "main_task": "true"
+ },
+ "logs": [],
+ "sub_tasks": [
+ {
+ "config_token": "deploy-v2.1",
+ "status": "success",
+ "description": "ip_allow",
+ "config_key": "ip_allow",
+ "filename": "/opt/ats/etc/trafficserver/ip_allow.yaml",
+ "meta": {
+ "created_time_ms": "1739808000200",
+ "last_updated_time_ms": "1739808000218",
+ "main_task": "false"
+ },
+ "logs": ["Finished loading"],
+ "sub_tasks": []
+ }
+ ]
+ }
+ ]
+ },
+ "id": "f1e2d3c4-0001-0001-0001-000000000001"
+ }
+
+
+**Query reload history (last 3):**
+
+Request:
+
+.. code-block:: json
+ :linenos:
+
+ {
+ "id": "a1b2c3d4-0001-0001-0001-000000000002",
+ "jsonrpc": "2.0",
+ "method": "get_reload_config_status",
+ "params": {
+ "count": 3
+ }
+ }
+
+Response contains up to 3 entries in the ``tasks`` array.
+
+
+**Token not found:**
+
+.. code-block:: json
+ :linenos:
+
+ {
+ "jsonrpc": "2.0",
+ "result": {
+ "errors": [
+ {
+ "message": "Token 'nonexistent' not found",
+ "code": 4
+ }
+ ],
+ "token": "nonexistent"
+ },
+ "id": "f1e2d3c4-0001-0001-0001-000000000001"
+ }
Host
diff --git a/include/iocore/dns/SplitDNSProcessor.h b/include/iocore/dns/SplitDNSProcessor.h
index 6097a109b9..caa7b8e95d 100644
--- a/include/iocore/dns/SplitDNSProcessor.h
+++ b/include/iocore/dns/SplitDNSProcessor.h
@@ -46,14 +46,13 @@ struct SplitDNSConfig {
static bool isSplitDNSEnabled();
- static void reconfigure();
+ static void reconfigure(ConfigContext ctx = {});
static SplitDNS *acquire();
static void release(SplitDNS *params);
static void print();
- static int m_id;
- static Ptr<ProxyMutex> dnsHandler_mutex;
- static ConfigUpdateHandler<SplitDNSConfig> *splitDNSUpdate;
+ static int m_id;
+ static Ptr<ProxyMutex> dnsHandler_mutex;
static int gsplit_dns_enabled;
};
diff --git a/include/iocore/eventsystem/ConfigProcessor.h b/include/iocore/eventsystem/ConfigProcessor.h
index 80b1e0b786..14804a5ffe 100644
--- a/include/iocore/eventsystem/ConfigProcessor.h
+++ b/include/iocore/eventsystem/ConfigProcessor.h
@@ -70,50 +70,4 @@ public:
std::atomic<int> ninfos{0};
};
-// A Continuation wrapper that calls the static reconfigure() method of the given class.
-template <typename UpdateClass> struct ConfigUpdateContinuation : public Continuation {
- int
- update(int /* etype */, void * /* data */)
- {
- UpdateClass::reconfigure();
- delete this;
- return EVENT_DONE;
- }
-
- ConfigUpdateContinuation(Ptr<ProxyMutex> &m) : Continuation(m.get()) { SET_HANDLER(&ConfigUpdateContinuation::update); }
-};
-
-template <typename UpdateClass>
-int
-ConfigScheduleUpdate(Ptr<ProxyMutex> &mutex)
-{
- eventProcessor.schedule_imm(new ConfigUpdateContinuation<UpdateClass>(mutex), ET_TASK);
- return 0;
-}
-
-template <typename UpdateClass> struct ConfigUpdateHandler {
- ConfigUpdateHandler() : mutex(new_ProxyMutex()) {}
- // The mutex member is ref-counted so should not explicitly free it
- ~ConfigUpdateHandler() {}
- int
- attach(const char *name)
- {
- return RecRegisterConfigUpdateCb(name, ConfigUpdateHandler::update, this);
- }
-
-private:
- static int
- update(const char *name, RecDataT /* data_type ATS_UNUSED */, RecData /* data ATS_UNUSED */, void *cookie)
- {
- ConfigUpdateHandler *self = static_cast<ConfigUpdateHandler *>(cookie);
-
- Dbg(_dbg_ctl, "%s(%s)", __PRETTY_FUNCTION__, name);
- return ConfigScheduleUpdate<UpdateClass>(self->mutex);
- }
-
- Ptr<ProxyMutex> mutex;
-
- inline static DbgCtl _dbg_ctl{"config"};
-};
-
extern ConfigProcessor configProcessor;
diff --git a/include/iocore/net/QUICMultiCertConfigLoader.h b/include/iocore/net/QUICMultiCertConfigLoader.h
index c2bfec87a9..4dad3313a6 100644
--- a/include/iocore/net/QUICMultiCertConfigLoader.h
+++ b/include/iocore/net/QUICMultiCertConfigLoader.h
@@ -30,7 +30,7 @@ class QUICCertConfig
{
public:
static void startup();
- static void reconfigure();
+ static void reconfigure(ConfigContext ctx = {});
static SSLCertLookup *acquire();
static void release(SSLCertLookup *lookup);
diff --git a/include/iocore/net/SSLSNIConfig.h b/include/iocore/net/SSLSNIConfig.h
index 4e2612cad8..b71502b6e3 100644
--- a/include/iocore/net/SSLSNIConfig.h
+++ b/include/iocore/net/SSLSNIConfig.h
@@ -117,7 +117,7 @@ public:
/** Loads sni.yaml and swap into place if successful
@return 0 for success, 1 is failure
*/
- static int reconfigure();
+ static int reconfigure(ConfigContext ctx = {});
static SNIConfigParams *acquire();
static void release(SNIConfigParams *params);
diff --git a/include/iocore/net/quic/QUICConfig.h b/include/iocore/net/quic/QUICConfig.h
index c0f28786f3..3bc871091a 100644
--- a/include/iocore/net/quic/QUICConfig.h
+++ b/include/iocore/net/quic/QUICConfig.h
@@ -151,7 +151,7 @@ class QUICConfig
{
public:
static void startup();
- static void reconfigure();
+ static void reconfigure(ConfigContext ctx = {});
static QUICConfigParams *acquire();
static void release(QUICConfigParams *params);
diff --git a/include/mgmt/config/ConfigContext.h b/include/mgmt/config/ConfigContext.h
new file mode 100644
index 0000000000..0dbce853a1
--- /dev/null
+++ b/include/mgmt/config/ConfigContext.h
@@ -0,0 +1,195 @@
+/** @file
+
+ ConfigContext - Context for configuration loading/reloading operations
+
+ Provides:
+ - Status tracking (in_progress, complete, fail, log)
+ - Inline content support for YAML configs (via -d flag or RPC API)
+
+ @section license License
+
+ Licensed to the Apache Software Foundation (ASF) under one
+ or more contributor license agreements. See the NOTICE file
+ distributed with this work for additional information
+ regarding copyright ownership. The ASF licenses this file
+ to you under the Apache License, Version 2.0 (the
+ "License"); you may not use this file except in compliance
+ with the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+ */
+
+#pragma once
+
+#include <memory>
+#include <string>
+#include <string_view>
+
+#include "swoc/Errata.h"
+#include "swoc/BufferWriter.h"
+#include "yaml-cpp/node/node.h"
+
+// Forward declarations
+class ConfigReloadTask;
+class ReloadCoordinator;
+namespace config
+{
+class ConfigRegistry;
+}
+
+///
+/// @brief Context passed to config handlers during load/reload operations.
+///
+/// This object is passed to reconfigure() methods to:
+/// 1. Track progress/status of the operation (in_progress, complete, fail, log)
+/// 2. Provide RPC-supplied YAML content (for -d flag (traffic_ctl) or direct JSONRPC calls)
+///
+/// For file-based reloads, handlers read from their own registered filename.
+/// For RPC reloads, handlers use supplied_yaml() to get the content.
+///
+/// @note This context is also used during **startup** configuration loading.
+/// At startup there is no active reload task, so all status operations
+/// (in_progress, complete, fail, log) are safe **no-ops**. To keep the
+/// existing code logic for loading/reloading this design aims to avoid
+/// having two separate code paths for startup vs. reload — handlers
+/// can use the same API in both cases.
+///
+/// Usage:
+/// @code
+/// void MyConfig::reconfigure(ConfigContext ctx) {
+/// ctx.in_progress();
+///
+/// YAML::Node root;
+/// if (auto yaml = ctx.supplied_yaml()) {
+/// // RPC mode: content provided via -d flag or RPC.
+/// // YAML::Node has explicit operator bool() → true when IsDefined().
+/// // Copy is cheap (internally reference-counted).
+/// root = yaml;
+/// } else {
+/// // File mode: read from registered filename.
+/// root = YAML::LoadFile(my_config_filename);
+/// }
+///
+/// // ... process config ...
+///
+/// ctx.complete("Loaded successfully");
+/// }
+/// @endcode
+///
+class ConfigContext
+{
+public:
+ ConfigContext();
+
+ explicit ConfigContext(std::shared_ptr<ConfigReloadTask> t, std::string_view description = "", std::string_view filename = "");
+
+ ~ConfigContext();
+
+ // Copy only — move is intentionally suppressed.
+ // ConfigContext holds a weak_ptr (cheap to copy) and a YAML::Node (ref-counted).
+ // Suppressing move ensures that std::move(ctx) silently copies, keeping the
+ // original valid. This is critical for execute_reload()'s post-handler check:
+ // if a handler defers work (e.g. LogConfig), the original ctx must remain
+ // valid so is_terminal() can detect the non-terminal state and emit a warning.
+ ConfigContext(ConfigContext const &);
+ ConfigContext &operator=(ConfigContext const &);
+
+ /// Check if this context wraps a live task.
+ /// Returns false for default-constructed or dedup-rejected contexts.
+ explicit
+ operator bool() const
+ {
+ return !_task.expired();
+ }
+
+ void in_progress(std::string_view text = "");
+ template <typename... Args>
+ void
+ in_progress(swoc::TextView fmt, Args &&...args)
+ {
+ std::string buf;
+ in_progress(swoc::bwprint(buf, fmt, std::forward<Args>(args)...));
+ }
+
+ void log(std::string_view text);
+ template <typename... Args>
+ void
+ log(swoc::TextView fmt, Args &&...args)
+ {
+ std::string buf;
+ log(swoc::bwprint(buf, fmt, std::forward<Args>(args)...));
+ }
+
+ /// Mark operation as successfully completed
+ void complete(std::string_view text = "");
+ template <typename... Args>
+ void
+ complete(swoc::TextView fmt, Args &&...args)
+ {
+ std::string buf;
+ complete(swoc::bwprint(buf, fmt, std::forward<Args>(args)...));
+ }
+
+ /// Mark operation as failed.
+ void fail(swoc::Errata const &errata, std::string_view summary = "");
+ void fail(std::string_view reason = "");
+ template <typename... Args>
+ void
+ fail(swoc::TextView fmt, Args &&...args)
+ {
+ std::string buf;
+ fail(swoc::bwprint(buf, fmt, std::forward<Args>(args)...));
+ }
+ /// Eg: fail(errata, "Failed to load config: {}", filename);
+ template <typename... Args>
+ void
+ fail(swoc::Errata const &errata, swoc::TextView fmt, Args &&...args)
+ {
+ std::string buf;
+ fail(errata, swoc::bwprint(buf, fmt, std::forward<Args>(args)...));
+ }
+
+ /// Check if the task has reached a terminal state (SUCCESS, FAIL, TIMEOUT).
+ [[nodiscard]] bool is_terminal() const;
+
+ /// Get the description associated with this context's task.
+ /// For registered configs this is the registration key (e.g., "sni", "ssl").
+ /// For dependent contexts it is the label passed to add_dependent_ctx().
+ [[nodiscard]] std::string get_description() const;
+
+ /// Create a dependent sub-task that tracks progress independently under this parent.
+ /// Each dependent reports its own status (in_progress/complete/fail) and the parent
+ /// task aggregates them. The dependent context also inherits the parent's supplied YAML node.
+ ///
+ [[nodiscard]] ConfigContext add_dependent_ctx(std::string_view description = "");
+
+ /// Get supplied YAML node (for RPC-based reloads).
+ /// A default-constructed YAML::Node is Undefined (operator bool() == false).
+ /// @code
+ /// if (auto yaml = ctx.supplied_yaml()) { /* use yaml node */ }
+ /// @endcode
+ /// @return copy of the supplied YAML node (cheap — YAML::Node is internally reference-counted).
+ [[nodiscard]] YAML::Node supplied_yaml() const;
+
+private:
+ /// Set supplied YAML node. Only ConfigRegistry should call this during reload setup.
+ void set_supplied_yaml(YAML::Node node);
+
+ std::weak_ptr<ConfigReloadTask> _task;
+ YAML::Node _supplied_yaml; ///< for no content, this will just be empty
+
+ friend class ReloadCoordinator;
+ friend class config::ConfigRegistry;
+};
+
+namespace config
+{
+/// Create a ConfigContext for use in reconfigure handlers
+ConfigContext make_config_reload_context(std::string_view description, std::string_view filename = "");
+} // namespace config
diff --git a/include/mgmt/config/ConfigRegistry.h b/include/mgmt/config/ConfigRegistry.h
new file mode 100644
index 0000000000..2ff1a8380f
--- /dev/null
+++ b/include/mgmt/config/ConfigRegistry.h
@@ -0,0 +1,344 @@
+/** @file
+ *
+ * Config Registry - Centralized configuration management
+ *
+ * Provides:
+ * - Registration of config handlers by key
+ * - Flexible trigger attachment (at registration or later)
+ * - RPC reload support (YAML content supplied via RPC)
+ * - Runtime lookup for RPC handlers
+ *
+ * @section license License
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+#include <functional>
+#include <initializer_list>
+#include <shared_mutex>
+#include <string>
+#include <unordered_map>
+#include <vector>
+
+#include <yaml-cpp/yaml.h>
+
+#include "iocore/eventsystem/Lock.h" // For Ptr<ProxyMutex>
+#include "mgmt/config/ConfigContext.h"
+#include "swoc/Errata.h"
+
+namespace config
+{
+
+/// Type of configuration file
+enum class ConfigType {
+ YAML, ///< Modern YAML config (ip_allow.yaml, sni.yaml, etc.)
+ LEGACY ///< Legacy .config files (remap.config, etc.)
+};
+
+/// Declares what content sources a config handler supports.
+/// @note If more sources are needed (e.g., Plugin, Env), consider
+/// converting to bitwise flags instead of adding combinatorial values.
+enum class ConfigSource {
+ FileOnly, ///< Handler only reloads from file on disk
+ RecordOnly, ///< Handler only reacts to record changes (no file, no RPC content)
+ FileAndRpc ///< Handler can also process YAML content supplied via RPC
+};
+
+/// Handler signature for config reload - receives ConfigContext
+/// Handler can check ctx.supplied_yaml() for rpc-supplied content
+using ConfigReloadHandler = std::function<void(ConfigContext)>;
+
+///
+/// @brief Central registry for configuration files
+///
+/// Singleton that maps config keys to their handlers, supporting:
+/// - YAML and legacy .config file types
+/// - Multiple trigger records per config
+/// - RPC reload with supplied YAML content (not for legacy .config)
+/// - Runtime lookup by string key
+///
+/// Usage:
+/// @code
+/// // Register with filename record (allows runtime filename changes)
+/// ConfigRegistry::Get_Instance().register_yaml(
+/// "ip_allow", // key
+/// "ip_allow.yaml", // default filename
+/// "proxy.config.cache.ip_allow.filename", // record holding filename
+/// [](ConfigContext s) { IpAllow::reconfigure(s); },
+/// {"proxy.config.cache.ip_allow.filename"} // triggers
+/// );
+///
+/// // Later, if needed, add another trigger from a different module
+/// ConfigRegistry::Get_Instance().attach("ip_allow", "proxy.config.plugin.extra");
+///
+/// // RPC reload with supplied content:
+/// // 1. Store content: registry.set_passed_config("ip_allow", yaml_node);
+/// // 2. Schedule: registry.schedule_reload("ip_allow");
+/// @endcode
+///
+class ConfigRegistry
+{
+public:
+ ///
+ /// @brief Configuration entry
+ ///
+ struct Entry {
+ std::string key; ///< Registry key (e.g., "ip_allow")
+ std::string default_filename; ///< Default filename if record not set (e.g., "ip_allow.yaml")
+ std::string filename_record; ///< Record containing filename (e.g., "proxy.config.cache.ip_allow.filename")
+ ConfigType type; ///< YAML or LEGACY - we set that based on the filename extension.
+ ConfigSource source{ConfigSource::FileOnly}; ///< What content sources this handler supports
+ ConfigReloadHandler handler; ///< Handler function (empty = static file/not reloadable)
+ std::vector<std::string> trigger_records; ///< Records that trigger reload
+ bool is_required{false}; ///< Whether the file must exist on disk
+
+ /// Resolve the actual filename (reads from record, falls back to default)
+ std::string resolve_filename() const;
+
+ /// Whether this entry has a reload handler (false for static/non-reloadable files).
+ bool
+ has_handler() const
+ {
+ return static_cast<bool>(handler);
+ }
+ };
+
+ ///
+ /// @brief Get singleton instance
+ ///
+ static ConfigRegistry &Get_Instance();
+
+ ///
+ /// @brief Register a config file
+ ///
+ /// Type (YAML/LEGACY) is inferred from filename extension:
+ /// - .yaml, .yml → YAML (supports rpc reload via ctx.supplied_yaml())
+ /// - others → LEGACY (file-based only)
+ ///
+ /// @param key Registry key (e.g., "ip_allow")
+ /// @param default_filename Default filename (e.g., "ip_allow.yaml")
+ /// @param filename_record Record that holds the filename (e.g., "proxy.config.cache.ip_allow.filename")
+ /// If empty, default_filename is always used.
+ /// @param handler Handler that receives ConfigContext
+ /// @param trigger_records Records that trigger reload (optional)
+ /// @param is_required Whether the file must exist on disk (default false)
+ ///
+ void register_config(const std::string &key, const std::string &default_filename, const std::string &filename_record,
+ ConfigReloadHandler handler, ConfigSource source, std::initializer_list<const char *> trigger_records = {},
+ bool is_required = false);
+
+ /// @brief Register a record-only config handler (no file).
+ ///
+ /// Convenience method for modules that have no config file but need their
+ /// reload handler to participate in the config tracking system (tracing,
+ /// status reporting, traffic_ctl config reload).
+ ///
+ /// This is NOT for arbitrary record-change callbacks — use RecRegisterConfigUpdateCb
+ /// for that. This is for config modules like SSLTicketKeyConfig that are reloaded
+ /// via record changes and need visibility in the reload infrastructure.
+ ///
+ /// Internally uses ConfigSource::RecordOnly.
+ ///
+ /// @param key Registry key (e.g., "ssl_ticket_key")
+ /// @param handler Handler that receives ConfigContext
+ /// @param trigger_records Records that trigger reload
+ ///
+ void register_record_config(const std::string &key, ConfigReloadHandler handler,
+ std::initializer_list<const char *> trigger_records);
+
+ /// @brief Register a non-reloadable config file (startup files).
+ ///
+ /// Static files are registered for informational purposes only — no reload
+ /// handler and no trigger records. This allows the registry to serve as the
+ /// single source of truth for all known configuration files, so that RPC
+ /// endpoints can gather and expose this information.
+ ///
+ /// @param key Registry key (e.g., "storage")
+ /// @param default_filename Default filename (e.g., "storage.config")
+ /// @param filename_record Record holding the filename path (optional)
+ /// @param is_required Whether the file must exist on disk
+ ///
+ void register_static_file(const std::string &key, const std::string &default_filename, const std::string &filename_record = {},
+ bool is_required = false);
+
+ ///
+ /// @brief Attach a trigger record to an existing config
+ ///
+ /// Can be called from any module to add additional triggers.
+ ///
+ /// @note Attaches an additional record trigger to an existing config entry.
+ ///
+ /// @param key The registered config key
+ /// @param record_name The record that triggers reload
+ /// @return 0 on success, -1 if key not found
+ ///
+ int attach(const std::string &key, const char *record_name);
+
+ ///
+ /// @brief Add a file dependency to an existing config
+ ///
+ /// Registers an additional file with FileManager for mtime-based change detection
+ /// and sets up a record callback to trigger the config's reload handler when the
+ /// file changes on disk or the record value is modified.
+ ///
+ /// This is for auxiliary/companion files that a config module depends on but that
+ /// are not the primary config file. For example, ip_allow depends on ip_categories.
+ ///
+ ///
+ /// @param key The registered config key (must already exist)
+ /// @param filename_record Record holding the filename (e.g., "proxy.config.cache.ip_categories.filename")
+ /// @param default_filename Default filename when record value is empty (e.g., "ip_categories.yaml")
+ /// @param is_required Whether the file is required to exist
+ /// @return 0 on success, -1 if key not found
+ ///
+ int add_file_dependency(const std::string &key, const char *filename_record, const char *default_filename, bool is_required);
+
+ ///
+ /// @brief Add a file dependency with an RPC-routable node key
+ ///
+ /// Like add_file_dependency(), but also registers @p dep_key as a routable key
+ /// so the RPC handler can route inline YAML content to the parent entry's handler.
+ ///
+ /// When an RPC reload request specifies @p dep_key, resolve() maps it to the parent
+ /// entry, and the content is grouped under the dep_key in the YAML node passed to
+ /// the handler. The handler (or its sub-modules) can then check for their key:
+ /// @code
+ /// if (auto yaml = ctx.supplied_yaml(); yaml && yaml["sni"]) {
+ /// // parse from yaml["sni"] instead of file
+ /// }
+ /// @endcode
+ ///
+ /// @param key The registered parent config key (must already exist)
+ /// @param dep_key Key for RPC routing (e.g., "sni"). Must be unique across all entries and dependencies.
+ /// @param filename_record Record holding the filename
+ /// @param default_filename Default filename when record value is empty
+ /// @param is_required Whether the file is required to exist
+ /// @return 0 on success, -1 if key not found or dep_key already exists
+ ///
+ int add_file_and_node_dependency(const std::string &key, const std::string &dep_key, const char *filename_record,
+ const char *default_filename, bool is_required);
+
+ ///
+ /// @brief Resolve a key to its entry, handling both direct entries and dependency keys
+ ///
+ /// Looks up @p key first in the direct entry map, then in the dependency key map.
+ /// For direct entries, returns {key, entry}. For dependency keys, returns {parent_key, parent_entry}.
+ /// Returns {"", nullptr} if the key is not found.
+ ///
+ /// Used by the RPC handler to route inline content to the correct parent handler,
+ /// grouping multiple dependency keys under the same parent into a single reload.
+ ///
+ /// @param key The key to look up (can be a direct entry key or a dependency key)
+ /// @return pair of {resolved_parent_key, entry_pointer}
+ ///
+ std::pair<std::string, Entry const *> resolve(const std::string &key) const;
+
+ ///
+ /// @brief Store passed config content for a key (internal RPC use only)
+ ///
+ /// Stores YAML content passed via RPC for rpc reload.
+ /// Called by RPC handlers in Configuration.cc before schedule_reload().
+ /// Content is kept for future reference/debugging.
+ /// Thread-safe.
+ ///
+ /// @note Not intended for external use. Will be moved to a restricted interface
+ /// when the plugin config registration API is introduced.
+ ///
+ /// @param key The registered config key
+ /// @param content YAML::Node content to store
+ ///
+ void set_passed_config(const std::string &key, YAML::Node content);
+
+ ///
+ /// @brief Schedule async reload for a config key
+ ///
+ /// Creates a ScheduledReloadContinuation on ET_TASK.
+ /// If content was set via set_passed_config(), it will be used (rpc reload).
+ /// Otherwise, handler reads from file.
+ ///
+ /// @param key The registered config key
+ ///
+ void schedule_reload(const std::string &key);
+
+ ///
+ /// @brief Execute reload for a key (called by ScheduledReloadContinuation)
+ ///
+ /// Checks for rpc-supplied content, creates context, calls handler.
+ /// Internal use - called from continuation on ET_TASK thread.
+ ///
+ /// @param key The config key to reload
+ ///
+ void execute_reload(const std::string &key);
+
+ /// look up.
+ bool contains(const std::string &key) const;
+ Entry const *find(const std::string &key) const;
+
+ /// Callback context for RecRegisterConfigUpdateCb (public for callback access)
+ struct TriggerContext {
+ std::string config_key;
+ Ptr<ProxyMutex> mutex;
+ };
+
+private:
+ ConfigRegistry() = default;
+ ~ConfigRegistry() = default;
+
+ // Non-copyable
+ ConfigRegistry(ConfigRegistry const &) = delete;
+ ConfigRegistry &operator=(ConfigRegistry const &) = delete;
+
+ /// Internal: common registration logic
+ void do_register(Entry entry);
+
+ /// Internal: setup trigger callbacks for an entry
+ void setup_triggers(Entry &entry);
+
+ /// Internal: wire a record callback to fire on_record_change for a config key.
+ /// Does NOT modify trigger_records — callers decide whether to store the record.
+ int wire_record_callback(const char *record_name, const std::string &config_key);
+
+ /// Hash for lookup.
+ struct StringHash {
+ using is_transparent = void;
+ size_t
+ operator()(std::string_view sv) const
+ {
+ return std::hash<std::string_view>{}(sv);
+ }
+ size_t
+ operator()(std::string const &s) const
+ {
+ return std::hash<std::string>{}(s);
+ }
+ };
+
+ mutable std::shared_mutex _mutex;
+ std::unordered_map<std::string, Entry, StringHash, std::equal_to<>> _entries;
+ std::unordered_map<std::string, YAML::Node, StringHash, std::equal_to<>> _passed_configs;
+ /// Maps dependency keys to their parent entry's key.
+ ///
+ /// When a coordinator entry manages multiple configuration files, each file can
+ /// be given a dependency key via add_file_and_node_dependency(). This allows
+ /// resolve() to route RPC-supplied content for a dependency key back to the
+ /// parent coordinator's handler, so a single reload fires for all related files.
+ std::unordered_map<std::string, std::string, StringHash, std::equal_to<>> _dep_key_to_parent;
+};
+
+} // namespace config
diff --git a/include/mgmt/config/ConfigReloadErrors.h b/include/mgmt/config/ConfigReloadErrors.h
new file mode 100644
index 0000000000..7b1fdcdfcd
--- /dev/null
+++ b/include/mgmt/config/ConfigReloadErrors.h
@@ -0,0 +1,53 @@
+/** @file
+
+ Config reload error codes — shared between server (Configuration.cc) and client (CtrlCommands.cc).
+
+ @section license License
+
+ Licensed to the Apache Software Foundation (ASF) under one
+ or more contributor license agreements. See the NOTICE file
+ distributed with this work for additional information
+ regarding copyright ownership. The ASF licenses this file
+ to you under the Apache License, Version 2.0 (the
+ "License"); you may not use this file except in compliance
+ with the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+*/
+
+#pragma once
+
+namespace config::reload::errors
+{
+/// Error codes for config reload RPC operations.
+/// Used in the YAML error nodes exchanged between traffic_server and traffic_ctl.
+///
+/// Range 6001–6099: general reload lifecycle errors
+/// Range 6010–6019: per-config validation errors
+enum class ConfigReloadError : int {
+ // --- General reload errors ---
+ TOKEN_NOT_FOUND = 6001, ///< Requested token does not exist in history
+ TOKEN_ALREADY_EXISTS = 6002, ///< Token name already in use
+ RELOAD_TASK_FAILED = 6003, ///< Failed to create or kick off reload task
+ RELOAD_IN_PROGRESS = 6004, ///< A reload is already running (use --force to override)
+ NO_RELOAD_TASKS = 6005, ///< No reload tasks found in history
+
+ // --- Per-config validation errors ---
+ CONFIG_NOT_REGISTERED = 6010, ///< Config key not found in ConfigRegistry
+ RPC_SOURCE_NOT_SUPPORTED = 6011, ///< Config does not support RPC as a content source
+ CONFIG_NO_HANDLER = 6012, ///< Config is registered but has no reload handler
+};
+
+/// Helper to convert enum to int for YAML node construction
+constexpr int
+to_int(ConfigReloadError e)
+{
+ return static_cast<int>(e);
+}
+} // namespace config::reload::errors
diff --git a/src/iocore/net/P_SSLClientCoordinator.h b/include/mgmt/config/ConfigReloadExecutor.h
similarity index 52%
copy from src/iocore/net/P_SSLClientCoordinator.h
copy to include/mgmt/config/ConfigReloadExecutor.h
index 51899cd0c5..9a146ea4e0 100644
--- a/src/iocore/net/P_SSLClientCoordinator.h
+++ b/include/mgmt/config/ConfigReloadExecutor.h
@@ -1,6 +1,6 @@
/** @file
- P_SSLClientCoordinator.h - coordinate the loading of SSL related configs
+ Config reload execution logic - schedules async reload work on ET_TASK.
@section license License
@@ -21,11 +21,23 @@
limitations under the License.
*/
-// A class to pass the ConfigUpdateHandler, so both SSLConfig and SNIConfig get updated
-// when the relevant files/configs get updated.
-class SSLClientCoordinator
+#pragma once
+
+#include <chrono>
+
+namespace config
{
-public:
- static void startup();
- static void reconfigure();
-};
+
+/// Schedule the config reload work to be executed on the ET_TASK thread.
+///
+/// This function schedules the actual reload work which includes:
+/// - Calling FileManager::rereadConfig() to detect and reload changed files
+/// - Calling FileManager::invokeConfigPluginCallbacks() to notify registered plugins
+///
+/// The reload status is tracked via ReloadCoordinator which must have been
+/// initialized with a task before calling this function.
+///
+/// @param delay Delay before executing the reload (default: 10ms)
+void schedule_reload_work(std::chrono::milliseconds delay = std::chrono::milliseconds{10});
+
+} // namespace config
diff --git a/include/mgmt/config/ConfigReloadTrace.h b/include/mgmt/config/ConfigReloadTrace.h
new file mode 100644
index 0000000000..e52078e0b9
--- /dev/null
+++ b/include/mgmt/config/ConfigReloadTrace.h
@@ -0,0 +1,367 @@
+/** @file
+ *
+ * ConfigReloadTrace - Reload task tracking and progress reporting
+ *
+ * @section license License
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+#include <atomic>
+#include <chrono>
+#include <string_view>
+#include <string>
+#include <mutex>
+#include <shared_mutex>
+#include <iostream>
+
+#include <swoc/Errata.h>
+#include <tscore/ink_platform.h>
+#include "iocore/eventsystem/Continuation.h"
+#include "iocore/eventsystem/EventSystem.h"
+#include "iocore/eventsystem/Event.h"
+#include "iocore/eventsystem/Tasks.h"
+#include "tscore/Diags.h"
+
+class ConfigReloadTask;
+class ConfigContext;
+
+namespace YAML
+{
+template <typename T> struct convert;
+} // namespace YAML
+
+using ConfigReloadTaskPtr = std::shared_ptr<ConfigReloadTask>;
+
+///
+/// @brief Progress checker for reload tasks — detects stuck/hanging tasks.
+///
+/// Created per-reload by ConfigReloadTask::start_progress_checker(), which is called
+/// only for main tasks in the IN_PROGRESS state. Each instance is bound to a single
+/// ConfigReloadTask and holds a shared_ptr to it.
+///
+/// Lifecycle:
+/// - Scheduled on ET_TASK when a reload starts.
+/// - check_progress() runs periodically (every check_interval).
+/// - Self-terminates (returns EVENT_DONE) when:
+/// * The task reaches a terminal state (SUCCESS, FAIL, TIMEOUT).
+/// * The task exceeds the configured timeout (marked as TIMEOUT, then stops).
+/// * The _reload pointer is null (defensive).
+/// - Reschedules itself (EVENT_CONT) only while the task is still non-terminal.
+/// - No idle polling — when no reload is in progress, no checker exists.
+///
+/// Configurable via records:
+/// - proxy.config.admin.reload.timeout: Duration string (default: "1h")
+/// Supports: "30s", "5min", "1h", "1 hour 30min", "0" (disabled)
+/// - proxy.config.admin.reload.check_interval: Duration string (default: "2s")
+/// Minimum: 1s (enforced). How often to check task progress.
+///
+/// If timeout is 0 or empty, timeout is disabled. Tasks can hang forever (BAD).
+/// Use --force (traffic_ctl / RPC API) flag to bypass the in-progress guard and start a new reload.
+/// Note: --force only marks the existing tracking task as stale; it does not cancel the actual work.
+///
+struct ConfigReloadProgress : public Continuation {
+ /// Record names for configuration
+ static constexpr std::string_view RECORD_TIMEOUT = "proxy.config.admin.reload.timeout";
+ static constexpr std::string_view RECORD_CHECK_INTERVAL = "proxy.config.admin.reload.check_interval";
+
+ /// Defaults
+ static constexpr std::string_view DEFAULT_TIMEOUT = "1h"; ///< 1 hour
+ static constexpr std::string_view DEFAULT_CHECK_INTERVAL = "2s"; ///< 2 seconds
+ static constexpr int64_t MIN_CHECK_INTERVAL_MS = 1000; ///< 1 second minimum
+
+ ConfigReloadProgress(ConfigReloadTaskPtr reload);
+ int check_progress(int /* etype */, void * /* data */);
+
+ /// Read timeout value from records, returns 0ms if disabled or invalid
+ [[nodiscard]] static std::chrono::milliseconds get_configured_timeout();
+
+ /// Read check interval from records, enforces minimum of 1s
+ [[nodiscard]] static std::chrono::milliseconds get_configured_check_interval();
+
+ /// Get the check interval for this instance
+ [[nodiscard]] std::chrono::milliseconds
+ get_check_interval() const
+ {
+ return _every;
+ }
+
+private:
+ /// Grace period before accepting a terminal state as final. A late reserve_subtask()
+ /// can pull the parent back from SUCCESS to IN_PROGRESS; this delay lets the checker
+ /// detect that transition instead of stopping prematurely.
+ static constexpr std::chrono::milliseconds TERMINAL_CONFIRMATION_DELAY{5000};
+ ConfigReloadTaskPtr _reload{nullptr};
+ std::chrono::milliseconds _every{std::chrono::seconds{2}}; ///< Set from config in constructor
+ bool _awaiting_terminal_confirmation{false}; ///< true after first terminal observation
+};
+
+///
+/// @brief Tracks the status and progress of a single config reload operation.
+///
+/// Represents either a top-level (main) reload task or a sub-task for an individual
+/// config module. Tasks form a tree: the main task has sub-tasks for each config,
+/// and sub-tasks can themselves have children (e.g., SSLClientCoordinator → SSLConfig, SNIConfig).
+///
+/// State flows: CREATED → IN_PROGRESS → SUCCESS / FAIL / TIMEOUT
+/// Parent tasks aggregate state from their children automatically.
+///
+/// Serialized to YAML via YAML::convert<ConfigReloadTask::Info> for RPC responses.
+///
+class ConfigReloadTask : public std::enable_shared_from_this<ConfigReloadTask>
+{
+public:
+ enum class State {
+ INVALID = -1,
+ CREATED, ///< Initial state — task exists but not started
+ IN_PROGRESS, ///< Work is actively happening
+ SUCCESS, ///< Terminal: completed successfully
+ FAIL, ///< Terminal: error occurred
+ TIMEOUT ///< Terminal: task exceeded time limit
+ };
+
+ /// Check if a state represents a terminal (final) state
+ [[nodiscard]] static constexpr bool
+ is_terminal(State s) noexcept
+ {
+ return s == State::SUCCESS || s == State::FAIL || s == State::TIMEOUT;
+ }
+
+ /// Convert State enum to string
+ [[nodiscard]] static constexpr std::string_view
+ state_to_string(State s) noexcept
+ {
+ switch (s) {
+ case State::INVALID:
+ return "invalid";
+ case State::CREATED:
+ return "created";
+ case State::IN_PROGRESS:
+ return "in_progress";
+ case State::SUCCESS:
+ return "success";
+ case State::FAIL:
+ return "fail";
+ case State::TIMEOUT:
+ return "timeout";
+ }
+ return "unknown";
+ }
+
+ /// Helper to get current time in milliseconds since epoch
+ [[nodiscard]] static int64_t
+ now_ms()
+ {
+ return std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count();
+ }
+
+ struct Info {
+ friend class ConfigReloadTask;
+ /// Grant friendship to the specific YAML::convert specialization.
+ friend struct YAML::convert<ConfigReloadTask::Info>;
+ Info() = default;
+ Info(State p_state, std::string_view p_token, std::string_view p_description, bool p_main_task)
+ : state(p_state), token(p_token), description(p_description), main_task(p_main_task)
+ {
+ }
+
+ protected:
+ int64_t created_time_ms{now_ms()}; ///< milliseconds since epoch
+ int64_t last_updated_time_ms{now_ms()}; ///< last time this task was updated (ms)
+ std::vector<std::string> logs; ///< log messages from handler
+ State state{State::CREATED};
+ std::string token;
+ std::string description;
+ std::string config_key; ///< registry key for dedup (empty for main/child tasks)
+ std::string filename; ///< source file, if applicable
+ std::vector<ConfigReloadTaskPtr> sub_tasks; ///< child tasks (if any)
+ bool main_task{false}; ///< true for the top-level reload task
+ };
+
+ using self_type = ConfigReloadTask;
+ ConfigReloadTask() = default;
+ ConfigReloadTask(std::string_view token, std::string_view description, bool main_task, ConfigReloadTaskPtr parent)
+ : _info(State::CREATED, token, description, main_task), _parent{parent}
+ {
+ if (_info.main_task) {
+ _info.state = State::IN_PROGRESS;
+ }
+ }
+
+ /// Start the periodic progress checker (ConfigReloadProgress).
+ /// Only runs once, and only for main tasks. The checker detects stuck tasks
+ /// and marks them as TIMEOUT if they exceed the configured time limit.
+ void start_progress_checker();
+
+ /// Create a child sub-task and return a ConfigContext wrapping it.
+ /// The child inherits the parent's token and if passed, the supplied YAML content.
+ [[nodiscard]] ConfigContext add_child(std::string_view description = "");
+
+ self_type &log(std::string const &text);
+ void set_completed();
+ void set_failed();
+ void set_in_progress();
+
+ void
+ set_description(std::string_view description)
+ {
+ std::unique_lock<std::shared_mutex> lock(_mutex);
+ _info.description = description;
+ }
+
+ [[nodiscard]] std::string
+ get_description() const
+ {
+ std::shared_lock<std::shared_mutex> lock(_mutex);
+ return _info.description;
+ }
+
+ void
+ set_filename(std::string_view filename)
+ {
+ std::unique_lock<std::shared_mutex> lock(_mutex);
+ _info.filename = filename;
+ }
+
+ [[nodiscard]] std::string
+ get_filename() const
+ {
+ std::shared_lock<std::shared_mutex> lock(_mutex);
+ return _info.filename;
+ }
+
+ void
+ set_config_key(std::string_view key)
+ {
+ std::unique_lock<std::shared_mutex> lock(_mutex);
+ _info.config_key = key;
+ }
+
+ /// Check if any immediate subtask has the given config_key.
+ /// Used by ReloadCoordinator to prevent duplicate subtasks within a single reload cycle.
+ [[nodiscard]] bool has_subtask_for_key(std::string_view key) const;
+
+ /// Find a subtask by its config_key. Returns nullptr if not found.
+ [[nodiscard]] ConfigReloadTaskPtr find_subtask_by_key(std::string_view key) const;
+
+ /// Debug utility: dump task tree to an output stream.
+ /// Recursively prints this task and all sub-tasks with indentation.
+
+ [[nodiscard]] bool
+ contains_dependents() const
+ {
+ std::shared_lock<std::shared_mutex> lock(_mutex);
+ return !_info.sub_tasks.empty();
+ }
+
+ /// Get created time in seconds (for Date formatting and metrics).
+ /// No lock needed — created_time_ms is immutable after construction.
+ [[nodiscard]] std::time_t
+ get_created_time() const
+ {
+ return static_cast<std::time_t>(
+ std::chrono::duration_cast<std::chrono::seconds>(std::chrono::milliseconds{_info.created_time_ms}).count());
+ }
+
+ /// Get created time in milliseconds since epoch.
+ /// No lock needed — created_time_ms is immutable after construction.
+ [[nodiscard]] int64_t
+ get_created_time_ms() const
+ {
+ return _info.created_time_ms;
+ }
+
+ [[nodiscard]] State
+ get_state() const
+ {
+ std::shared_lock<std::shared_mutex> lock(_mutex);
+ return _info.state;
+ }
+
+ /// Mark task as TIMEOUT with an optional reason logged
+ void mark_as_bad_state(std::string_view reason = "");
+
+ [[nodiscard]] std::vector<std::string>
+ get_logs() const
+ {
+ std::shared_lock<std::shared_mutex> lock(_mutex);
+ return _info.logs;
+ }
+
+ [[nodiscard]] std::string
+ get_token() const
+ {
+ std::shared_lock<std::shared_mutex> lock(_mutex);
+ return _info.token;
+ }
+
+ [[nodiscard]] bool
+ is_main_task() const
+ {
+ std::shared_lock<std::shared_mutex> lock(_mutex);
+ return _info.main_task;
+ }
+
+ /// Create a copy of the current task info
+ [[nodiscard]] Info
+ get_info() const
+ {
+ std::shared_lock<std::shared_mutex> lock(_mutex);
+ Info copy = _info;
+ copy.last_updated_time_ms = _atomic_last_updated_ms.load(std::memory_order_acquire);
+ return copy;
+ }
+
+ /// Get last updated time in seconds (considers subtasks)
+ [[nodiscard]] std::time_t get_last_updated_time() const;
+
+ /// Get last updated time in milliseconds (considers subtasks)
+ [[nodiscard]] int64_t get_last_updated_time_ms() const;
+
+ void
+ update_last_updated_time()
+ {
+ _atomic_last_updated_ms.store(now_ms(), std::memory_order_release);
+ }
+
+ /// Read the last updated time for this task only (no subtask traversal, lock-free)
+ [[nodiscard]] int64_t
+ get_own_last_updated_time_ms() const
+ {
+ return _atomic_last_updated_ms.load(std::memory_order_acquire);
+ }
+
+private:
+ /// Add a pre-created sub-task to this task's children list.
+ /// Called by ReloadCoordinator::create_config_context().
+ void add_sub_task(ConfigReloadTaskPtr sub_task);
+ void on_sub_task_update(State state);
+ void aggregate_status();
+ void notify_parent();
+ void set_state_and_notify(State state);
+
+ mutable std::shared_mutex _mutex;
+ bool _reload_progress_checker_started{false};
+ Info _info;
+ ConfigReloadTaskPtr _parent; ///< parent task, if any
+
+ std::atomic<int64_t> _atomic_last_updated_ms{now_ms()};
+
+ friend class ReloadCoordinator;
+};
diff --git a/include/mgmt/config/FileManager.h b/include/mgmt/config/FileManager.h
index 57b115321b..0d44cc4714 100644
--- a/include/mgmt/config/FileManager.h
+++ b/include/mgmt/config/FileManager.h
@@ -36,8 +36,6 @@
#include <mgmt/rpc/jsonrpc/JsonRPC.h>
-class ConfigUpdateCbTable;
-
class FileManager
{
public:
@@ -142,7 +140,7 @@ public:
bool isConfigStale();
void configFileChild(const char *parent, const char *child);
- void registerConfigPluginCallbacks(ConfigUpdateCbTable *cblist);
+ void registerConfigPluginCallbacks(std::function<void()> cb);
void invokeConfigPluginCallbacks();
static FileManager &
@@ -155,8 +153,8 @@ public:
private:
FileManager();
- ink_mutex accessLock; // Protects bindings hashtable
- ConfigUpdateCbTable *_pluginCallbackList{nullptr};
+ ink_mutex accessLock; // Protects bindings hashtable
+ std::function<void()> _pluginCallback;
std::mutex _callbacksMutex;
std::mutex _accessMutex;
@@ -169,5 +167,3 @@ private:
/// JSONRPC endpoint
swoc::Rv<YAML::Node> get_files_registry_rpc_endpoint(std::string_view const &id, YAML::Node const ¶ms);
};
-
-void initializeRegistry(); // implemented in AddConfigFilesHere.cc
diff --git a/include/mgmt/config/ReloadCoordinator.h b/include/mgmt/config/ReloadCoordinator.h
new file mode 100644
index 0000000000..8dd1adfa26
--- /dev/null
+++ b/include/mgmt/config/ReloadCoordinator.h
@@ -0,0 +1,124 @@
+/** @file
+ *
+ * ReloadCoordinator - Manages config reload lifecycle and concurrency
+ *
+ * @section license License
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+#include <string_view>
+#include <string>
+
+#include <mutex>
+#include <shared_mutex>
+#include <swoc/Errata.h>
+#include <tscore/ink_platform.h>
+#include "tscore/Diags.h"
+#include "mgmt/config/ConfigReloadTrace.h"
+#include "mgmt/config/ConfigContext.h"
+
+class ReloadCoordinator
+{
+public:
+ /// Initialize a new reload session. Generates a token, checks for in-progress reloads,
+ /// and creates the main tracking task. Use --force to bypass the in-progress guard.
+ [[nodiscard]] swoc::Errata prepare_reload(std::string &token_name, const char *token_prefix = "rldtk-", bool force = false);
+
+ /// Return snapshots of the last N reload tasks (0 = all). Most recent first.
+ [[nodiscard]] std::vector<ConfigReloadTask::Info> get_all(std::size_t N = 0) const;
+
+ /// Look up a reload task by its token. Returns {found, info_snapshot}.
+ [[nodiscard]] std::pair<bool, ConfigReloadTask::Info> find_by_token(std::string_view token) const;
+
+ /// Singleton access
+ static ReloadCoordinator &
+ Get_Instance()
+ {
+ static ReloadCoordinator instance;
+ return instance;
+ }
+
+ [[nodiscard]] std::shared_ptr<ConfigReloadTask>
+ get_current_task() const
+ {
+ std::shared_lock lock(_mutex);
+ return _current_task;
+ }
+
+ /// Create a sub-task context for the given config key.
+ ///
+ /// Deduplication: if a subtask with the same @a config_key already exists on the
+ /// current main task, returns an empty ConfigContext (operator bool() == false).
+ /// This prevents the same handler from running multiple times in a single reload
+ /// cycle when multiple trigger records map to the same config key.
+ ///
+ /// @see ConfigRegistry::setup_triggers() — N trigger records produce N callbacks.
+ [[nodiscard]] ConfigContext create_config_context(std::string_view config_key, std::string_view description = "",
+ std::string_view filename = "");
+
+ [[nodiscard]] bool is_reload_in_progress() const;
+
+ [[nodiscard]] bool
+ has_token(std::string_view token_name) const
+ {
+ std::shared_lock lock(_mutex);
+ return std::any_of(_history.begin(), _history.end(),
+ [&token_name](const std::shared_ptr<ConfigReloadTask> &task) { return task->get_token() == token_name; });
+ }
+
+ ///
+ /// @brief Mark a reload task as stale/superseded
+ ///
+ /// Used internally when --force flag (jsonrpc or traffic_ctl) is specified to mark the current
+ /// in-progress task as stale before starting a new one.
+ ///
+ /// Note: This does NOT stop running handlers. Any handlers actively
+ /// processing will continue. This only updates the task tracking status
+ /// so we can spawn another reload task. Use with caution.
+ ///
+ /// @param token The token of the task to mark stale (empty = current task)
+ /// @param reason Reason for marking stale (will be logged)
+ /// @return true if task was found and marked, false otherwise
+ ///
+ bool mark_task_as_stale(std::string_view token = "", std::string_view reason = "Superseded by new reload");
+
+ /// Pre-register a CREATED subtask for the given config key on the current main task.
+ /// Called by on_record_change() during the synchronous RecExecConfigUpdateCbs flush
+ /// to reserve a placeholder before the handler continuation is scheduled on ET_TASK.
+ /// If no reload is active or the subtask already exists, this is a no-op.
+ void reserve_subtask(std::string_view config_key);
+
+private:
+ static constexpr size_t MAX_HISTORY_SIZE = 100; ///< Maximum number of reload tasks to keep in history. TODO: maybe configurable?
+
+ /// Create main task (caller must hold unique lock)
+ void create_main_config_task(std::string_view token, std::string description);
+
+ std::string generate_token_name(const char *prefix) const;
+
+ std::vector<std::shared_ptr<ConfigReloadTask>> _history;
+ std::shared_ptr<ConfigReloadTask> _current_task;
+ mutable std::shared_mutex _mutex;
+
+ // Prevent construction/copying from outside
+ ReloadCoordinator() = default;
+ ReloadCoordinator(const ReloadCoordinator &) = delete;
+ ReloadCoordinator &operator=(const ReloadCoordinator &) = delete;
+};
diff --git a/include/mgmt/rpc/handlers/config/Configuration.h b/include/mgmt/rpc/handlers/config/Configuration.h
index e6f00b5aea..29cfee5e86 100644
--- a/include/mgmt/rpc/handlers/config/Configuration.h
+++ b/include/mgmt/rpc/handlers/config/Configuration.h
@@ -24,7 +24,40 @@
namespace rpc::handlers::config
{
+/// Only records.yaml config.
swoc::Rv<YAML::Node> set_config_records(std::string_view const &id, YAML::Node const ¶ms);
+
+/**
+ * @brief Unified config reload handler — supports file source and RPC source modes.
+ *
+ * File source (default):
+ * Reloads all changed config files from disk (on-disk configuration).
+ * Params:
+ * token: optional custom reload token
+ * force: force reload even if one is in progress
+ *
+ * RPC source (when "configs" param present):
+ * Reloads specific configs using YAML content injected through the RPC call,
+ * bypassing on-disk files.
+ * Params:
+ * token: optional custom reload token
+ * configs: map of config_key -> yaml_content
+ * e.g.:
+ * configs:
+ * ip_allow:
+ * - apply: in
+ * ip_addrs: 0.0.0.0/0
+ * sni:
+ * - fqdn: '*.example.com'
+ *
+ * Response:
+ * token: reload task token
+ * created_time: task creation timestamp
+ * message: status message
+ * errors: array of errors (if any)
+ */
swoc::Rv<YAML::Node> reload_config(std::string_view const &id, YAML::Node const ¶ms);
+swoc::Rv<YAML::Node> get_reload_config_status(std::string_view const &id, YAML::Node const ¶ms);
+
} // namespace rpc::handlers::config
diff --git a/include/proxy/CacheControl.h b/include/proxy/CacheControl.h
index fcd789634b..15ff1e60e6 100644
--- a/include/proxy/CacheControl.h
+++ b/include/proxy/CacheControl.h
@@ -33,6 +33,7 @@
#include "iocore/eventsystem/EventSystem.h"
#include "proxy/ControlBase.h"
#include "tscore/Result.h"
+#include "mgmt/config/ConfigContext.h"
struct RequestData;
@@ -127,4 +128,4 @@ bool host_rule_in_CacheControlTable();
bool ip_rule_in_CacheControlTable();
void initCacheControl();
-void reloadCacheControl();
+void reloadCacheControl(ConfigContext ctx);
diff --git a/include/proxy/IPAllow.h b/include/proxy/IPAllow.h
index 9d707247a0..f354c1faaa 100644
--- a/include/proxy/IPAllow.h
+++ b/include/proxy/IPAllow.h
@@ -40,8 +40,6 @@
#include "swoc/swoc_ip.h"
#include "swoc/Errata.h"
-// forward declare in name only so it can be a friend.
-struct IpAllowUpdate;
namespace YAML
{
class Node;
@@ -206,7 +204,7 @@ public:
static ACL match(sockaddr const *sa, match_key_t key);
static void startup();
- static void reconfigure();
+ static void reconfigure(ConfigContext ctx = {});
/// @return The global instance.
static IpAllow *acquire();
/// Release the configuration.
diff --git a/include/proxy/ParentSelection.h b/include/proxy/ParentSelection.h
index 5960cfda18..a8fd0143a8 100644
--- a/include/proxy/ParentSelection.h
+++ b/include/proxy/ParentSelection.h
@@ -430,7 +430,7 @@ class HttpRequestData;
struct ParentConfig {
public:
static void startup();
- static void reconfigure();
+ static void reconfigure(ConfigContext ctx = {});
static void print();
static void set_parent_table(P_table *pTable, ParentRecord *rec, int num_elements);
diff --git a/include/proxy/ReverseProxy.h b/include/proxy/ReverseProxy.h
index e7aca26ca0..20cf5a0cea 100644
--- a/include/proxy/ReverseProxy.h
+++ b/include/proxy/ReverseProxy.h
@@ -39,6 +39,7 @@
#include "proxy/http/remap/RemapPluginInfo.h"
#include "proxy/http/remap/UrlRewrite.h"
#include "proxy/http/remap/UrlMapping.h"
+#include "mgmt/config/ConfigContext.h"
#define EMPTY_PORT_MAPPING (int32_t) ~0
@@ -54,7 +55,7 @@ mapping_type request_url_remap_redirect(HTTPHdr *request_header, URL *redirect_u
bool response_url_remap(HTTPHdr *response_header, UrlRewrite *table);
// Reload Functions
-bool reloadUrlRewrite();
+bool reloadUrlRewrite(ConfigContext ctx);
bool urlRewriteVerify();
int url_rewrite_CB(const char *name, RecDataT data_type, RecData data, void *cookie);
diff --git a/include/proxy/http/PreWarmConfig.h b/include/proxy/http/PreWarmConfig.h
index 2ff2535b95..24675e0e14 100644
--- a/include/proxy/http/PreWarmConfig.h
+++ b/include/proxy/http/PreWarmConfig.h
@@ -43,14 +43,13 @@ public:
static void startup();
- // ConfigUpdateContinuation interface
- static void reconfigure();
+ // ConfigRegistry reload handler
+ static void reconfigure(ConfigContext ctx = {});
// ConfigProcessor::scoped_config interface
static PreWarmConfigParams *acquire();
static void release(PreWarmConfigParams *params);
private:
- inline static int _config_id = 0;
- inline static std::unique_ptr<ConfigUpdateHandler<PreWarmConfig>> _config_update_handler;
+ inline static int _config_id = 0;
};
diff --git a/include/proxy/logging/LogConfig.h b/include/proxy/logging/LogConfig.h
index 47a83d7693..d891cf0b23 100644
--- a/include/proxy/logging/LogConfig.h
+++ b/include/proxy/logging/LogConfig.h
@@ -34,6 +34,7 @@
#include "proxy/logging/RolledLogDeleter.h"
#include "swoc/MemSpan.h"
#include "tsutil/Metrics.h"
+#include "mgmt/config/ReloadCoordinator.h"
using ts::Metrics;
@@ -103,11 +104,14 @@ public:
void display(FILE *fd = stdout);
void setup_log_objects();
- static int reconfigure(const char *name, RecDataT data_type, RecData data, void *cookie);
+ // static int reconfigure(const char *name, RecDataT data_type, RecData data, void *cookie);
+ static void reconfigure(ConfigContext ctx = {}); // ConfigRegistry reload handler
static void register_config_callbacks();
static void register_stat_callbacks();
+ ConfigContext reload_ctx; ///< Tracks reload status;
+
bool space_to_write(int64_t bytes_to_write) const;
bool
diff --git a/include/records/RecCore.h b/include/records/RecCore.h
index d0a6ed5b4f..67e3ba2f6f 100644
--- a/include/records/RecCore.h
+++ b/include/records/RecCore.h
@@ -29,6 +29,7 @@
#include "tscore/Diags.h"
#include "records/RecDefs.h"
+#include "mgmt/config/ConfigContext.h"
#include "swoc/MemSpan.h"
struct RecRecord;
@@ -244,9 +245,17 @@ RecErrT RecGetRecordPersistenceType(const char *name, RecPersistT *persist_type,
RecErrT RecGetRecordSource(const char *name, RecSourceT *source, bool lock = true);
/// Generate a warning if any configuration name/value is not registered.
-void RecConfigWarnIfUnregistered();
+// void RecConfigWarnIfUnregistered();
+/// Generate a warning if any configuration name/value is not registered.
+void RecConfigWarnIfUnregistered(ConfigContext ctx = {});
//------------------------------------------------------------------------
// Set RecRecord attributes
//------------------------------------------------------------------------
RecErrT RecSetSyncRequired(const char *name, bool lock = true);
+
+/// Flush pending record config-update callbacks (those marked sync-required).
+/// This forces immediate execution of RecConfigUpdateCb callbacks for dirty records,
+/// rather than waiting for the next config_update_cont timer tick (~3s).
+/// After this call the sync-required flag on those records is cleared.
+void RecFlushConfigUpdateCbs();
diff --git a/include/records/YAMLConfigReloadTaskEncoder.h b/include/records/YAMLConfigReloadTaskEncoder.h
new file mode 100644
index 0000000000..5aee5a7bca
--- /dev/null
+++ b/include/records/YAMLConfigReloadTaskEncoder.h
@@ -0,0 +1,69 @@
+/** @file
+
+ YAML encoder for ConfigReloadTask::Info — serializes reload task snapshots to YAML nodes
+ for JSONRPC responses.
+
+ @section license License
+
+ Licensed to the Apache Software Foundation (ASF) under one
+ or more contributor license agreements. See the NOTICE file
+ distributed with this work for additional information
+ regarding copyright ownership. The ASF licenses this file
+ to you under the Apache License, Version 2.0 (the
+ "License"); you may not use this file except in compliance
+ with the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+ */
+
+#pragma once
+#include <string>
+#include <memory>
+#include <vector>
+#include <iostream>
+#include <swoc/Errata.h>
+#include <tscore/ink_platform.h>
+#include <yaml-cpp/yaml.h>
+
+#include "mgmt/config/ReloadCoordinator.h"
+
+namespace YAML
+{
+template <> struct convert<ConfigReloadTask::Info> {
+ static Node
+ encode(const ConfigReloadTask::Info &info)
+ {
+ Node node;
+ node["config_token"] = info.token;
+ node["status"] = std::string(ConfigReloadTask::state_to_string(info.state));
+ node["description"] = info.description;
+ node["config_key"] = info.config_key;
+ node["filename"] = info.filename;
+ auto meta = YAML::Node(YAML::NodeType::Map);
+ meta["created_time_ms"] = info.created_time_ms;
+ meta["last_updated_time_ms"] = info.last_updated_time_ms;
+ meta["main_task"] = info.main_task ? "true" : "false";
+
+ node["meta"] = meta;
+
+ node["logs"] = YAML::Node(YAML::NodeType::Sequence);
+ // if no logs, it will be empty sequence.
+ for (const auto &log : info.logs) {
+ node["logs"].push_back(log);
+ }
+
+ node["sub_tasks"] = YAML::Node(YAML::NodeType::Sequence);
+ for (const auto &sub_task : info.sub_tasks) {
+ node["sub_tasks"].push_back(sub_task->get_info());
+ }
+ return node;
+ }
+};
+
+} // namespace YAML
diff --git a/include/shared/rpc/yaml_codecs.h b/include/shared/rpc/yaml_codecs.h
index 1e61742a51..d719973f31 100644
--- a/include/shared/rpc/yaml_codecs.h
+++ b/include/shared/rpc/yaml_codecs.h
@@ -33,7 +33,7 @@ namespace helper
// traffic_ctl display something.
template <typename T>
inline auto
-try_extract(YAML::Node const &node, const char *name, bool throwOnFail = false)
+try_extract(YAML::Node const &node, const char *name, bool throwOnFail = false, T def = T{}) -> T
{
try {
if (auto n = node[name]) {
@@ -44,8 +44,9 @@ try_extract(YAML::Node const &node, const char *name, bool throwOnFail = false)
throw ex;
}
}
- return T{};
+ return def;
}
+
} // namespace helper
/**
* YAML namespace. All json rpc request codecs can be placed here. It will read all the definitions from "requests.h"
diff --git a/include/tscore/ArgParser.h b/include/tscore/ArgParser.h
index a4bd5916fe..a29c87148d 100644
--- a/include/tscore/ArgParser.h
+++ b/include/tscore/ArgParser.h
@@ -226,6 +226,8 @@ public:
void validate_mutex_groups(Arguments &ret) const;
// Helper method to validate option dependencies
void validate_dependencies(Arguments &ret) const;
+ // Helper method to apply default values for options not explicitly set
+ void apply_option_defaults(Arguments &ret);
// The command name and help message
std::string _name;
std::string _description;
diff --git a/src/cripts/CMakeLists.txt b/src/cripts/CMakeLists.txt
index 6e151f46f3..808b983570 100644
--- a/src/cripts/CMakeLists.txt
+++ b/src/cripts/CMakeLists.txt
@@ -60,7 +60,7 @@ set(CRIPTS_BUNDLE_HEADERS
add_library(cripts SHARED ${CPP_FILES})
add_library(ts::cripts ALIAS cripts)
-target_link_libraries(cripts PUBLIC libswoc::libswoc OpenSSL::Crypto fmt::fmt PkgConfig::PCRE2)
+target_link_libraries(cripts PUBLIC libswoc::libswoc OpenSSL::Crypto fmt::fmt PkgConfig::PCRE2 yaml-cpp::yaml-cpp)
set_target_properties(cripts PROPERTIES PUBLIC_HEADER "${CRIPTS_PUBLIC_HEADERS}")
set_target_properties(
diff --git a/src/iocore/aio/CMakeLists.txt b/src/iocore/aio/CMakeLists.txt
index 4f6f4bc0b8..3d06b67ae1 100644
--- a/src/iocore/aio/CMakeLists.txt
+++ b/src/iocore/aio/CMakeLists.txt
@@ -27,7 +27,7 @@ endif()
if(BUILD_TESTING)
add_executable(test_AIO test_AIO.cc)
- target_link_libraries(test_AIO ts::aio)
+ target_link_libraries(test_AIO ts::aio configmanager)
add_test(
NAME test_AIO
COMMAND $<TARGET_FILE:test_AIO>
diff --git a/src/iocore/cache/Cache.cc b/src/iocore/cache/Cache.cc
index 512a5e7bf7..aeb5cb2e98 100644
--- a/src/iocore/cache/Cache.cc
+++ b/src/iocore/cache/Cache.cc
@@ -31,6 +31,7 @@
#include "Stripe.h"
#include "StripeSM.h"
#include "iocore/cache/Cache.h"
+#include "mgmt/config/ConfigRegistry.h"
#include "tscore/Filenames.h"
#include "tscore/InkErrno.h"
#include "tscore/Layout.h"
@@ -227,7 +228,25 @@ Cache::open_done()
{
CacheHostTable *hosttable_raw = new CacheHostTable(this, scheme);
hosttable.reset(hosttable_raw);
- hosttable_raw->register_config_callback(&hosttable);
+
+ auto *ppt = &this->hosttable;
+ config::ConfigRegistry::Get_Instance().register_config( // late config registration
+ "cache_hosting", // registry key
+ ts::filename::HOSTING, // default filename
+ "proxy.config.cache.hosting_filename", // record holding the filename
+ [ppt](ConfigContext ctx) { // reload handler
+ CacheType type = CacheType::HTTP;
+ Cache *cache = nullptr;
+ {
+ ReplaceablePtr<CacheHostTable>::ScopedReader ht(ppt);
+ type = ht->type;
+ cache = ht->cache;
+ }
+ ppt->reset(new CacheHostTable(cache, type));
+ ctx.complete("Finished loading");
+ },
+ config::ConfigSource::FileOnly, // no RPC content source. Legacy for now.
+ {"proxy.config.cache.hosting_filename"}); // trigger records
}
ReplaceablePtr<CacheHostTable>::ScopedReader hosttable(&this->hosttable);
diff --git a/src/iocore/cache/CacheHosting.cc b/src/iocore/cache/CacheHosting.cc
index c8f7d5f679..395de221c4 100644
--- a/src/iocore/cache/CacheHosting.cc
+++ b/src/iocore/cache/CacheHosting.cc
@@ -227,15 +227,6 @@ CacheHostTable::Match(std::string_view rdata, CacheHostResult *result) const
hostMatch->Match(rdata, result);
}
-int
-CacheHostTable::config_callback(const char * /* name ATS_UNUSED */, RecDataT /* data_type ATS_UNUSED */,
- RecData /* data ATS_UNUSED */, void *cookie)
-{
- ReplaceablePtr<CacheHostTable> *ppt = static_cast<ReplaceablePtr<CacheHostTable> *>(cookie);
- eventProcessor.schedule_imm(new CacheHostTableConfig(ppt), ET_TASK);
- return 0;
-}
-
int fstat_wrapper(int fd, struct stat *s);
// int ControlMatcher::BuildTable() {
diff --git a/src/iocore/cache/P_CacheHosting.h b/src/iocore/cache/P_CacheHosting.h
index d6dc8fd6c2..37008ccba8 100644
--- a/src/iocore/cache/P_CacheHosting.h
+++ b/src/iocore/cache/P_CacheHosting.h
@@ -27,6 +27,7 @@
#include "tscore/MatcherUtils.h"
#include "tscore/HostLookup.h"
#include "tsutil/Bravo.h"
+#include "tscore/Filenames.h"
#include <memory>
@@ -240,14 +241,6 @@ public:
return hostMatch.get();
}
- static int config_callback(const char *, RecDataT, RecData, void *);
-
- void
- register_config_callback(ReplaceablePtr<CacheHostTable> *p)
- {
- RecRegisterConfigUpdateCb("proxy.config.cache.hosting_filename", CacheHostTable::config_callback, (void *)p);
- }
-
CacheType type = CacheType::HTTP;
Cache *cache = nullptr;
int m_numEntries = 0;
@@ -259,35 +252,6 @@ private:
const char *matcher_name = "unknown"; // Used for Debug/Warning/Error messages
};
-struct CacheHostTableConfig;
-using CacheHostTabHandler = int (CacheHostTableConfig::*)(int, void *);
-struct CacheHostTableConfig : public Continuation {
- CacheHostTableConfig(ReplaceablePtr<CacheHostTable> *appt) : Continuation(nullptr), ppt(appt)
- {
- SET_HANDLER(&CacheHostTableConfig::mainEvent);
- }
-
- ~CacheHostTableConfig() {}
-
- int
- mainEvent(int /* event ATS_UNUSED */, Event * /* e ATS_UNUSED */)
- {
- CacheType type = CacheType::HTTP;
- Cache *cache = nullptr;
- {
- ReplaceablePtr<CacheHostTable>::ScopedReader hosttable(ppt);
- type = hosttable->type;
- cache = hosttable->cache;
- }
- ppt->reset(new CacheHostTable(cache, type));
- delete this;
- return EVENT_DONE;
- }
-
-private:
- ReplaceablePtr<CacheHostTable> *ppt;
-};
-
/* list of volumes in the volume.config file */
struct ConfigVol {
int number;
diff --git a/src/iocore/dns/SplitDNS.cc b/src/iocore/dns/SplitDNS.cc
index 7542143e1c..d136161989 100644
--- a/src/iocore/dns/SplitDNS.cc
+++ b/src/iocore/dns/SplitDNS.cc
@@ -31,6 +31,7 @@
#include "P_SplitDNSProcessor.h"
#include "tscore/Tokenizer.h"
#include "tscore/Filenames.h"
+#include "mgmt/config/ConfigRegistry.h"
#include <sys/types.h>
#include "P_SplitDNS.h"
@@ -46,8 +47,6 @@
-------------------------------------------------------------- */
static const char modulePrefix[] = "[SplitDNS]";
-ConfigUpdateHandler<SplitDNSConfig> *SplitDNSConfig::splitDNSUpdate = nullptr;
-
static ClassAllocator<DNSRequestData, false> DNSReqAllocator("DNSRequestDataAllocator");
/* --------------------------------------------------------------
@@ -115,19 +114,25 @@ SplitDNSConfig::release(SplitDNS *params)
void
SplitDNSConfig::startup()
{
- // startup just check gsplit_dns_enabled
- gsplit_dns_enabled = RecGetRecordInt("proxy.config.dns.splitDNS.enabled").value_or(0);
- SplitDNSConfig::splitDNSUpdate = new ConfigUpdateHandler<SplitDNSConfig>();
- SplitDNSConfig::splitDNSUpdate->attach("proxy.config.cache.splitdns.filename");
+ gsplit_dns_enabled = RecGetRecordInt("proxy.config.dns.splitDNS.enabled").value_or(0);
+
+ config::ConfigRegistry::Get_Instance().register_config(
+ "split_dns", // registry key
+ ts::filename::SPLITDNS, // default filename
+ "proxy.config.dns.splitdns.filename", // record holding the filename
+ [](ConfigContext ctx) { SplitDNSConfig::reconfigure(ctx); }, // reload handler
+ config::ConfigSource::FileOnly, // no RPC content
+ {"proxy.config.dns.splitdns.filename"}); // trigger records
}
/* --------------------------------------------------------------
SplitDNSConfig::reconfigure()
-------------------------------------------------------------- */
void
-SplitDNSConfig::reconfigure()
+SplitDNSConfig::reconfigure(ConfigContext ctx)
{
if (0 == gsplit_dns_enabled) {
+ ctx.complete("SplitDNS disabled, skipping reload");
return;
}
@@ -142,6 +147,7 @@ SplitDNSConfig::reconfigure()
Warning("Failed to load %s - No NAMEDs provided! Disabling SplitDNS", ts::filename::SPLITDNS);
gsplit_dns_enabled = 0;
delete params;
+ ctx.fail("No NAMEDs provided, disabling SplitDNS");
return;
}
params->m_numEle = params->m_DNSSrvrTable->getEntryCount();
@@ -160,6 +166,7 @@ SplitDNSConfig::reconfigure()
}
Note("%s finished loading", ts::filename::SPLITDNS);
+ ctx.complete("Finished loading");
}
/* --------------------------------------------------------------
diff --git a/src/iocore/eventsystem/CMakeLists.txt b/src/iocore/eventsystem/CMakeLists.txt
index 1eaf5cd29d..e3130eb745 100644
--- a/src/iocore/eventsystem/CMakeLists.txt
+++ b/src/iocore/eventsystem/CMakeLists.txt
@@ -53,9 +53,9 @@ endif()
if(BUILD_TESTING)
add_executable(test_EventSystem unit_tests/test_EventSystem.cc)
- target_link_libraries(test_EventSystem ts::inkevent Catch2::Catch2WithMain)
+ target_link_libraries(test_EventSystem ts::inkevent configmanager Catch2::Catch2WithMain)
add_executable(test_IOBuffer unit_tests/test_IOBuffer.cc)
- target_link_libraries(test_IOBuffer ts::inkevent Catch2::Catch2WithMain)
+ target_link_libraries(test_IOBuffer ts::inkevent configmanager Catch2::Catch2WithMain)
add_executable(test_MIOBufferWriter unit_tests/test_MIOBufferWriter.cc)
target_link_libraries(test_MIOBufferWriter libswoc::libswoc Catch2::Catch2WithMain)
diff --git a/src/iocore/eventsystem/RecProcess.cc b/src/iocore/eventsystem/RecProcess.cc
index 128154cb3e..8a27eeb69a 100644
--- a/src/iocore/eventsystem/RecProcess.cc
+++ b/src/iocore/eventsystem/RecProcess.cc
@@ -45,6 +45,7 @@ static Event *config_update_cont_event;
static Event *sync_cont_event;
static DbgCtl dbg_ctl_statsproc{"statsproc"};
+static DbgCtl dbg_ctl_configproc{"configproc"};
//-------------------------------------------------------------------------
// Simple setters for the intervals to decouple this from the proxy
@@ -107,7 +108,7 @@ struct config_update_cont : public Continuation {
exec_callbacks(int /* event */, Event * /* e */)
{
RecExecConfigUpdateCbs(REC_PROCESS_UPDATE_REQUIRED);
- Dbg(dbg_ctl_statsproc, "config_update_cont() processed");
+ Dbg(dbg_ctl_configproc, "config_update_cont() processed");
return EVENT_CONT;
}
diff --git a/src/iocore/hostdb/CMakeLists.txt b/src/iocore/hostdb/CMakeLists.txt
index 7cc9ada324..4e099f8da7 100644
--- a/src/iocore/hostdb/CMakeLists.txt
+++ b/src/iocore/hostdb/CMakeLists.txt
@@ -36,11 +36,13 @@ if(BUILD_TESTING)
)
add_executable(test_HostFile test_HostFile.cc HostFile.cc HostDBInfo.cc)
- target_link_libraries(test_HostFile PRIVATE ts::tscore ts::tsutil ts::inkevent Catch2::Catch2WithMain)
+ target_link_libraries(test_HostFile PRIVATE ts::tscore ts::tsutil ts::inkevent configmanager Catch2::Catch2WithMain)
add_catch2_test(NAME test_hostdb_HostFile COMMAND $<TARGET_FILE:test_HostFile>)
add_executable(test_RefCountCache test_RefCountCache.cc)
- target_link_libraries(test_RefCountCache PRIVATE ts::tscore ts::tsutil ts::inkevent Catch2::Catch2WithMain)
+ target_link_libraries(
+ test_RefCountCache PRIVATE ts::tscore ts::tsutil ts::inkevent configmanager Catch2::Catch2WithMain
+ )
add_catch2_test(NAME test_hostdb_RefCountCache COMMAND $<TARGET_FILE:test_RefCountCache>)
endif()
diff --git a/src/iocore/net/P_SSLClientCoordinator.h b/src/iocore/net/P_SSLClientCoordinator.h
index 51899cd0c5..cb2f64f278 100644
--- a/src/iocore/net/P_SSLClientCoordinator.h
+++ b/src/iocore/net/P_SSLClientCoordinator.h
@@ -21,11 +21,13 @@
limitations under the License.
*/
-// A class to pass the ConfigUpdateHandler, so both SSLConfig and SNIConfig get updated
-// when the relevant files/configs get updated.
+#include "mgmt/config/ConfigContext.h"
+
+// A class to coordinate the loading of SSL related configs (SSLConfig, SNIConfig,
+// SSLCertificateConfig). All are reloaded together when any of the trigger records change.
class SSLClientCoordinator
{
public:
static void startup();
- static void reconfigure();
+ static void reconfigure(ConfigContext ctx = {});
};
diff --git a/src/iocore/net/P_SSLConfig.h b/src/iocore/net/P_SSLConfig.h
index 9aea6dc5f6..12f8afd626 100644
--- a/src/iocore/net/P_SSLConfig.h
+++ b/src/iocore/net/P_SSLConfig.h
@@ -173,7 +173,7 @@ private:
struct SSLConfig {
static void startup();
- static void reconfigure();
+ static void reconfigure(ConfigContext ctx = {});
static SSLConfigParams *acquire();
static SSLConfigParams *load_acquire();
static void release(SSLConfigParams *params);
@@ -195,7 +195,7 @@ private:
struct SSLCertificateConfig {
static bool startup();
- static bool reconfigure();
+ static bool reconfigure(ConfigContext ctx = {});
static SSLCertLookup *acquire();
static void release(SSLCertLookup *params);
@@ -218,7 +218,7 @@ struct SSLTicketParams : public ConfigInfo {
struct SSLTicketKeyConfig {
static void startup();
- static bool reconfigure();
+ static bool reconfigure(ConfigContext ctx = {});
static bool reconfigure_data(char *ticket_data, int ticket_data_len);
static SSLTicketParams *
diff --git a/src/iocore/net/QUICMultiCertConfigLoader.cc b/src/iocore/net/QUICMultiCertConfigLoader.cc
index 314285d40a..34a39115c4 100644
--- a/src/iocore/net/QUICMultiCertConfigLoader.cc
+++ b/src/iocore/net/QUICMultiCertConfigLoader.cc
@@ -38,7 +38,7 @@ QUICCertConfig::startup()
}
void
-QUICCertConfig::reconfigure()
+QUICCertConfig::reconfigure(ConfigContext ctx)
{
bool retStatus = true;
SSLConfig::scoped_config params;
@@ -66,8 +66,10 @@ QUICCertConfig::reconfigure()
if (retStatus) {
Note("(quic) %s finished loading%s", params->configFilePath, ts::bw_dbg.c_str());
+ ctx.complete("QUICCertConfig loaded");
} else {
Error("(quic) %s failed to load%s", params->configFilePath, ts::bw_dbg.c_str());
+ ctx.fail("QUICCertConfig failed to load");
}
}
diff --git a/src/iocore/net/SSLClientCoordinator.cc b/src/iocore/net/SSLClientCoordinator.cc
index 43b2e0c0a8..e4af562498 100644
--- a/src/iocore/net/SSLClientCoordinator.cc
+++ b/src/iocore/net/SSLClientCoordinator.cc
@@ -24,44 +24,52 @@
#include "P_SSLClientCoordinator.h"
#include "P_SSLConfig.h"
#include "iocore/net/SSLSNIConfig.h"
+#include "mgmt/config/ConfigRegistry.h"
+#include "tscore/Filenames.h"
#if TS_USE_QUIC == 1
#include "iocore/net/QUICMultiCertConfigLoader.h"
#endif
-std::unique_ptr<ConfigUpdateHandler<SSLClientCoordinator>> sslClientUpdate;
-
void
-SSLClientCoordinator::reconfigure()
+SSLClientCoordinator::reconfigure(ConfigContext reconf_ctx)
{
// The SSLConfig must have its configuration loaded before the SNIConfig.
// The SSLConfig owns the client cert context storage and the SNIConfig will load
// into it.
- SSLConfig::reconfigure();
- SNIConfig::reconfigure();
- SSLCertificateConfig::reconfigure();
+ SSLConfig::reconfigure(reconf_ctx.add_dependent_ctx("SSLConfig"));
+ SNIConfig::reconfigure(reconf_ctx.add_dependent_ctx("SNIConfig"));
+ SSLCertificateConfig::reconfigure(reconf_ctx.add_dependent_ctx("SSLCertificateConfig"));
#if TS_USE_QUIC == 1
- QUICCertConfig::reconfigure();
+ QUICCertConfig::reconfigure(reconf_ctx.add_dependent_ctx("QUICCertConfig"));
#endif
+ reconf_ctx.complete("SSL configs reloaded");
}
void
SSLClientCoordinator::startup()
{
- // The SSLConfig must have its configuration loaded before the SNIConfig.
- // The SSLConfig owns the client cert context storage and the SNIConfig will load
- // into it.
- sslClientUpdate.reset(new ConfigUpdateHandler<SSLClientCoordinator>());
- sslClientUpdate->attach("proxy.config.ssl.client.cert.path");
- sslClientUpdate->attach("proxy.config.ssl.client.cert.filename");
- sslClientUpdate->attach("proxy.config.ssl.client.private_key.path");
- sslClientUpdate->attach("proxy.config.ssl.client.private_key.filename");
- sslClientUpdate->attach("proxy.config.ssl.keylog_file");
+ // Register with ConfigRegistry — no primary file, this is a pure coordinator.
+ // File dependencies (sni.yaml, ssl_multicert.config) are tracked via add_file_and_node_dependency
+ // so (when enabled) the RPC handler can route injected YAML content to the coordinator's handler.
+ config::ConfigRegistry::Get_Instance().register_record_config(
+ "ssl_client_coordinator", // registry key
+ [](ConfigContext ctx) { SSLClientCoordinator::reconfigure(ctx); }, // reload handler
+ {"proxy.config.ssl.client.cert.path", // trigger records
+ "proxy.config.ssl.client.cert.filename", "proxy.config.ssl.client.private_key.path",
+ "proxy.config.ssl.client.private_key.filename", "proxy.config.ssl.keylog_file", "proxy.config.ssl.server.cert.path",
+ "proxy.config.ssl.server.private_key.path", "proxy.config.ssl.server.cert_chain.filename",
+ "proxy.config.ssl.server.session_ticket.enable"});
+
+ // Track sni.yaml — FileManager watches for mtime changes, record wired to trigger reload.
+ // When enabled, the "sni" dep_key makes this routable for RPC inline content.
+ config::ConfigRegistry::Get_Instance().add_file_and_node_dependency(
+ "ssl_client_coordinator", "sni", "proxy.config.ssl.servername.filename", ts::filename::SNI, false);
+
+ // Track ssl_multicert.config — same pattern.
+ config::ConfigRegistry::Get_Instance().add_file_and_node_dependency(
+ "ssl_client_coordinator", "ssl_multicert", "proxy.config.ssl.server.multicert.filename", ts::filename::SSL_MULTICERT, false);
+
+ // Sub-module initialization (order matters: SSLConfig before SNIConfig)
SSLConfig::startup();
- sslClientUpdate->attach("proxy.config.ssl.servername.filename");
SNIConfig::startup();
- sslClientUpdate->attach("proxy.config.ssl.server.multicert.filename");
- sslClientUpdate->attach("proxy.config.ssl.server.cert.path");
- sslClientUpdate->attach("proxy.config.ssl.server.private_key.path");
- sslClientUpdate->attach("proxy.config.ssl.server.cert_chain.filename");
- sslClientUpdate->attach("proxy.config.ssl.server.session_ticket.enable");
}
diff --git a/src/iocore/net/SSLConfig.cc b/src/iocore/net/SSLConfig.cc
index 15ab3d7740..6aaf8c2374 100644
--- a/src/iocore/net/SSLConfig.cc
+++ b/src/iocore/net/SSLConfig.cc
@@ -43,6 +43,7 @@
#include "tscore/Layout.h"
#include "records/RecHttp.h"
#include "records/RecCore.h"
+#include "mgmt/config/ConfigRegistry.h"
#include <openssl/pem.h>
#include <array>
@@ -81,8 +82,6 @@ char *SSLConfigParams::engine_conf_file = nullptr;
namespace
{
-std::unique_ptr<ConfigUpdateHandler<SSLTicketKeyConfig>> sslTicketKey;
-
DbgCtl dbg_ctl_ssl_load{"ssl_load"};
DbgCtl dbg_ctl_ssl_config_updateCTX{"ssl_config_updateCTX"};
DbgCtl dbg_ctl_ssl_client_ctx{"ssl_client_ctx"};
@@ -606,7 +605,7 @@ SSLConfig::startup()
}
void
-SSLConfig::reconfigure()
+SSLConfig::reconfigure(ConfigContext ctx)
{
Dbg(dbg_ctl_ssl_load, "Reload SSLConfig");
SSLConfigParams *params;
@@ -617,6 +616,7 @@ SSLConfig::reconfigure()
params->initialize(); // re-read configuration
// Make the new config available for use.
commit_config_id();
+ ctx.complete("SSLConfig reloaded");
}
SSLConfigParams *
@@ -657,7 +657,7 @@ SSLCertificateConfig::startup()
}
bool
-SSLCertificateConfig::reconfigure()
+SSLCertificateConfig::reconfigure(ConfigContext ctx)
{
bool retStatus = true;
SSLConfig::scoped_config params;
@@ -694,8 +694,10 @@ SSLCertificateConfig::reconfigure()
if (retStatus) {
Note("(ssl) %s finished loading%s", params->configFilePath, ts::bw_dbg.c_str());
+ ctx.complete("SSLCertificateConfig loaded {}", ts::bw_dbg.c_str());
} else {
Error("(ssl) %s failed to load%s", params->configFilePath, ts::bw_dbg.c_str());
+ ctx.fail("SSLCertificateConfig failed to load {}", ts::bw_dbg.c_str());
}
return retStatus;
@@ -796,9 +798,18 @@ SSLTicketParams::LoadTicketData(char *ticket_data, int ticket_data_len)
void
SSLTicketKeyConfig::startup()
{
- sslTicketKey.reset(new ConfigUpdateHandler<SSLTicketKeyConfig>());
+ config::ConfigRegistry::Get_Instance().register_record_config("ssl_ticket_key", // key
+ [](ConfigContext ctx) { // handler callback
+ // eventually ctx should be passed through to the reconfigure fn
+ // and the loaders so it can show more details.
+ if (SSLTicketKeyConfig::reconfigure(ctx)) {
+ ctx.complete("SSL ticket key reloaded");
+ } else {
+ ctx.fail("Failed to reload SSL ticket key");
+ }
+ },
+ {"proxy.config.ssl.server.ticket_key.filename"});
- sslTicketKey->attach("proxy.config.ssl.server.ticket_key.filename");
SSLConfig::scoped_config params;
if (!reconfigure() && params->configExitOnLoadError) {
Fatal("Failed to load SSL ticket key file");
@@ -806,7 +817,7 @@ SSLTicketKeyConfig::startup()
}
bool
-SSLTicketKeyConfig::reconfigure()
+SSLTicketKeyConfig::reconfigure([[maybe_unused]] ConfigContext ctx)
{
SSLTicketParams *ticketKey = new SSLTicketParams();
diff --git a/src/iocore/net/SSLSNIConfig.cc b/src/iocore/net/SSLSNIConfig.cc
index 060f654774..341b489f22 100644
--- a/src/iocore/net/SSLSNIConfig.cc
+++ b/src/iocore/net/SSLSNIConfig.cc
@@ -319,9 +319,10 @@ SNIConfig::startup()
}
int
-SNIConfig::reconfigure()
+SNIConfig::reconfigure(ConfigContext ctx)
{
Dbg(dbg_ctl_ssl, "Reload SNI file");
+
SNIConfigParams *params = new SNIConfigParams;
bool retStatus = params->initialize();
@@ -337,8 +338,10 @@ SNIConfig::reconfigure()
std::string sni_filename = RecConfigReadConfigPath("proxy.config.ssl.servername.filename");
if (retStatus || TSSystemState::is_initializing()) {
Note("%s finished loading", sni_filename.c_str());
+ ctx.complete("Loading finished");
} else {
Error("%s failed to load", sni_filename.c_str());
+ ctx.fail("Failed to load");
}
return retStatus ? 1 : 0;
diff --git a/src/iocore/net/quic/QUICConfig.cc b/src/iocore/net/quic/QUICConfig.cc
index a97baf8ace..6790e25b20 100644
--- a/src/iocore/net/quic/QUICConfig.cc
+++ b/src/iocore/net/quic/QUICConfig.cc
@@ -451,7 +451,7 @@ QUICConfig::startup()
}
void
-QUICConfig::reconfigure()
+QUICConfig::reconfigure(ConfigContext ctx)
{
QUICConfigParams *params;
params = new QUICConfigParams;
@@ -460,6 +460,7 @@ QUICConfig::reconfigure()
_config_id = configProcessor.set(_config_id, params);
QUICConnectionId::SCID_LEN = params->scid_len();
+ ctx.complete("QUICConfig reloaded");
}
QUICConfigParams *
diff --git a/src/mgmt/config/AddConfigFilesHere.cc b/src/mgmt/config/AddConfigFilesHere.cc
deleted file mode 100644
index 38ff8abad9..0000000000
--- a/src/mgmt/config/AddConfigFilesHere.cc
+++ /dev/null
@@ -1,81 +0,0 @@
-/** @file
-
- A brief file description
-
- @section license License
-
- Licensed to the Apache Software Foundation (ASF) under one
- or more contributor license agreements. See the NOTICE file
- distributed with this work for additional information
- regarding copyright ownership. The ASF licenses this file
- to you under the Apache License, Version 2.0 (the
- "License"); you may not use this file except in compliance
- with the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
- */
-
-#include "tscore/ink_platform.h"
-#include "tscore/Filenames.h"
-#include "../../records/P_RecCore.h"
-#include "tscore/Diags.h"
-#include "mgmt/config/FileManager.h"
-
-static constexpr bool REQUIRED{true};
-static constexpr bool NOT_REQUIRED{false};
-/****************************************************************************
- *
- * AddConfigFilesHere.cc - Structs for config files and
- *
- *
- ****************************************************************************/
-void
-registerFile(const char *configName, const char *defaultName, bool isRequired)
-{
- auto fname{RecGetRecordStringAlloc(configName)};
- FileManager::instance().addFile(fname ? ats_as_c_str(fname) : defaultName, configName, false, isRequired);
-}
-
-//
-// initializeRegistry()
-//
-// Code to initialize of registry of objects that represent
-// Web Editable configuration files
-//
-// thread-safe: NO! - Should only be executed once from the main
-// web interface thread, before any child
-// threads have been spawned
-void
-initializeRegistry()
-{
- static int run_already = 0;
-
- if (run_already == 0) {
- run_already = 1;
- } else {
- ink_assert(!"Configuration Object Registry Initialized More than Once");
- }
-
- registerFile("proxy.config.log.config.filename", ts::filename::LOGGING, NOT_REQUIRED);
- registerFile("", ts::filename::STORAGE, REQUIRED);
- registerFile("proxy.config.socks.socks_config_file", ts::filename::SOCKS, NOT_REQUIRED);
- registerFile(ts::filename::RECORDS, ts::filename::RECORDS, NOT_REQUIRED);
- registerFile("proxy.config.cache.control.filename", ts::filename::CACHE, NOT_REQUIRED);
- registerFile("proxy.config.cache.ip_allow.filename", ts::filename::IP_ALLOW, NOT_REQUIRED);
- registerFile("proxy.config.cache.ip_categories.filename", ts::filename::IP_CATEGORIES, NOT_REQUIRED);
- registerFile("proxy.config.http.parent_proxy.file", ts::filename::PARENT, NOT_REQUIRED);
- registerFile("proxy.config.url_remap.filename", ts::filename::REMAP, NOT_REQUIRED);
- registerFile("", ts::filename::VOLUME, NOT_REQUIRED);
- registerFile("proxy.config.cache.hosting_filename", ts::filename::HOSTING, NOT_REQUIRED);
- registerFile("", ts::filename::PLUGIN, NOT_REQUIRED);
- registerFile("proxy.config.dns.splitdns.filename", ts::filename::SPLITDNS, NOT_REQUIRED);
- registerFile("proxy.config.ssl.server.multicert.filename", ts::filename::SSL_MULTICERT, NOT_REQUIRED);
- registerFile("proxy.config.ssl.servername.filename", ts::filename::SNI, NOT_REQUIRED);
- registerFile("proxy.config.jsonrpc.filename", ts::filename::JSONRPC, NOT_REQUIRED);
-}
diff --git a/src/mgmt/config/CMakeLists.txt b/src/mgmt/config/CMakeLists.txt
index e4e106ff92..6107734f63 100644
--- a/src/mgmt/config/CMakeLists.txt
+++ b/src/mgmt/config/CMakeLists.txt
@@ -15,13 +15,13 @@
#
#######################
-add_library(configmanager STATIC FileManager.cc AddConfigFilesHere.cc)
+add_library(configmanager STATIC FileManager.cc ConfigReloadExecutor.cc ConfigRegistry.cc)
add_library(ts::configmanager ALIAS configmanager)
target_link_libraries(
configmanager
- PUBLIC ts::tscore
- PRIVATE ts::proxy
+ PUBLIC ts::tscore ts::records
+ PRIVATE ts::inkevent ts::jsonrpc_protocol yaml-cpp::yaml-cpp
)
clang_tidy_check(configmanager)
diff --git a/src/mgmt/config/ConfigContext.cc b/src/mgmt/config/ConfigContext.cc
new file mode 100644
index 0000000000..c23f3e2760
--- /dev/null
+++ b/src/mgmt/config/ConfigContext.cc
@@ -0,0 +1,159 @@
+/** @file
+
+ ConfigContext implementation
+
+ @section license License
+
+ Licensed to the Apache Software Foundation (ASF) under one
+ or more contributor license agreements. See the NOTICE file
+ distributed with this work for additional information
+ regarding copyright ownership. The ASF licenses this file
+ to you under the Apache License, Version 2.0 (the
+ "License"); you may not use this file except in compliance
+ with the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+ */
+
+#include "mgmt/config/ConfigContext.h"
+#include "mgmt/config/ConfigReloadTrace.h"
+#include "mgmt/config/ReloadCoordinator.h"
+
+#include <yaml-cpp/yaml.h>
+
+// Defined here (not = default in header) so that YAML::Node ctor/dtor/copy
+// symbols are only emitted in this TU (part of librecords, which links yaml-cpp).
+// Otherwise every consumer of RecCore.h would need yaml-cpp at link time.
+ConfigContext::ConfigContext() = default;
+ConfigContext::~ConfigContext() = default;
+ConfigContext::ConfigContext(ConfigContext const &) = default;
+ConfigContext &ConfigContext::operator=(ConfigContext const &) = default;
+
+ConfigContext::ConfigContext(std::shared_ptr<ConfigReloadTask> t, std::string_view description, std::string_view filename)
+ : _task(t)
+{
+ if (auto p = _task.lock()) {
+ if (!description.empty()) {
+ p->set_description(description);
+ }
+ if (!filename.empty()) {
+ p->set_filename(filename);
+ }
+ }
+}
+
+bool
+ConfigContext::is_terminal() const
+{
+ if (auto p = _task.lock()) {
+ return ConfigReloadTask::is_terminal(p->get_state());
+ }
+ return true; // expired task is supposed to be terminal
+}
+
+void
+ConfigContext::in_progress(std::string_view text)
+{
+ if (auto p = _task.lock()) {
+ p->set_in_progress();
+ if (!text.empty()) {
+ p->log(std::string{text});
+ }
+ }
+}
+
+void
+ConfigContext::log(std::string_view text)
+{
+ if (auto p = _task.lock()) {
+ p->log(std::string{text});
+ }
+}
+
+void
+ConfigContext::complete(std::string_view text)
+{
+ if (auto p = _task.lock()) {
+ p->set_completed();
+ if (!text.empty()) {
+ p->log(std::string{text});
+ }
+ }
+}
+
+void
+ConfigContext::fail(std::string_view reason)
+{
+ if (auto p = _task.lock()) {
+ p->set_failed();
+ if (!reason.empty()) {
+ p->log(std::string{reason});
+ }
+ }
+}
+
+void
+ConfigContext::fail(swoc::Errata const &errata, std::string_view summary)
+{
+ if (auto p = _task.lock()) {
+ p->set_failed();
+ // Log the summary first
+ if (!summary.empty()) {
+ p->log(std::string{summary});
+ }
+ // Log each error from the errata
+ for (auto const &err : errata) {
+ p->log(std::string{err.text()});
+ }
+ }
+}
+
+std::string
+ConfigContext::get_description() const
+{
+ if (auto p = _task.lock()) {
+ return p->get_description();
+ }
+ return {};
+}
+
+ConfigContext
+ConfigContext::add_dependent_ctx(std::string_view description)
+{
+ if (auto p = _task.lock()) {
+ auto child = p->add_child(description);
+ // child task will get the full content of the parent task
+ // TODO: eventually we can have a "key" passed so child module
+ // only gets their node of interest.
+ child._supplied_yaml = _supplied_yaml;
+ return child;
+ }
+ return {};
+}
+
+void
+ConfigContext::set_supplied_yaml(YAML::Node node)
+{
+ _supplied_yaml = node; // YAML::Node has no move semantics; copy is cheap (ref-counted).
+}
+
+YAML::Node
+ConfigContext::supplied_yaml() const
+{
+ return _supplied_yaml;
+}
+
+namespace config
+{
+ConfigContext
+make_config_reload_context(std::string_view description, std::string_view filename)
+{
+ return ReloadCoordinator::Get_Instance().create_config_context({}, description, filename);
+}
+} // namespace config
diff --git a/src/mgmt/config/ConfigRegistry.cc b/src/mgmt/config/ConfigRegistry.cc
new file mode 100644
index 0000000000..0a3382f846
--- /dev/null
+++ b/src/mgmt/config/ConfigRegistry.cc
@@ -0,0 +1,492 @@
+/** @file
+ *
+ * Config Registry implementation
+ *
+ * @section license License
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "mgmt/config/ConfigRegistry.h"
+
+#include "iocore/eventsystem/Continuation.h"
+#include "iocore/eventsystem/EventProcessor.h"
+#include "iocore/eventsystem/Tasks.h"
+#include "records/RecCore.h"
+#include "mgmt/config/ConfigContext.h"
+#include "mgmt/config/FileManager.h"
+#include "mgmt/config/ReloadCoordinator.h"
+#include "tscore/Diags.h"
+#include "tscore/ink_assert.h"
+#include "tscore/Layout.h"
+#include "tsutil/ts_errata.h"
+#include "swoc/TextView.h"
+
+#include <yaml-cpp/yaml.h>
+
+namespace
+{
+DbgCtl dbg_ctl{"config.reload"};
+
+/// Infer ConfigType from the filename extension.
+config::ConfigType
+infer_config_type(swoc::TextView filename)
+{
+ return (filename.ends_with(".yaml") || filename.ends_with(".yml")) ? config::ConfigType::YAML : config::ConfigType::LEGACY;
+}
+
+// Resolve a config filename: read the current value from the named record,
+// fallback to default_filename if the record is empty or absent.
+// Returns the bare filename (no sysconfdir prefix) — suitable for FileManager::addFile().
+std::string
+resolve_config_filename(const char *record_name, const std::string &default_filename)
+{
+ if (record_name && record_name[0] != '\0') {
+ if (auto val = RecGetRecordStringAlloc(record_name); val && !val->empty()) {
+ return std::string{*val};
+ }
+ }
+ return default_filename;
+}
+
+///
+// Continuation that executes config reload on ET_TASK thread
+// Used by ConfigRegistry::schedule_reload() for async rpc reloads (content supplied via RPC) or file reloads
+//
+class ScheduledReloadContinuation : public Continuation
+{
+public:
+ ScheduledReloadContinuation(Ptr<ProxyMutex> &m, std::string key) : Continuation(m.get()), _config_key(std::move(key))
+ {
+ SET_HANDLER(&ScheduledReloadContinuation::execute);
+ }
+
+ int
+ execute(int /* event */, Event * /* e */)
+ {
+ Dbg(dbg_ctl, "ScheduledReloadContinuation: executing reload for config '%s'", _config_key.c_str());
+ config::ConfigRegistry::Get_Instance().execute_reload(_config_key);
+ delete this;
+ return EVENT_DONE;
+ }
+
+private:
+ std::string _config_key;
+};
+
+///
+// Continuation used by record-triggered reloads (via on_record_change callback)
+// This is separate from ScheduledReloadContinuation as it always reloads from file
+//
+class RecordTriggeredReloadContinuation : public Continuation
+{
+public:
+ RecordTriggeredReloadContinuation(Ptr<ProxyMutex> &m, std::string key) : Continuation(m.get()), _config_key(std::move(key))
+ {
+ SET_HANDLER(&RecordTriggeredReloadContinuation::execute);
+ }
+
+ int
+ execute(int /* event */, Event * /* e */)
+ {
+ Dbg(dbg_ctl, "RecordTriggeredReloadContinuation: executing reload for config '%s'", _config_key.c_str());
+
+ auto const *entry = config::ConfigRegistry::Get_Instance().find(_config_key);
+
+ if (entry == nullptr) {
+ Warning("Config key '%s' not found in registry", _config_key.c_str());
+ } else if (!entry->has_handler()) {
+ Warning("Config '%s' has no handler", _config_key.c_str());
+ } else {
+ auto ctx = ReloadCoordinator::Get_Instance().create_config_context(_config_key, _config_key, entry->resolve_filename());
+ if (!ctx) {
+ if (ReloadCoordinator::Get_Instance().is_reload_in_progress()) {
+ // True duplicate — same config key already handled in this reload cycle
+ Dbg(dbg_ctl, "Config '%s' reload skipped (duplicate in this reload cycle)", _config_key.c_str());
+ } else {
+ // Standalone record change (no active reload) — run handler directly
+ Dbg(dbg_ctl, "Config '%s' standalone record-triggered reload (no active reload task)", _config_key.c_str());
+ entry->handler(ctx);
+ }
+ } else {
+ ctx.in_progress();
+ entry->handler(ctx);
+ Dbg(dbg_ctl, "Config '%s' file reload completed", _config_key.c_str());
+ }
+ }
+
+ delete this;
+ return EVENT_DONE;
+ }
+
+private:
+ std::string _config_key;
+};
+
+///
+/// Callback invoked by the Records system when a trigger record changes.
+/// Only fires for records registered with ConfigRegistry (via trigger_records
+/// in register_config()/register_record_config(), or via add_file_dependency()).
+///
+/// Record-triggered reload: fan-in deduplication
+/// ──────────────────────────────────────────────
+/// When a config key has N trigger records (e.g., ssl_client_coordinator has 11),
+/// setup_triggers() registers an independent on_record_change callback for each.
+/// The Records system (RecExecConfigUpdateCbs) fires all record
+/// callbacks synchronously in one pass — N records produce N calls here, each
+/// scheduling its own RecordTriggeredReloadContinuation on ET_TASK.
+///
+/// All N continuations carry the same config_key and would invoke the same handler.
+/// The handler doesn't know which specific record triggered it — trigger records are
+/// an OR-set meaning "any of these changed → reconfigure this subsystem."
+///
+/// If different records need different handlers, register them under separate config keys.
+///
+int
+on_record_change(const char *name, RecDataT /* data_type */, RecData /* data */, void *cookie)
+{
+ auto *ctx = static_cast<config::ConfigRegistry::TriggerContext *>(cookie);
+
+ Dbg(dbg_ctl, "Record '%s' changed, scheduling reload for config '%s'", name, ctx->config_key.c_str());
+
+ // Pre-register a CREATED subtask so the main task knows work is pending.
+ // Without this, aggregate_status() can reach SUCCESS before the continuation
+ // runs and creates the subtask. The continuation will activate the reserved
+ // subtask instead of creating a new one.
+ ReloadCoordinator::Get_Instance().reserve_subtask(ctx->config_key);
+
+ // Schedule file reload on ET_TASK thread (always file-based, no rpc-supplied content)
+ eventProcessor.schedule_imm(new RecordTriggeredReloadContinuation(ctx->mutex, ctx->config_key), ET_TASK);
+
+ return 0;
+}
+
+} // anonymous namespace
+
+namespace config
+{
+
+ConfigRegistry &
+ConfigRegistry::Get_Instance()
+{
+ static ConfigRegistry _instance;
+ return _instance;
+}
+
+std::string
+ConfigRegistry::Entry::resolve_filename() const
+{
+ auto fname = resolve_config_filename(filename_record.empty() ? nullptr : filename_record.c_str(), default_filename);
+
+ // Build full path if not already absolute
+ if (!fname.empty() && fname[0] != '/') {
+ return Layout::get()->sysconfdir + "/" + fname;
+ }
+ return fname;
+}
+
+void
+ConfigRegistry::do_register(Entry entry)
+{
+ const char *type_str = (entry.type == ConfigType::YAML) ? "YAML" : "legacy";
+
+ Dbg(dbg_ctl, "Registering %s config '%s' (default: %s, record: %s, triggers: %zu)", type_str, entry.key.c_str(),
+ entry.default_filename.c_str(), entry.filename_record.empty() ? "<none>" : entry.filename_record.c_str(),
+ entry.trigger_records.size());
+
+ std::unique_lock lock(_mutex);
+ auto [it, inserted] = _entries.emplace(entry.key, std::move(entry));
+
+ if (inserted) {
+ setup_triggers(it->second);
+
+ // Register with FileManager for mtime-based file change detection.
+ // This replaces the manual registerFile() call in AddConfigFilesHere.cc.
+ // When rereadConfig() detects the file changed, it calls RecSetSyncRequired()
+ // on the filename_record, which eventually triggers our on_record_change callback.
+ if (!it->second.default_filename.empty()) {
+ auto resolved = resolve_config_filename(it->second.filename_record.empty() ? nullptr : it->second.filename_record.c_str(),
+ it->second.default_filename);
+ FileManager::instance().addFile(resolved.c_str(), it->second.filename_record.c_str(), false, it->second.is_required);
+ }
+ } else {
+ Warning("Config '%s' already registered, ignoring", it->first.c_str());
+ }
+}
+
+void
+ConfigRegistry::register_config(const std::string &key, const std::string &default_filename, const std::string &filename_record,
+ ConfigReloadHandler handler, ConfigSource source,
+ std::initializer_list<const char *> trigger_records, bool is_required)
+{
+ Entry entry;
+ entry.key = key;
+ entry.default_filename = default_filename;
+ entry.filename_record = filename_record;
+ entry.handler = std::move(handler);
+ entry.source = source;
+ entry.is_required = is_required;
+ entry.type = infer_config_type(default_filename);
+
+ for (auto const *record : trigger_records) {
+ entry.trigger_records.emplace_back(record);
+ }
+
+ do_register(std::move(entry));
+}
+
+void
+ConfigRegistry::register_record_config(const std::string &key, ConfigReloadHandler handler,
+ std::initializer_list<const char *> trigger_records)
+{
+ register_config(key, "", "", std::move(handler), ConfigSource::RecordOnly, trigger_records);
+}
+
+void
+ConfigRegistry::register_static_file(const std::string &key, const std::string &default_filename,
+ const std::string &filename_record, bool is_required)
+{
+ // Delegate — no handler, no trigger records, FileOnly source.
+ register_config(key, default_filename, filename_record, nullptr, ConfigSource::FileOnly, {}, is_required);
+}
+
+void
+ConfigRegistry::setup_triggers(Entry &entry)
+{
+ for (auto const &record : entry.trigger_records) {
+ wire_record_callback(record.c_str(), entry.key);
+ }
+}
+
+int
+ConfigRegistry::wire_record_callback(const char *record_name, const std::string &config_key)
+{
+ // TriggerContext lives for the lifetime of the process — intentionally not deleted
+ // as RecRegisterConfigUpdateCb stores the pointer and may invoke the callback at any time.
+ // This is a small, bounded allocation (one per trigger record).
+ auto *ctx = new TriggerContext();
+ ctx->config_key = config_key;
+ ctx->mutex = new_ProxyMutex();
+
+ Dbg(dbg_ctl, "Wiring record callback '%s' to config '%s'", record_name, config_key.c_str());
+
+ int result = RecRegisterConfigUpdateCb(record_name, on_record_change, ctx);
+ if (result != 0) {
+ Warning("Failed to wire callback for record '%s' on config '%s'", record_name, config_key.c_str());
+ delete ctx;
+ return -1;
+ }
+ return 0;
+}
+
+int
+ConfigRegistry::attach(const std::string &key, const char *record_name)
+{
+ std::string config_key;
+
+ // Single lock for check-and-modify.
+ {
+ std::unique_lock lock(_mutex);
+ auto it = _entries.find(key);
+ if (it == _entries.end()) {
+ Warning("Cannot attach trigger to unknown config: %s", key.c_str());
+ return -1;
+ }
+
+ // Store record in entry — owned trigger
+ it->second.trigger_records.emplace_back(record_name);
+ config_key = it->second.key;
+ }
+ // Lock released before external call to RecRegisterConfigUpdateCb
+
+ Dbg(dbg_ctl, "Attaching trigger '%s' to config '%s'", record_name, key.c_str());
+ return wire_record_callback(record_name, config_key);
+}
+
+int
+ConfigRegistry::add_file_dependency(const std::string &key, const char *filename_record, const char *default_filename,
+ bool is_required)
+{
+ std::string config_key;
+
+ {
+ std::shared_lock lock(_mutex);
+ auto it = _entries.find(key);
+ if (it == _entries.end()) {
+ Warning("Cannot add file dependency to unknown config: %s", key.c_str());
+ return -1;
+ }
+ config_key = it->second.key;
+ }
+
+ auto resolved = resolve_config_filename(filename_record, default_filename);
+
+ Dbg(dbg_ctl, "Adding file dependency '%s' (resolved: %s) to config '%s'", filename_record, resolved.c_str(), key.c_str());
+
+ // Register with FileManager for mtime-based change detection.
+ // When rereadConfig() detects the file changed, it calls RecSetSyncRequired()
+ // on the filename_record, which triggers on_record_change below.
+ FileManager::instance().addFile(resolved.c_str(), filename_record, false, is_required);
+
+ // Wire callback — dependency trigger, not stored in trigger_records.
+ return wire_record_callback(filename_record, config_key);
+}
+
+int
+ConfigRegistry::add_file_and_node_dependency(const std::string &key, const std::string &dep_key, const char *filename_record,
+ const char *default_filename, bool is_required)
+{
+ // Do the normal file dependency work (FileManager registration + record callback wiring)
+ int ret = add_file_dependency(key, filename_record, default_filename, is_required);
+ if (ret != 0) {
+ return ret;
+ }
+
+ // Register the dep_key -> parent mapping for RPC routing
+ std::unique_lock lock(_mutex);
+ if (_entries.count(dep_key)) {
+ Warning("ConfigRegistry: dep_key '%s' collides with an existing entry key, ignoring", dep_key.c_str());
+ return -1;
+ }
+ if (_dep_key_to_parent.count(dep_key)) {
+ Warning("ConfigRegistry: dep_key '%s' already registered, ignoring", dep_key.c_str());
+ return -1;
+ }
+ _dep_key_to_parent[dep_key] = key;
+ Dbg(dbg_ctl, "Dependency key '%s' routes to parent '%s'", dep_key.c_str(), key.c_str());
+ return 0;
+}
+
+std::pair<std::string, ConfigRegistry::Entry const *>
+ConfigRegistry::resolve(const std::string &key) const
+{
+ std::shared_lock lock(_mutex);
+
+ // Direct entry lookup
+ auto it = _entries.find(key);
+ if (it != _entries.end()) {
+ return {key, &it->second};
+ }
+
+ // Dependency key lookup
+ auto dep_it = _dep_key_to_parent.find(key);
+ if (dep_it != _dep_key_to_parent.end()) {
+ auto parent_it = _entries.find(dep_it->second);
+ if (parent_it != _entries.end()) {
+ return {dep_it->second, &parent_it->second};
+ }
+ }
+
+ return {{}, nullptr};
+}
+
+bool
+ConfigRegistry::contains(const std::string &key) const
+{
+ std::shared_lock lock(_mutex);
+ return _entries.find(key) != _entries.end();
+}
+
+ConfigRegistry::Entry const *
+ConfigRegistry::find(const std::string &key) const
+{
+ std::shared_lock lock(_mutex);
+ auto it = _entries.find(key);
+ return it != _entries.end() ? &it->second : nullptr;
+}
+
+void
+ConfigRegistry::set_passed_config(const std::string &key, YAML::Node content)
+{
+ std::unique_lock lock(_mutex);
+ _passed_configs[key] = std::move(content);
+ Dbg(dbg_ctl, "Stored passed config for '%s'", key.c_str());
+}
+
+void
+ConfigRegistry::schedule_reload(const std::string &key)
+{
+ Dbg(dbg_ctl, "Scheduling async reload for config '%s'", key.c_str());
+
+ Ptr<ProxyMutex> mutex(new_ProxyMutex());
+ eventProcessor.schedule_imm(new ScheduledReloadContinuation(mutex, key), ET_TASK);
+}
+
+void
+ConfigRegistry::execute_reload(const std::string &key)
+{
+ Dbg(dbg_ctl, "Executing reload for config '%s'", key.c_str());
+
+ // Single lock for both lookups: passed config (from RPC) and registry entry
+ YAML::Node passed_config;
+ Entry entry_copy;
+ {
+ std::shared_lock lock(_mutex);
+
+ if (auto pc_it = _passed_configs.find(key); pc_it != _passed_configs.end()) {
+ passed_config = pc_it->second;
+ Dbg(dbg_ctl, "Retrieved passed config for '%s'", key.c_str());
+ }
+
+ if (auto it = _entries.find(key); it != _entries.end()) {
+ entry_copy = it->second;
+ } else {
+ Warning("Config '%s' not found in registry during execute_reload", key.c_str());
+ return;
+ }
+ }
+
+ ink_release_assert(entry_copy.has_handler());
+
+ // Create context with subtask tracking
+ // For rpc reload: use key as description, no filename (source: rpc)
+ // For file reload: use key as description, filename indicates source: file
+ std::string filename = passed_config.IsDefined() ? "" : entry_copy.resolve_filename();
+ auto ctx = ReloadCoordinator::Get_Instance().create_config_context(entry_copy.key, entry_copy.key, filename);
+ ctx.in_progress();
+
+ if (passed_config.IsDefined()) {
+ // Passed config mode: store YAML node directly for handler to use via supplied_yaml()
+ Dbg(dbg_ctl, "Config '%s' reloading from rpc-supplied content", entry_copy.key.c_str());
+ ctx.set_supplied_yaml(passed_config);
+ } else {
+ Dbg(dbg_ctl, "Config '%s' reloading from file '%s'", entry_copy.key.c_str(), filename.c_str());
+ }
+
+ // Handler checks ctx.supplied_yaml() for rpc-supplied content, otherwise reads from the
+ // module's known filename.
+ try {
+ entry_copy.handler(ctx);
+ if (!ctx.is_terminal()) { // handler did not call ctx.complete() or ctx.fail(). It may have deferred work to another thread.
+ Warning("Config '%s' handler returned without reaching a terminal state. "
+ "If the handler deferred work to another thread, ensure ctx.complete() or ctx.fail() "
+ "is called when processing finishes; otherwise the task will remain in progress "
+ "until the timeout checker marks it as TIMEOUT.",
+ entry_copy.key.c_str());
+ }
+ Dbg(dbg_ctl, "Config '%s' reload completed", entry_copy.key.c_str());
+ // TODO: For future diff/etc support, snapshot the config content here.
+ // For RPC reloads: serialize passed_config to string.
+ // For file reloads: read the file content at reload time.
+ // Store in ConfigReloadTask::Info for history-based diffing.
+ } catch (std::exception const &ex) {
+ ctx.fail(ex.what());
+ Warning("Config '%s' reload failed: %s", entry_copy.key.c_str(), ex.what());
+ }
+}
+
+} // namespace config
diff --git a/src/mgmt/config/ConfigReloadExecutor.cc b/src/mgmt/config/ConfigReloadExecutor.cc
new file mode 100644
index 0000000000..86a1d2714c
--- /dev/null
+++ b/src/mgmt/config/ConfigReloadExecutor.cc
@@ -0,0 +1,102 @@
+/** @file
+
+ Config reload execution logic - schedules async reload work on ET_TASK.
+
+ @section license License
+
+ Licensed to the Apache Software Foundation (ASF) under one
+ or more contributor license agreements. See the NOTICE file
+ distributed with this work for additional information
+ regarding copyright ownership. The ASF licenses this file
+ to you under the Apache License, Version 2.0 (the
+ "License"); you may not use this file except in compliance
+ with the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+ */
+
+#include "mgmt/config/ConfigReloadExecutor.h"
+#include "mgmt/config/FileManager.h"
+#include "mgmt/config/ReloadCoordinator.h"
+
+#include "iocore/eventsystem/Continuation.h"
+#include "iocore/eventsystem/Tasks.h"
+#include "iocore/eventsystem/EventProcessor.h"
+
+#include "records/RecCore.h"
+
+#include "tscore/Diags.h"
+
+namespace
+{
+DbgCtl dbg_ctl_config{"config.reload"};
+
+/**
+ * Continuation that executes the actual config reload work.
+ * This runs on ET_TASK thread to avoid blocking the main RPC thread.
+ */
+struct ReloadWorkContinuation : public Continuation {
+ int
+ handleEvent(int /* etype */, void * /* data */)
+ {
+ bool failed{false};
+ auto current_task = ReloadCoordinator::Get_Instance().get_current_task();
+
+ Dbg(dbg_ctl_config, "Executing config reload work");
+
+ if (current_task) {
+ Dbg(dbg_ctl_config, "Reload task token: %s", current_task->get_token().c_str());
+ }
+
+ // This will tell each changed file to reread itself. If some module is waiting
+ // for a record to be reloaded, it will be notified and the file update will happen
+ // at each module's logic.
+ // Each module will get a ConfigContext object which will be used to track the reload progress.
+ if (auto err = FileManager::instance().rereadConfig(); !err.empty()) {
+ Dbg(dbg_ctl_config, "rereadConfig failed");
+ failed = true;
+ }
+
+ // Force-flush pending record callbacks. rereadConfig() marks records as
+ // sync-required via RecSetSyncRequired(), but the actual on_record_change
+ // callbacks normally wait for the next config_update_cont tick (~3s).
+ // Flushing here fires those callbacks immediately so record-triggered
+ // handlers can reserve their subtasks before handleEvent() returns.
+ // RecExecConfigUpdateCbs clears the sync-required flag so the next
+ // config_update_cont tick is a no-op for these records.
+ RecFlushConfigUpdateCbs();
+ Dbg(dbg_ctl_config, "Flushed pending record update callbacks");
+
+ Dbg(dbg_ctl_config, "Invoking plugin callbacks");
+ // If any callback was registered (TSMgmtUpdateRegister) for config notifications,
+ // then it will eventually be notified.
+ FileManager::instance().invokeConfigPluginCallbacks();
+
+ Dbg(dbg_ctl_config, "Reload work completed, failed=%s", failed ? "true" : "false");
+
+ delete this;
+ return failed ? EVENT_ERROR : EVENT_DONE;
+ }
+
+ ReloadWorkContinuation() : Continuation(new_ProxyMutex()) { SET_HANDLER(&ReloadWorkContinuation::handleEvent); }
+};
+
+} // namespace
+
+namespace config
+{
+
+void
+schedule_reload_work(std::chrono::milliseconds delay)
+{
+ Dbg(dbg_ctl_config, "Scheduling reload work with %lldms delay", static_cast<long long>(delay.count()));
+ eventProcessor.schedule_in(new ReloadWorkContinuation(), HRTIME_MSECONDS(delay.count()), ET_TASK);
+}
+
+} // namespace config
diff --git a/src/mgmt/config/ConfigReloadTrace.cc b/src/mgmt/config/ConfigReloadTrace.cc
new file mode 100644
index 0000000000..aa05843388
--- /dev/null
+++ b/src/mgmt/config/ConfigReloadTrace.cc
@@ -0,0 +1,397 @@
+/** @file
+
+ ConfigReloadTrace — reload progress checker and task timeout detection.
+
+ @section license License
+
+ Licensed to the Apache Software Foundation (ASF) under one
+ or more contributor license agreements. See the NOTICE file
+ distributed with this work for additional information
+ regarding copyright ownership. The ASF licenses this file
+ to you under the Apache License, Version 2.0 (the
+ "License"); you may not use this file except in compliance
+ with the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+ */
+
+#include "mgmt/config/ConfigReloadTrace.h"
+#include "mgmt/config/ConfigContext.h"
+#include "records/RecCore.h"
+
+#include <algorithm>
+#include "tsutil/Metrics.h"
+#include "tsutil/ts_time_parser.h"
+
+namespace
+{
+DbgCtl dbg_ctl_config{"config.reload"};
+
+/// Helper to read a time duration from records configuration.
+[[nodiscard]] std::chrono::milliseconds
+read_time_record(std::string_view record_name, std::string_view default_value, std::chrono::milliseconds fallback,
+ std::chrono::milliseconds minimum = std::chrono::milliseconds{0})
+{
+ // record_name / default_value are compile-time string_view constants, always null-terminated.
+ char str[128] = {0};
+
+ auto result = RecGetRecordString(record_name.data(), str, sizeof(str));
+ std::string_view value = (result.has_value() && !result->empty()) ? result.value() : default_value;
+
+ auto [duration, errata] = ts::time_parser(value);
+ if (!errata.is_ok()) {
+ Dbg(dbg_ctl_config, "Failed to parse '%.*s' value '%.*s': using fallback", static_cast<int>(record_name.size()),
+ record_name.data(), static_cast<int>(value.size()), value.data());
+ return fallback;
+ }
+
+ auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(duration);
+
+ // Enforce minimum if specified
+ if (minimum.count() > 0 && ms < minimum) {
+ Dbg(dbg_ctl_config, "'%.*s' value %lldms below minimum, using %lldms", static_cast<int>(record_name.size()), record_name.data(),
+ static_cast<long long>(ms.count()), static_cast<long long>(minimum.count()));
+ return minimum;
+ }
+
+ return ms;
+}
+} // namespace
+
+std::chrono::milliseconds
+ConfigReloadProgress::get_configured_timeout()
+{
+ return read_time_record(RECORD_TIMEOUT, DEFAULT_TIMEOUT, std::chrono::hours{1});
+}
+
+std::chrono::milliseconds
+ConfigReloadProgress::get_configured_check_interval()
+{
+ return read_time_record(RECORD_CHECK_INTERVAL, DEFAULT_CHECK_INTERVAL, std::chrono::seconds{2},
+ std::chrono::milliseconds{MIN_CHECK_INTERVAL_MS});
+}
+
+ConfigContext
+ConfigReloadTask::add_child(std::string_view description)
+{
+ std::unique_lock<std::shared_mutex> lock(_mutex);
+ // Read token directly - can't call get_token() as it would deadlock (tries to acquire shared_lock on same mutex)
+ auto trace = std::make_shared<ConfigReloadTask>(_info.token, description, false, shared_from_this());
+ _info.sub_tasks.push_back(trace);
+ return ConfigContext{trace, description};
+}
+
+ConfigReloadTask &
+ConfigReloadTask::log(std::string const &text)
+{
+ std::unique_lock<std::shared_mutex> lock(_mutex);
+ _info.logs.push_back(text);
+ return *this;
+}
+
+void
+ConfigReloadTask::add_sub_task(ConfigReloadTaskPtr sub_task)
+{
+ {
+ std::unique_lock<std::shared_mutex> lock(_mutex);
+ Dbg(dbg_ctl_config, "Adding subtask %s to task %s", sub_task->get_description().c_str(), _info.description.c_str());
+ _info.sub_tasks.push_back(sub_task);
+ }
+ // Re-aggregate only if the parent prematurely reached SUCCESS. Record-triggered
+ // handlers register asynchronously (via config_update_cont, ~3s timer), so a
+ // new CREATED subtask can arrive after all previously known subtasks completed.
+ // Guarding on SUCCESS avoids redundant work when the parent is still IN_PROGRESS
+ // and avoids overwriting a TIMEOUT set by the progress checker.
+ if (get_state() == State::SUCCESS) {
+ aggregate_status();
+ }
+}
+
+bool
+ConfigReloadTask::has_subtask_for_key(std::string_view key) const
+{
+ std::shared_lock<std::shared_mutex> lock(_mutex);
+ return std::any_of(_info.sub_tasks.begin(), _info.sub_tasks.end(),
+ [&key](const auto &t) { return t->_info.config_key == key; }); // config_key is immutable once in sub_tasks
+}
+
+ConfigReloadTaskPtr
+ConfigReloadTask::find_subtask_by_key(std::string_view key) const
+{
+ std::shared_lock<std::shared_mutex> lock(_mutex);
+ auto it =
+ std::find_if(_info.sub_tasks.begin(), _info.sub_tasks.end(), [&key](const auto &t) { return t->_info.config_key == key; });
+ return it != _info.sub_tasks.end() ? *it : nullptr;
+}
+
+void
+ConfigReloadTask::set_in_progress()
+{
+ this->set_state_and_notify(State::IN_PROGRESS);
+}
+
+void
+ConfigReloadTask::set_completed()
+{
+ this->set_state_and_notify(State::SUCCESS);
+}
+
+void
+ConfigReloadTask::set_failed()
+{
+ this->set_state_and_notify(State::FAIL);
+}
+
+/// @note Main-task only. Does not call notify_parent() — do not call on subtasks.
+void
+ConfigReloadTask::mark_as_bad_state(std::string_view reason)
+{
+ std::unique_lock<std::shared_mutex> lock(_mutex);
+ // Once a task reaches SUCCESS, FAIL, or TIMEOUT, reject further transitions.
+ if (is_terminal(_info.state)) {
+ Warning("ConfigReloadTask '%s': ignoring mark_as_bad_state from %.*s — already terminal.", _info.description.c_str(),
+ static_cast<int>(state_to_string(_info.state).size()), state_to_string(_info.state).data());
+ return;
+ }
+ _info.state = State::TIMEOUT;
+ _atomic_last_updated_ms.store(now_ms(), std::memory_order_release);
+ if (!reason.empty()) {
+ // Push directly to avoid deadlock (log() would try to acquire same mutex)
+ _info.logs.emplace_back(reason);
+ }
+}
+
+void
+ConfigReloadTask::notify_parent()
+{
+ Dbg(dbg_ctl_config, "parent null =%s , parent main task? %s", _parent ? "false" : "true",
+ (_parent && _parent->is_main_task()) ? "true" : "false");
+
+ if (_parent) {
+ _parent->aggregate_status();
+ }
+}
+
+void
+ConfigReloadTask::set_state_and_notify(State state)
+{
+ {
+ std::unique_lock<std::shared_mutex> lock(_mutex);
+ if (_info.state == state) {
+ return;
+ }
+ // Once a task reaches a terminal state, reject further transitions.
+ if (is_terminal(_info.state)) {
+ auto const cur_str = state_to_string(_info.state);
+ auto const new_str = state_to_string(state);
+ Dbg(dbg_ctl_config, "ConfigReloadTask '%s': ignoring transition from %.*s to %.*s — already terminal.",
+ _info.description.c_str(), static_cast<int>(cur_str.size()), cur_str.data(), static_cast<int>(new_str.size()),
+ new_str.data());
+ return;
+ }
+ Dbg(dbg_ctl_config, "State changed to %.*s for task %s", static_cast<int>(state_to_string(state).size()),
+ state_to_string(state).data(), _info.description.c_str());
+ _info.state = state;
+ _atomic_last_updated_ms.store(now_ms(), std::memory_order_release);
+ }
+
+ // Now that the lock is released, we can safely notify the parent.
+ this->notify_parent();
+}
+
+void
+ConfigReloadTask::aggregate_status()
+{
+ // Use unique_lock throughout to avoid TOCTOU race and data races
+ std::unique_lock<std::shared_mutex> lock(_mutex);
+
+ if (_info.sub_tasks.empty()) {
+ // No subtasks - keep current state (don't change to CREATED)
+ return;
+ }
+
+ bool any_failed = false;
+ bool any_in_progress = false;
+ bool all_success = true;
+ bool all_created = true;
+
+ for (const auto &sub_task : _info.sub_tasks) {
+ State sub_state = sub_task->get_state();
+ switch (sub_state) {
+ case State::FAIL:
+ case State::TIMEOUT: // Treat TIMEOUT as failure
+ any_failed = true;
+ all_success = false;
+ all_created = false;
+ break;
+ case State::IN_PROGRESS: // Handle IN_PROGRESS explicitly!
+ any_in_progress = true;
+ all_success = false;
+ all_created = false;
+ break;
+ case State::SUCCESS:
+ all_created = false;
+ break;
+ case State::CREATED:
+ all_success = false;
+ break;
+ case State::INVALID:
+ default:
+ // Unknown state - treat as not success, not created
+ all_success = false;
+ all_created = false;
+ break;
+ }
+ }
+
+ // Determine new parent state based on children
+ // Priority: FAIL/TIMEOUT > IN_PROGRESS > SUCCESS > CREATED
+ State new_state;
+ if (any_failed) {
+ new_state = State::FAIL;
+ } else if (any_in_progress) {
+ // If any subtask is still working, parent is IN_PROGRESS
+ new_state = State::IN_PROGRESS;
+ } else if (all_success) {
+ Dbg(dbg_ctl_config, "Setting %s task '%s' to SUCCESS (all subtasks succeeded)", _info.main_task ? "main" : "sub",
+ _info.description.c_str());
+ new_state = State::SUCCESS;
+ } else if (all_created && !_info.main_task) {
+ Dbg(dbg_ctl_config, "Setting %s task '%s' to CREATED (all subtasks created)", _info.main_task ? "main" : "sub",
+ _info.description.c_str());
+ new_state = State::CREATED;
+ } else {
+ // Mixed state or main task with created subtasks - keep as IN_PROGRESS
+ Dbg(dbg_ctl_config, "Setting %s task '%s' to IN_PROGRESS (mixed state)", _info.main_task ? "main" : "sub",
+ _info.description.c_str());
+ new_state = State::IN_PROGRESS;
+ }
+
+ // Only update if state actually changed
+ if (_info.state != new_state) {
+ _info.state = new_state;
+ _atomic_last_updated_ms.store(now_ms(), std::memory_order_release);
+ }
+
+ // Release lock before notifying parent to avoid potential deadlock
+ lock.unlock();
+
+ if (_parent) {
+ _parent->aggregate_status();
+ }
+}
+
+int64_t
+ConfigReloadTask::get_last_updated_time_ms() const
+{
+ int64_t last_time_ms = _atomic_last_updated_ms.load(std::memory_order_acquire);
+
+ std::shared_lock<std::shared_mutex> lock(_mutex);
+ for (const auto &sub_task : _info.sub_tasks) {
+ int64_t sub_time_ms = sub_task->get_own_last_updated_time_ms();
+ if (sub_time_ms > last_time_ms) {
+ last_time_ms = sub_time_ms;
+ }
+ }
+ return last_time_ms;
+}
+
+std::time_t
+ConfigReloadTask::get_last_updated_time() const
+{
+ return static_cast<std::time_t>(
+ std::chrono::duration_cast<std::chrono::seconds>(std::chrono::milliseconds{get_last_updated_time_ms()}).count());
+}
+void
+ConfigReloadTask::start_progress_checker()
+{
+ std::unique_lock<std::shared_mutex> lock(_mutex);
+ if (!_reload_progress_checker_started && _info.main_task && _info.state == State::IN_PROGRESS) { // can only start once
+ auto *checker = new ConfigReloadProgress(shared_from_this());
+ eventProcessor.schedule_in(checker, HRTIME_MSECONDS(checker->get_check_interval().count()), ET_TASK);
+ _reload_progress_checker_started = true;
+ }
+}
+
+// reload progress checker
+int
+ConfigReloadProgress::check_progress(int /* etype */, void * /* data */)
+{
+ Dbg(dbg_ctl_config, "Checking progress for reload task %s - descr: %s", _reload ? _reload->get_token().c_str() : "null",
+ _reload ? _reload->get_description().c_str() : "null");
+ if (_reload == nullptr) {
+ return EVENT_DONE;
+ }
+
+ auto const current_state = _reload->get_state();
+ if (ConfigReloadTask::is_terminal(current_state)) {
+ auto const state_str = ConfigReloadTask::state_to_string(current_state);
+ if (_awaiting_terminal_confirmation) {
+ // Confirmed terminal — safe to stop.
+ Dbg(dbg_ctl_config, "Reload task %s confirmed %.*s after grace period, stopping progress check.",
+ _reload->get_token().c_str(), static_cast<int>(state_str.size()), state_str.data());
+ return EVENT_DONE;
+ }
+ // First observation of terminal state — reschedule once more to confirm
+ // it isn't pulled back to IN_PROGRESS by a late reserve_subtask().
+ _awaiting_terminal_confirmation = true;
+ Dbg(dbg_ctl_config, "Reload task %s reached %.*s, scheduling confirmation in %lldms.", _reload->get_token().c_str(),
+ static_cast<int>(state_str.size()), state_str.data(), static_cast<long long>(TERMINAL_CONFIRMATION_DELAY.count()));
+ eventProcessor.schedule_in(this, HRTIME_MSECONDS(TERMINAL_CONFIRMATION_DELAY.count()), ET_TASK);
+ return EVENT_CONT;
+ }
+ // State was pulled back from terminal (e.g., SUCCESS -> IN_PROGRESS) — reset and continue.
+ _awaiting_terminal_confirmation = false;
+
+ // Get configured timeout (read dynamically to allow runtime changes)
+ // Returns 0ms if disabled (timeout string is "0" or empty)
+ auto max_running_time = get_configured_timeout();
+
+ // Check if timeout is disabled (0ms means disabled)
+ if (max_running_time.count() == 0) {
+ Dbg(dbg_ctl_config, "Timeout disabled - task %s will run indefinitely until completion or manual cancellation",
+ _reload->get_token().c_str());
+ // Still reschedule to detect completion, but don't timeout
+ eventProcessor.schedule_in(this, HRTIME_MSECONDS(_every.count()), ET_TASK);
+ return EVENT_CONT;
+ }
+
+ // ok, it's running, should we keep it running?
+ auto ct = std::chrono::system_clock::from_time_t(_reload->get_created_time());
+ auto lut = std::chrono::system_clock::from_time_t(_reload->get_last_updated_time());
+ std::string buf;
+ if (lut + max_running_time < std::chrono::system_clock::now()) {
+ if (_reload->contains_dependents()) {
+ swoc::bwprint(buf, "Task {} timed out after {}ms with no reload action (no config to reload). Last state: {}",
+ _reload->get_token(), max_running_time.count(), ConfigReloadTask::state_to_string(current_state));
+ } else {
+ swoc::bwprint(buf, "Reload task {} timed out after {}ms. Previous state: {}.", _reload->get_token(), max_running_time.count(),
+ ConfigReloadTask::state_to_string(current_state));
+ }
+ _reload->mark_as_bad_state(buf);
+ Dbg(dbg_ctl_config, "%s", buf.c_str());
+ return EVENT_DONE;
+ }
+
+ swoc::bwprint(buf,
+ "Reload task {} ongoing with state {}, created at {} and last update at {}. Timeout in {}ms. Will check again.",
+ _reload->get_token(), ConfigReloadTask::state_to_string(current_state),
+ swoc::bwf::Date(std::chrono::system_clock::to_time_t(ct)),
+ swoc::bwf::Date(std::chrono::system_clock::to_time_t(lut)), max_running_time.count());
+ Dbg(dbg_ctl_config, "%s", buf.c_str());
+
+ eventProcessor.schedule_in(this, HRTIME_MSECONDS(_every.count()), ET_TASK);
+ return EVENT_CONT;
+}
+
+ConfigReloadProgress::ConfigReloadProgress(ConfigReloadTaskPtr reload)
+ : Continuation(new_ProxyMutex()), _reload{reload}, _every{get_configured_check_interval()}
+{
+ SET_HANDLER(&ConfigReloadProgress::check_progress);
+}
diff --git a/src/mgmt/config/FileManager.cc b/src/mgmt/config/FileManager.cc
index 31a7834d0f..e3df9ea9b4 100644
--- a/src/mgmt/config/FileManager.cc
+++ b/src/mgmt/config/FileManager.cc
@@ -25,14 +25,13 @@
#include <vector>
#include <algorithm>
-#include "api/InkAPIInternal.h" // TODO: this brings a lot of dependencies, double check this.
-
#include "tscore/ink_platform.h"
#include "tscore/ink_file.h"
#include "../../records/P_RecCore.h"
#include "tscore/Diags.h"
#include "tscore/Filenames.h"
#include "tscore/Layout.h"
+#include "mgmt/config/ConfigRegistry.h"
#if HAVE_STRUCT_STAT_ST_MTIMESPEC_TV_NSEC
#define TS_ARCHIVE_STAT_MTIME(t) ((t).st_mtime * 1000000000 + (t).st_mtimespec.tv_nsec)
@@ -52,13 +51,12 @@ process_config_update(std::string const &fileName, std::string const &configName
Dbg(dbg_ctl, "Config update requested for '%s'. [%s]", fileName.empty() ? "Unknown" : fileName.c_str(),
configName.empty() ? "No config record associated" : configName.c_str());
swoc::Errata ret;
- // TODO: make sure records holds the name after change, if not we should change it.
+ // records.yaml reload is now handled by its ConfigRegistry handler
+ // (registered in register_config_files() in traffic_server.cc).
+ // Delegate to ConfigRegistry::execute_reload("records") so the reload
+ // is traced and status-reported like every other config.
if (fileName == ts::filename::RECORDS) {
- if (auto zret = RecReadYamlConfigFile(); zret) {
- RecConfigWarnIfUnregistered();
- } else {
- ret.note("Error reading {}", fileName).note(zret);
- }
+ config::ConfigRegistry::Get_Instance().execute_reload("records");
} else if (!configName.empty()) { // Could be the case we have a child file to reload with no related config record.
RecT rec_type;
if (auto r = RecGetRecordType(configName.c_str(), &rec_type); r == REC_ERR_OKAY && rec_type == RECT_CONFIG) {
@@ -72,13 +70,13 @@ process_config_update(std::string const &fileName, std::string const &configName
}
// JSONRPC endpoint defs.
-const std::string CONFIG_REGISTRY_KEY_STR{"config_registry"};
-const std::string FILE_PATH_KEY_STR{"file_path"};
-const std::string RECORD_NAME_KEY_STR{"config_record_name"};
-const std::string PARENT_CONFIG_KEY_STR{"parent_config"};
-const std::string ROOT_ACCESS_NEEDED_KEY_STR{"root_access_needed"};
-const std::string IS_REQUIRED_KEY_STR{"is_required"};
-const std::string NA_STR{"N/A"};
+constexpr const char *CONFIG_REGISTRY_KEY_STR{"config_registry"};
+constexpr const char *FILE_PATH_KEY_STR{"file_path"};
+constexpr const char *RECORD_NAME_KEY_STR{"config_record_name"};
+constexpr const char *PARENT_CONFIG_KEY_STR{"parent_config"};
+constexpr const char *ROOT_ACCESS_NEEDED_KEY_STR{"root_access_needed"};
+constexpr const char *IS_REQUIRED_KEY_STR{"is_required"};
+constexpr const char *NA_STR{"N/A"};
} // namespace
@@ -153,21 +151,18 @@ FileManager::fileChanged(std::string const &fileName, std::string const &configN
return ret;
}
-// TODO: To do the following here, we have to pull up a lot of dependencies we don't really
-// need, #include "InkAPIInternal.h" brings plenty of them. Double check this approach. RPC will
-// also be able to pass messages to plugins, once that's designed it can also cover this.
void
-FileManager::registerConfigPluginCallbacks(ConfigUpdateCbTable *cblist)
+FileManager::registerConfigPluginCallbacks(std::function<void()> cb)
{
- _pluginCallbackList = cblist;
+ _pluginCallback = std::move(cb);
}
void
FileManager::invokeConfigPluginCallbacks()
{
Dbg(dbg_ctl, "invoke plugin callbacks");
- if (_pluginCallbackList) {
- _pluginCallbackList->invoke();
+ if (_pluginCallback) {
+ _pluginCallback();
}
}
@@ -194,7 +189,8 @@ FileManager::rereadConfig()
// ToDo: rb->isVersions() was always true before, because numberBackups was always >= 1. So ROLLBACK_CHECK_ONLY could not
// happen at all...
if (rb->checkForUserUpdate(FileManager::ROLLBACK_CHECK_AND_UPDATE)) {
- Dbg(dbg_ctl, "File %s changed.", it.first.c_str());
+ Dbg(dbg_ctl, "File %s changed. Has a parent=%s, ", it.first.c_str(),
+ rb->getParentConfig() ? rb->getParentConfig()->getFileName() : "none");
if (auto const &r = fileChanged(rb->getFileName(), rb->getConfigName()); !r) {
ret.note(r);
}
diff --git a/src/mgmt/config/ReloadCoordinator.cc b/src/mgmt/config/ReloadCoordinator.cc
new file mode 100644
index 0000000000..202a7806af
--- /dev/null
+++ b/src/mgmt/config/ReloadCoordinator.cc
@@ -0,0 +1,270 @@
+/** @file
+
+ ReloadCoordinator - tracks config reload sessions and status.
+
+ @section license License
+
+ Licensed to the Apache Software Foundation (ASF) under one
+ or more contributor license agreements. See the NOTICE file
+ distributed with this work for additional information
+ regarding copyright ownership. The ASF licenses this file
+ to you under the Apache License, Version 2.0 (the
+ "License"); you may not use this file except in compliance
+ with the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+ */
+
+#include "mgmt/config/ReloadCoordinator.h"
+
+#include <algorithm>
+#include <mutex>
+#include <utility>
+
+#include "tscore/Diags.h"
+#include "tsutil/Metrics.h"
+#include "swoc/Errata.h"
+
+namespace
+{
+DbgCtl dbg_ctl{"config.reload"};
+} // namespace
+
+swoc::Errata
+ReloadCoordinator::prepare_reload(std::string &token_name, const char *token_prefix, bool force)
+{
+ std::unique_lock lock(_mutex);
+
+ if (token_name.empty()) {
+ token_name = generate_token_name(token_prefix);
+ }
+
+ Dbg(dbg_ctl, "Preparing reload task for token: %s (force=%s)", token_name.c_str(), force ? "true" : "false");
+
+ // Check if a reload is already in progress.
+ if (_current_task != nullptr) {
+ auto state = _current_task->get_state();
+ if (!ConfigReloadTask::is_terminal(state) && state != ConfigReloadTask::State::INVALID) {
+ if (force) {
+ Dbg(dbg_ctl, "Force mode: marking existing reload as stale to start new one");
+ _current_task->mark_as_bad_state("Superseded by forced reload");
+ } else {
+ return swoc::Errata("Reload already in progress for token: {}", token_name);
+ }
+ }
+ }
+
+ Dbg(dbg_ctl, "No reload in progress detected");
+
+ // Create the main task for tracking (status tracking only)
+ // The actual reload work is scheduled separately via config::schedule_reload_work()
+ create_main_config_task(token_name, "Main reload task");
+
+ Dbg(dbg_ctl, "Reload task created with token: %s", token_name.c_str());
+ return {}; // Success — caller will schedule the actual work
+}
+
+void
+ReloadCoordinator::create_main_config_task(std::string_view token, std::string description)
+{
+ _current_task = std::make_shared<ConfigReloadTask>(token, description, true /*root*/, nullptr);
+ _current_task->start_progress_checker();
+
+ std::string txt;
+ swoc::bwprint(txt, "{} - {}", description, swoc::bwf::Date(_current_task->get_created_time()));
+ _current_task->set_description(txt);
+
+ // Enforce history size limit — remove oldest when full
+ if (_history.size() >= MAX_HISTORY_SIZE) {
+ _history.erase(_history.begin());
+ }
+ _history.push_back(_current_task);
+
+ ts::Metrics &metrics = ts::Metrics::instance();
+ static auto reconf_time = metrics.lookup("proxy.process.proxy.reconfigure_time");
+ metrics[reconf_time].store(
+ _current_task->get_created_time()); // This may be different from the actual task reload time. Ok for now.
+}
+
+std::string
+ReloadCoordinator::generate_token_name(const char *prefix) const
+{
+ auto now = std::chrono::system_clock::now();
+ auto time = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()).count();
+ return std::string(prefix) + std::to_string(time);
+}
+
+void
+ReloadCoordinator::reserve_subtask(std::string_view config_key)
+{
+ std::unique_lock lock(_mutex);
+ if (!_current_task) {
+ return;
+ }
+
+ // Block only hard-terminal states (FAIL, TIMEOUT). SUCCESS is intentionally
+ // allowed: records.yaml is always the first file processed by rereadConfig(),
+ // so the main task reaches SUCCESS (from the "records" subtask) before any
+ // other file-based or record-triggered reservation runs. Adding a CREATED
+ // subtask to a SUCCESS parent causes add_sub_task() → aggregate_status() to
+ // pull the parent back to IN_PROGRESS.
+ auto state = _current_task->get_state();
+ if (state == ConfigReloadTask::State::FAIL || state == ConfigReloadTask::State::TIMEOUT) {
+ return;
+ }
+
+ // Already reserved or handled — nothing to do.
+ if (_current_task->has_subtask_for_key(config_key)) {
+ return;
+ }
+
+ auto task = std::make_shared<ConfigReloadTask>(_current_task->get_token(), config_key, false, _current_task);
+ task->set_config_key(config_key);
+ _current_task->add_sub_task(task);
+
+ Dbg(dbg_ctl, "Reserved subtask for config '%.*s'", static_cast<int>(config_key.size()), config_key.data());
+}
+
+ConfigContext
+ReloadCoordinator::create_config_context(std::string_view config_key, std::string_view description, std::string_view filename)
+{
+ std::unique_lock lock(_mutex);
+ if (!_current_task) {
+ // No active reload — return empty context (safe no-op for startup path)
+ return ConfigContext{};
+ }
+
+ // Check for an existing subtask with this config key.
+ //
+ // Two cases:
+ // 1. Reserved (CREATED) — pre-registered by reserve_subtask() in on_record_change.
+ // Return a ConfigContext wrapping it so the handler can activate and complete it.
+ // 2. Already active/done — true duplicate from N trigger records mapping to one config key.
+ // Return empty to skip.
+ if (!config_key.empty() && !ConfigReloadTask::is_terminal(_current_task->get_state())) {
+ auto existing = _current_task->find_subtask_by_key(config_key);
+ if (existing) {
+ if (existing->get_state() == ConfigReloadTask::State::CREATED) {
+ // Activate the reserved subtask
+ Dbg(dbg_ctl, "Activating reserved subtask for config '%.*s'", static_cast<int>(config_key.size()), config_key.data());
+ return ConfigContext{existing, description, filename};
+ }
+ // Already handled — true duplicate
+ Dbg(dbg_ctl, "Duplicate reload for config '%.*s' — subtask already exists, skipping", static_cast<int>(config_key.size()),
+ config_key.data());
+ return ConfigContext{};
+ }
+ }
+
+ // No existing subtask — create a new one
+ auto task =
+ std::make_shared<ConfigReloadTask>(_current_task->get_token(), description, false /*not a main reload job*/, _current_task);
+ task->set_config_key(config_key);
+ _current_task->add_sub_task(task);
+
+ ConfigContext ctx{task, description, filename};
+ return ctx;
+}
+
+bool
+ReloadCoordinator::is_reload_in_progress() const
+{
+ std::shared_lock lock(_mutex);
+
+ if (_current_task == nullptr) {
+ Dbg(dbg_ctl, "No current task found, reload not in progress.");
+ return false;
+ }
+
+ auto state = _current_task->get_state();
+ if (!ConfigReloadTask::is_terminal(state) && state != ConfigReloadTask::State::INVALID) {
+ Dbg(dbg_ctl, "Found reload in progress for task: %s", _current_task->get_token().c_str());
+ return true;
+ } else {
+ auto state_str = ConfigReloadTask::state_to_string(state);
+ Dbg(dbg_ctl, "Current task is not running, state: %s", state_str.data());
+ }
+
+ return false;
+}
+
+std::pair<bool, ConfigReloadTask::Info>
+ReloadCoordinator::find_by_token(std::string_view token_name) const
+{
+ std::shared_lock lock(_mutex);
+ Dbg(dbg_ctl, "Search %s, history size=%d", token_name.data(), static_cast<int>(_history.size()));
+
+ auto it =
+ std::find_if(_history.begin(), _history.end(), [&token_name](auto const &task) { return task->get_token() == token_name; });
+
+ if (it != _history.end()) {
+ return {true, (*it)->get_info()};
+ }
+ return {false, ConfigReloadTask::Info{}};
+}
+
+std::vector<ConfigReloadTask::Info>
+ReloadCoordinator::get_all(std::size_t N) const
+{
+ std::shared_lock lock(_mutex);
+ std::vector<ConfigReloadTask::Info> result;
+ if (N == 0) {
+ N = _history.size();
+ }
+
+ result.reserve(std::min(N, _history.size()));
+
+ auto start_it = _history.begin();
+ if (_history.size() > N) {
+ start_it = _history.end() - N;
+ }
+
+ std::transform(start_it, _history.end(), std::back_inserter(result),
+ [](const std::shared_ptr<ConfigReloadTask> &task) { return task->get_info(); });
+
+ return result;
+}
+
+bool
+ReloadCoordinator::mark_task_as_stale(std::string_view token, std::string_view reason)
+{
+ std::unique_lock lock(_mutex);
+
+ std::shared_ptr<ConfigReloadTask> task_to_mark;
+
+ if (token.empty()) {
+ task_to_mark = _current_task;
+ } else {
+ auto it = std::find_if(_history.begin(), _history.end(), [&token](auto const &task) { return task->get_token() == token; });
+ if (it != _history.end()) {
+ task_to_mark = *it;
+ }
+ }
+
+ if (!task_to_mark) {
+ Dbg(dbg_ctl, "No task found to mark stale (token: %.*s)", static_cast<int>(token.size()),
+ token.empty() ? "<current>" : token.data());
+ return false;
+ }
+
+ auto state = task_to_mark->get_state();
+ if (ConfigReloadTask::is_terminal(state)) {
+ auto const state_str = ConfigReloadTask::state_to_string(state);
+ Dbg(dbg_ctl, "Task %s already in terminal state (%.*s), cannot mark stale", task_to_mark->get_token().c_str(),
+ static_cast<int>(state_str.size()), state_str.data());
+ return false;
+ }
+
+ auto state_str = ConfigReloadTask::state_to_string(state);
+ Dbg(dbg_ctl, "Marking task %s as stale (state: %s) - reason: %s", task_to_mark->get_token().c_str(), state_str.data(),
+ reason.data());
+
+ task_to_mark->mark_as_bad_state(reason);
+ return true;
+}
diff --git a/src/mgmt/rpc/CMakeLists.txt b/src/mgmt/rpc/CMakeLists.txt
index bee0f8929f..b3a844f792 100644
--- a/src/mgmt/rpc/CMakeLists.txt
+++ b/src/mgmt/rpc/CMakeLists.txt
@@ -68,7 +68,9 @@ if(BUILD_TESTING)
add_executable(
test_jsonrpcserver server/unit_tests/test_rpcserver.cc ${CMAKE_SOURCE_DIR}/src/shared/rpc/IPCSocketClient.cc
)
- target_link_libraries(test_jsonrpcserver Catch2::Catch2WithMain ts::jsonrpc_server ts::inkevent libswoc::libswoc)
+ target_link_libraries(
+ test_jsonrpcserver Catch2::Catch2WithMain ts::jsonrpc_server ts::inkevent libswoc::libswoc configmanager
+ )
add_catch2_test(NAME test_jsonrpcserver COMMAND test_jsonrpcserver)
endif()
diff --git a/src/mgmt/rpc/handlers/config/Configuration.cc b/src/mgmt/rpc/handlers/config/Configuration.cc
index 0c57659d6f..04c8716574 100644
--- a/src/mgmt/rpc/handlers/config/Configuration.cc
+++ b/src/mgmt/rpc/handlers/config/Configuration.cc
@@ -27,11 +27,19 @@
#include "tscore/Diags.h"
#include "mgmt/config/FileManager.h"
+#include "mgmt/config/ConfigReloadExecutor.h"
+#include "mgmt/config/ConfigRegistry.h"
#include "../common/RecordsUtils.h"
#include "tsutil/Metrics.h"
-namespace utils = rpc::handlers::records::utils;
+#include "mgmt/config/ReloadCoordinator.h"
+#include "mgmt/config/ConfigReloadErrors.h"
+#include "records/YAMLConfigReloadTaskEncoder.h"
+
+namespace utils = rpc::handlers::records::utils;
+using ConfigError = config::reload::errors::ConfigReloadError;
+constexpr auto errc = config::reload::errors::to_int;
namespace
{
@@ -41,11 +49,12 @@ struct SetRecordCmdInfo {
std::string value;
};
-DbgCtl dbg_ctl_RPC{"RPC"};
+DbgCtl dbg_ctl_RPC{"rpc"};
} // namespace
namespace YAML
{
+
template <> struct convert<SetRecordCmdInfo> {
static bool
decode(Node const &node, SetRecordCmdInfo &info)
@@ -186,25 +195,197 @@ set_config_records(std::string_view const & /* id ATS_UNUSED */, YAML::Node cons
return resp;
}
+///
+// Unified config reload handler - supports file source and RPC source modes
+// RPC source is detected by presence of "configs" parameter
+//
swoc::Rv<YAML::Node>
-reload_config(std::string_view const & /* id ATS_UNUSED */, YAML::Node const & /* params ATS_UNUSED */)
+reload_config(std::string_view const & /* id ATS_UNUSED */, YAML::Node const ¶ms)
{
- ts::Metrics &metrics = ts::Metrics::instance();
- static auto reconf_time = metrics.lookup("proxy.process.proxy.reconfigure_time");
- static auto reconf_req = metrics.lookup("proxy.process.proxy.reconfigure_required");
+ std::string token = params["token"] ? params["token"].as<std::string>() : std::string{};
+ bool const force = params["force"] ? params["force"].as<bool>() : false;
+ std::string buf;
swoc::Rv<YAML::Node> resp;
- Dbg(dbg_ctl_RPC, "invoke plugin callbacks");
- // if there is any error, report it back.
- if (auto err = FileManager::instance().rereadConfig(); !err.empty()) {
- resp.note(err);
+
+ auto make_error = [&](std::string_view msg, int code) -> YAML::Node {
+ YAML::Node err;
+ err["message"] = msg;
+ err["code"] = code;
+ return err;
+ };
+
+ // Check if reload is already in progress
+ if (!force && ReloadCoordinator::Get_Instance().is_reload_in_progress()) {
+ resp.result()["errors"].push_back(make_error(
+ swoc::bwprint(buf, "Reload ongoing with token '{}'", ReloadCoordinator::Get_Instance().get_current_task()->get_token()),
+ errc(ConfigError::RELOAD_IN_PROGRESS)));
+ resp.result()["tasks"].push_back(ReloadCoordinator::Get_Instance().get_current_task()->get_info());
+ return resp;
+ }
+
+ // Validate token doesn't already exist
+ if (!token.empty() && ReloadCoordinator::Get_Instance().has_token(token)) {
+ resp.result()["errors"].push_back(
+ make_error(swoc::bwprint(buf, "Token '{}' already exists.", token), errc(ConfigError::TOKEN_ALREADY_EXISTS)));
+ return resp;
+ }
+
+ ///
+ // RPC source: detected by presence of "configs" parameter
+ // Expected format:
+ // configs:
+ // ip_allow:
+ // - apply: in
+ // ...
+ // sni:
+ // - fqdn: '*.example.com'
+ // ...
+ //
+ if (params["configs"] && params["configs"].IsMap()) {
+ auto const &configs = params["configs"];
+ auto ®istry = ::config::ConfigRegistry::Get_Instance();
+
+ // Dependency keys (registered via add_file_and_node_dependency) are resolved to their
+ // parent entry. Multiple dependency keys for the same parent are merged into a single
+ // YAML node so the parent handler fires only once.
+ struct ResolvedConfig {
+ std::string parent_key;
+ std::string original_key;
+ YAML::Node content;
+ };
+ std::vector<ResolvedConfig> valid_configs;
+
+ for (auto it = configs.begin(); it != configs.end(); ++it) {
+ std::string key = it->first.as<std::string>();
+
+ auto [parent_key, entry] = registry.resolve(key);
+ if (!entry) {
+ resp.result()["errors"].push_back(
+ make_error(swoc::bwprint(buf, "Config '{}' not registered", key), errc(ConfigError::CONFIG_NOT_REGISTERED)));
+ continue;
+ }
+
+ if (entry->source != ::config::ConfigSource::FileAndRpc) {
+ resp.result()["errors"].push_back(make_error(swoc::bwprint(buf, "Config '{}' does not support direct RPC content", key),
+ errc(ConfigError::RPC_SOURCE_NOT_SUPPORTED)));
+ continue;
+ }
+
+ if (!entry->handler) {
+ resp.result()["errors"].push_back(
+ make_error(swoc::bwprint(buf, "Config '{}' has no handler", key), errc(ConfigError::CONFIG_NO_HANDLER)));
+ continue;
+ }
+
+ valid_configs.push_back({parent_key, key, it->second});
+ }
+
+ // If no valid configs, return early without creating a task
+ if (valid_configs.empty()) {
+ resp.result()["message"].push_back("No configs were scheduled for reload");
+ return resp;
+ }
+
+ // Create reload task only if we have valid configs
+ std::string token_prefix = token.empty() ? "rpc-" : "";
+ if (auto ret = ReloadCoordinator::Get_Instance().prepare_reload(token, token_prefix.c_str(), force); !ret.is_ok()) {
+ resp.result()["errors"].push_back(
+ make_error(swoc::bwprint(buf, "Failed to create reload task: {}", ret), errc(ConfigError::RELOAD_TASK_FAILED)));
+ return resp;
+ }
+
+ // - Direct entries (key == parent_key): content passed as-is (existing behavior).
+ // - Dependency keys (key != parent_key): content merged under original keys,
+ // so the handler can check yaml["sni"], yaml["ssl_multicert"], etc.
+ std::unordered_map<std::string, std::vector<std::pair<std::string, YAML::Node>>> by_parent;
+
+ for (auto &vc : valid_configs) {
+ by_parent[vc.parent_key].emplace_back(vc.original_key, std::move(vc.content));
+ }
+
+ for (auto &[parent_key, items] : by_parent) {
+ if (items.size() == 1 && items[0].first == parent_key) {
+ // Single direct entry — pass content as-is (preserves existing behavior)
+ registry.set_passed_config(parent_key, items[0].second);
+ } else {
+ // Dependency key(s) or multiple items — merge under original keys
+ YAML::Node merged;
+ for (auto &[orig_key, content] : items) {
+ merged[orig_key] = content;
+ }
+ registry.set_passed_config(parent_key, merged);
+ }
+ Dbg(dbg_ctl_RPC, "Scheduling reload for '%s' (%zu config(s))", parent_key.c_str(), items.size());
+ registry.schedule_reload(parent_key);
+ }
+
+ // Build response
+ resp.result()["token"] = token;
+ resp.result()["created_time"] =
+ swoc::bwprint(buf, "{}", swoc::bwf::Date(ReloadCoordinator::Get_Instance().get_current_task()->get_created_time()));
+ resp.result()["message"].push_back("Inline reload scheduled");
+
+ return resp;
}
- // If any callback was register(TSMgmtUpdateRegister) for config notifications, then it will be eventually notify.
- FileManager::instance().invokeConfigPluginCallbacks();
- metrics[reconf_time].store(time(nullptr));
- metrics[reconf_req].store(0);
+ ///
+ // File source: default when no "configs" param
+ //
+ if (auto ret = ReloadCoordinator::Get_Instance().prepare_reload(token, "rldtk-", force); !ret.is_ok()) {
+ resp.result()["errors"].push_back(make_error(swoc::bwprint(buf, "Failed to prepare reload for token '{}': {}", token, ret),
+ errc(ConfigError::RELOAD_TASK_FAILED)));
+ return resp;
+ }
+
+ // Schedule the actual reload work asynchronously on ET_TASK
+ ::config::schedule_reload_work();
+
+ resp.result()["created_time"] =
+ swoc::bwprint(buf, "{}", swoc::bwf::Date(ReloadCoordinator::Get_Instance().get_current_task()->get_created_time()));
+ resp.result()["message"].push_back("Reload task scheduled");
+ resp.result()["token"] = token;
return resp;
}
+swoc::Rv<YAML::Node>
+get_reload_config_status(std::string_view const & /* id ATS_UNUSED */, YAML::Node const ¶ms)
+{
+ swoc::Rv<YAML::Node> resp;
+
+ auto make_error = [&](std::string const &msg, int code) -> YAML::Node {
+ YAML::Node err;
+ err["message"] = msg;
+ err["code"] = code;
+ return err;
+ };
+
+ const std::string token = params["token"] ? params["token"].as<std::string>() : "";
+
+ if (!token.empty()) {
+ if (auto [found, info] = ReloadCoordinator::Get_Instance().find_by_token(token); !found) {
+ std::string text;
+ Dbg(dbg_ctl_RPC, "No reload task found with token: %s", token.c_str());
+ resp.result()["errors"].push_back(
+ make_error(swoc::bwprint(text, "Token '{}' not found", token), errc(ConfigError::TOKEN_NOT_FOUND)));
+ resp.result()["token"] = token;
+ } else {
+ resp.result()["tasks"].push_back(info);
+ }
+ } else {
+ const int count = params["count"] ? params["count"].as<int>() : 1;
+ Dbg(dbg_ctl_RPC, "No token provided, count=%d", count);
+ // no token provided and no count, get last one.
+ auto infos = ReloadCoordinator::Get_Instance().get_all(count);
+ if (infos.empty()) {
+ resp.result()["errors"].push_back(make_error("No reload tasks found", errc(ConfigError::NO_RELOAD_TASKS)));
+ } else {
+ for (const auto &info : infos) {
+ resp.result()["tasks"].push_back(info);
+ }
+ }
+ }
+
+ return resp;
+}
} // namespace rpc::handlers::config
diff --git a/src/proxy/CMakeLists.txt b/src/proxy/CMakeLists.txt
index 93c1669784..34874f380f 100644
--- a/src/proxy/CMakeLists.txt
+++ b/src/proxy/CMakeLists.txt
@@ -41,8 +41,8 @@ add_library(ts::proxy ALIAS proxy)
target_link_libraries(
proxy
- PUBLIC ts::inkcache ts::inkevent ts::tsutil ts::tscore ts::inknet
- PRIVATE ts::rpcpublichandlers ts::jsonrpc_protocol ts::inkutils ts::tsapibackend
+ PUBLIC ts::inkcache ts::inkevent ts::tsutil ts::tscore ts::inknet ts::http
+ PRIVATE ts::http ts::rpcpublichandlers ts::jsonrpc_protocol ts::inkutils ts::tsapibackend ts::configmanager
)
add_subdirectory(hdrs)
diff --git a/src/proxy/CacheControl.cc b/src/proxy/CacheControl.cc
index ce5bb64985..ae0bc70e76 100644
--- a/src/proxy/CacheControl.cc
+++ b/src/proxy/CacheControl.cc
@@ -33,7 +33,7 @@
#include "tscore/Filenames.h"
#include "proxy/CacheControl.h"
#include "proxy/ControlMatcher.h"
-#include "iocore/eventsystem/ConfigProcessor.h"
+#include "mgmt/config/ConfigRegistry.h"
#include "proxy/http/HttpConfig.h"
namespace
{
@@ -85,30 +85,6 @@ struct CC_FreerContinuation : public Continuation {
CC_FreerContinuation(CC_table *ap) : Continuation(nullptr), p(ap) { SET_HANDLER(&CC_FreerContinuation::freeEvent); }
};
-// struct CC_UpdateContinuation
-//
-// Used to read the cache.conf file after the manager signals
-// a change
-//
-struct CC_UpdateContinuation : public Continuation {
- int
- file_update_handler(int /* etype ATS_UNUSED */, void * /* data ATS_UNUSED */)
- {
- reloadCacheControl();
- delete this;
- return EVENT_DONE;
- }
- CC_UpdateContinuation(Ptr<ProxyMutex> &m) : Continuation(m) { SET_HANDLER(&CC_UpdateContinuation::file_update_handler); }
-};
-
-int
-cacheControlFile_CB(const char * /* name ATS_UNUSED */, RecDataT /* data_type ATS_UNUSED */, RecData /* data ATS_UNUSED */,
- void * /* cookie ATS_UNUSED */)
-{
- eventProcessor.schedule_imm(new CC_UpdateContinuation(reconfig_mutex), ET_CALL);
- return 0;
-}
-
//
// Begin API functions
//
@@ -130,7 +106,14 @@ initCacheControl()
ink_assert(CacheControlTable == nullptr);
reconfig_mutex = new_ProxyMutex();
CacheControlTable = new CC_table("proxy.config.cache.control.filename", modulePrefix, &http_dest_tags);
- RecRegisterConfigUpdateCb("proxy.config.cache.control.filename", cacheControlFile_CB, nullptr);
+
+ config::ConfigRegistry::Get_Instance().register_config( // File registration.
+ "cache_control", // registry key
+ ts::filename::CACHE, // default filename
+ "proxy.config.cache.control.filename", // record holding the filename
+ [](ConfigContext ctx) { reloadCacheControl(ctx); }, // reload handler
+ config::ConfigSource::FileOnly, // no RPC content source
+ {"proxy.config.cache.control.filename"}); // trigger records
}
// void reloadCacheControl()
@@ -140,10 +123,9 @@ initCacheControl()
// lock acquire is also blocking
//
void
-reloadCacheControl()
+reloadCacheControl(ConfigContext ctx)
{
Note("%s loading ...", ts::filename::CACHE);
-
CC_table *newTable;
Dbg(dbg_ctl_cache_control, "%s updated, reloading", ts::filename::CACHE);
@@ -152,6 +134,7 @@ reloadCacheControl()
ink_atomic_swap(&CacheControlTable, newTable);
Note("%s finished loading", ts::filename::CACHE);
+ ctx.complete("Finished loading");
}
void
diff --git a/src/proxy/IPAllow.cc b/src/proxy/IPAllow.cc
index 56c52a621d..4eb1e99fca 100644
--- a/src/proxy/IPAllow.cc
+++ b/src/proxy/IPAllow.cc
@@ -27,6 +27,7 @@
#include <string_view>
#include "proxy/IPAllow.h"
+#include "mgmt/config/ConfigRegistry.h"
#include "records/RecCore.h"
#include "swoc/Errata.h"
#include "swoc/TextView.h"
@@ -73,8 +74,6 @@ size_t IpAllow::configid = 0;
bool IpAllow::accept_check_p = true; // initializing global flag for fast deny
uint8_t IpAllow::subjects[Subject::MAX_SUBJECTS];
-static ConfigUpdateHandler<IpAllow> *ipAllowUpdate;
-
//
// Begin API functions
//
@@ -93,9 +92,23 @@ IpAllow::startup()
// Should not have been initialized before
ink_assert(IpAllow::configid == 0);
- ipAllowUpdate = new ConfigUpdateHandler<IpAllow>();
- ipAllowUpdate->attach("proxy.config.cache.ip_allow.filename");
- ipAllowUpdate->attach("proxy.config.cache.ip_categories.filename");
+ config::ConfigRegistry::Get_Instance().register_config(
+ "ip_allow", // registry key
+ ts::filename::IP_ALLOW, // default filename
+ "proxy.config.cache.ip_allow.filename", // record holding the filename
+ [](ConfigContext ctx) { IpAllow::reconfigure(ctx); }, // reload handler
+ config::ConfigSource::FileOnly, // no RPC content source. Change to FileAndRpc if we want to support RPC.
+ // if supplied, YAML can be sourced by calling ctx.supplied_yaml()
+ {"proxy.config.cache.ip_allow.filename"}); // trigger records
+
+ // ip_categories is an auxiliary data file loaded by ip_allow (see BuildCategories()).
+ // Track it with FileManager for mtime detection and register a record callback
+ // so that changes to the file or the record trigger an ip_allow reload.
+ config::ConfigRegistry::Get_Instance().add_file_dependency(
+ "ip_allow", // config key to attach to
+ "proxy.config.cache.ip_categories.filename", // record holding the filename
+ ts::filename::IP_CATEGORIES, // default filename (used when record is "")
+ false); // not required
reconfigure();
@@ -108,34 +121,39 @@ IpAllow::startup()
}
void
-IpAllow::reconfigure()
+IpAllow::reconfigure(ConfigContext ctx)
{
- self_type *new_table;
-
+ self_type *new_table;
+ std::string text;
+ std::string errata_text;
Note("%s loading ...", ts::filename::IP_ALLOW);
+ ctx.in_progress();
new_table = new self_type("proxy.config.cache.ip_allow.filename", "proxy.config.cache.ip_categories.filename");
// IP rules need categories, so load them first (if they exist).
if (auto errata = new_table->BuildCategories(); !errata.is_ok()) {
- std::string text;
- swoc::bwprint(text, "{} failed to load\n{}", new_table->ip_categories_config_file, errata);
- Error("%s", text.c_str());
+ swoc::bwprint(text, "{} failed to load", new_table->ip_categories_config_file);
+ swoc::bwprint(errata_text, "{}", errata);
+ Error("%s\n%s", text.c_str(), errata_text.c_str());
+ ctx.fail(errata, "{} failed to load", new_table->ip_categories_config_file);
delete new_table;
return;
}
if (auto errata = new_table->BuildTable(); !errata.is_ok()) {
- std::string text;
- swoc::bwprint(text, "{} failed to load\n{}", ts::filename::IP_ALLOW, errata);
+ swoc::bwprint(text, "{} failed to load", ts::filename::IP_ALLOW);
+ swoc::bwprint(errata_text, "{}", errata);
if (errata.severity() <= ERRATA_ERROR) {
- Error("%s", text.c_str());
+ Error("%s\n%s", text.c_str(), errata_text.c_str());
} else {
- Fatal("%s", text.c_str());
+ Fatal("%s\n%s", text.c_str(), errata_text.c_str());
}
+ ctx.fail(errata, "{} failed to load", ts::filename::IP_ALLOW);
delete new_table;
return;
}
configid = configProcessor.set(configid, new_table);
Note("%s finished loading", ts::filename::IP_ALLOW);
+ ctx.complete("Finished loading");
}
IpAllow *
diff --git a/src/proxy/ParentSelection.cc b/src/proxy/ParentSelection.cc
index 0870bcb9bf..3290778acf 100644
--- a/src/proxy/ParentSelection.cc
+++ b/src/proxy/ParentSelection.cc
@@ -24,7 +24,7 @@
#include "proxy/ParentConsistentHash.h"
#include "proxy/ParentRoundRobin.h"
#include "proxy/ControlMatcher.h"
-#include "iocore/eventsystem/ConfigProcessor.h"
+#include "mgmt/config/ConfigRegistry.h"
#include "proxy/HostStatus.h"
#include "proxy/hdrs/HTTP.h"
#include "proxy/http/HttpTransact.h"
@@ -42,9 +42,8 @@ using namespace std::literals;
using P_table = ControlMatcher<ParentRecord, ParentResult>;
// Global Vars for Parent Selection
-static const char modulePrefix[] = "[ParentSelection]";
-static ConfigUpdateHandler<ParentConfig> *parentConfigUpdate = nullptr;
-static int self_detect = 2;
+static const char modulePrefix[] = "[ParentSelection]";
+static int self_detect = 2;
// Config var names
static const char *file_var = "proxy.config.http.parent_proxy.file";
@@ -288,24 +287,20 @@ int ParentConfig::m_id = 0;
void
ParentConfig::startup()
{
- parentConfigUpdate = new ConfigUpdateHandler<ParentConfig>();
+ config::ConfigRegistry::Get_Instance().register_config(
+ "parent_proxy", // registry key
+ ts::filename::PARENT, // default filename
+ file_var, // record holding the filename
+ [](ConfigContext ctx) { ParentConfig::reconfigure(ctx); }, // reload handler
+ config::ConfigSource::FileOnly, // file-based only
+ {file_var, default_var, retry_var, threshold_var}); // trigger records
// Load the initial configuration
reconfigure();
-
- // Setup the callbacks for reconfiuration
- // parent table
- parentConfigUpdate->attach(file_var);
- // default parent
- parentConfigUpdate->attach(default_var);
- // Retry time
- parentConfigUpdate->attach(retry_var);
- // Fail Threshold
- parentConfigUpdate->attach(threshold_var);
}
void
-ParentConfig::reconfigure()
+ParentConfig::reconfigure(ConfigContext ctx)
{
Note("%s loading ...", ts::filename::PARENT);
@@ -324,6 +319,7 @@ ParentConfig::reconfigure()
}
Note("%s finished loading", ts::filename::PARENT);
+ ctx.complete("Finished loading");
}
void
diff --git a/src/proxy/ReverseProxy.cc b/src/proxy/ReverseProxy.cc
index 341c2c7de4..9fb8da55c5 100644
--- a/src/proxy/ReverseProxy.cc
+++ b/src/proxy/ReverseProxy.cc
@@ -30,8 +30,8 @@
#include "tscore/ink_platform.h"
#include "tscore/Filenames.h"
#include <dlfcn.h>
-#include "iocore/eventsystem/ConfigProcessor.h"
#include "proxy/ReverseProxy.h"
+#include "mgmt/config/ConfigRegistry.h"
#include "tscore/MatcherUtils.h"
#include "tscore/Tokenizer.h"
#include "ts/remap.h"
@@ -70,6 +70,17 @@ init_reverse_proxy()
reconfig_mutex = new_ProxyMutex();
rewrite_table = new UrlRewrite();
+ // Register with ConfigRegistry BEFORE load() so that remap.config is in
+ // FileManager's bindings when .include directives call configFileChild()
+ // to register child files (e.g. test.inc).
+ config::ConfigRegistry::Get_Instance().register_config("remap", // registry key
+ ts::filename::REMAP, // default filename
+ "proxy.config.url_remap.filename", // record holding the filename
+ [](ConfigContext ctx) { reloadUrlRewrite(ctx); }, // reload handler
+ config::ConfigSource::FileOnly, // file-based only
+ {"proxy.config.url_remap.filename", // trigger records
+ "proxy.config.proxy_name", "proxy.config.http.referer_default_redirect"});
+
Note("%s loading ...", ts::filename::REMAP);
if (!rewrite_table->load()) {
Emergency("%s failed to load", ts::filename::REMAP);
@@ -77,10 +88,7 @@ init_reverse_proxy()
Note("%s finished loading", ts::filename::REMAP);
}
- RecRegisterConfigUpdateCb("proxy.config.url_remap.filename", url_rewrite_CB, (void *)FILE_CHANGED);
- RecRegisterConfigUpdateCb("proxy.config.proxy_name", url_rewrite_CB, (void *)TSNAME_CHANGED);
RecRegisterConfigUpdateCb("proxy.config.reverse_proxy.enabled", url_rewrite_CB, (void *)REVERSE_CHANGED);
- RecRegisterConfigUpdateCb("proxy.config.http.referer_default_redirect", url_rewrite_CB, (void *)HTTP_DEFAULT_REDIRECT_CHANGED);
// Hold at least one lease, until we reload the configuration
rewrite_table->acquire();
@@ -109,18 +117,6 @@ response_url_remap(HTTPHdr *response_header, UrlRewrite *table)
// End API Functions
//
-/** Used to read the remap.config file after the manager signals a change. */
-struct UR_UpdateContinuation : public Continuation {
- int
- file_update_handler(int /* etype ATS_UNUSED */, void * /* data ATS_UNUSED */)
- {
- static_cast<void>(reloadUrlRewrite());
- delete this;
- return EVENT_DONE;
- }
- UR_UpdateContinuation(Ptr<ProxyMutex> &m) : Continuation(m) { SET_HANDLER(&UR_UpdateContinuation::file_update_handler); }
-};
-
bool
urlRewriteVerify()
{
@@ -134,15 +130,17 @@ urlRewriteVerify()
*/
bool
-reloadUrlRewrite()
+reloadUrlRewrite(ConfigContext ctx)
{
+ std::string msg_buffer;
+ msg_buffer.reserve(1024);
UrlRewrite *newTable, *oldTable;
Note("%s loading ...", ts::filename::REMAP);
Dbg(dbg_ctl_url_rewrite, "%s updated, reloading...", ts::filename::REMAP);
newTable = new UrlRewrite();
if (newTable->load()) {
- static const char *msg_format = "%s finished loading";
+ swoc::bwprint(msg_buffer, "{} finished loading", ts::filename::REMAP);
// Hold at least one lease, until we reload the configuration
newTable->acquire();
@@ -155,43 +153,25 @@ reloadUrlRewrite()
// Release the old one
oldTable->release();
- Dbg(dbg_ctl_url_rewrite, msg_format, ts::filename::REMAP);
- Note(msg_format, ts::filename::REMAP);
+ Dbg(dbg_ctl_url_rewrite, "%s", msg_buffer.c_str());
+ Note("%s", msg_buffer.c_str());
+ ctx.complete(msg_buffer);
return true;
} else {
- static const char *msg_format = "%s failed to load";
+ swoc::bwprint(msg_buffer, "{} failed to load", ts::filename::REMAP);
delete newTable;
- Dbg(dbg_ctl_url_rewrite, msg_format, ts::filename::REMAP);
- Error(msg_format, ts::filename::REMAP);
+ Dbg(dbg_ctl_url_rewrite, "%s", msg_buffer.c_str());
+ Error("%s", msg_buffer.c_str());
+ ctx.fail(msg_buffer);
return false;
}
}
int
-url_rewrite_CB(const char * /* name ATS_UNUSED */, RecDataT /* data_type ATS_UNUSED */, RecData data, void *cookie)
+url_rewrite_CB(const char * /* name ATS_UNUSED */, RecDataT /* data_type ATS_UNUSED */, RecData data,
+ void * /* cookie ATS_UNUSED */)
{
- int my_token = static_cast<int>((long)cookie);
-
- switch (my_token) {
- case REVERSE_CHANGED:
- rewrite_table->SetReverseFlag(data.rec_int);
- break;
-
- case TSNAME_CHANGED:
- case FILE_CHANGED:
- case HTTP_DEFAULT_REDIRECT_CHANGED:
- eventProcessor.schedule_imm(new UR_UpdateContinuation(reconfig_mutex), ET_TASK);
- break;
-
- case URL_REMAP_MODE_CHANGED:
- // You need to restart TS.
- break;
-
- default:
- ink_assert(0);
- break;
- }
-
+ rewrite_table->SetReverseFlag(data.rec_int);
return 0;
}
diff --git a/src/proxy/hdrs/CMakeLists.txt b/src/proxy/hdrs/CMakeLists.txt
index 09dfc6f8b6..45a084dd6e 100644
--- a/src/proxy/hdrs/CMakeLists.txt
+++ b/src/proxy/hdrs/CMakeLists.txt
@@ -55,7 +55,14 @@ if(BUILD_TESTING)
unit_tests/unit_test_main.cc
)
target_link_libraries(
- test_proxy_hdrs PRIVATE ts::hdrs ts::tscore ts::inkevent libswoc::libswoc Catch2::Catch2WithMain lshpack
+ test_proxy_hdrs
+ PRIVATE ts::hdrs
+ ts::tscore
+ ts::inkevent
+ libswoc::libswoc
+ Catch2::Catch2WithMain
+ lshpack
+ configmanager
)
add_catch2_test(NAME test_proxy_hdrs COMMAND test_proxy_hdrs)
diff --git a/src/proxy/http/PreWarmConfig.cc b/src/proxy/http/PreWarmConfig.cc
index bfe1582518..4adab6e212 100644
--- a/src/proxy/http/PreWarmConfig.cc
+++ b/src/proxy/http/PreWarmConfig.cc
@@ -23,6 +23,7 @@
#include "proxy/http/PreWarmConfig.h"
#include "proxy/http/PreWarmManager.h"
+#include "mgmt/config/ConfigRegistry.h"
////
// PreWarmConfigParams
@@ -43,22 +44,21 @@ PreWarmConfigParams::PreWarmConfigParams()
void
PreWarmConfig::startup()
{
- _config_update_handler = std::make_unique<ConfigUpdateHandler<PreWarmConfig>>();
-
- // dynamic configs
- _config_update_handler->attach("proxy.config.tunnel.prewarm.event_period");
- _config_update_handler->attach("proxy.config.tunnel.prewarm.algorithm");
+ config::ConfigRegistry::Get_Instance().register_record_config(
+ "prewarm", [](ConfigContext ctx) { PreWarmConfig::reconfigure(ctx); },
+ {"proxy.config.tunnel.prewarm.event_period", "proxy.config.tunnel.prewarm.algorithm"});
reconfigure();
}
void
-PreWarmConfig::reconfigure()
+PreWarmConfig::reconfigure(ConfigContext ctx)
{
PreWarmConfigParams *params = new PreWarmConfigParams();
_config_id = configProcessor.set(_config_id, params);
prewarmManager.reconfigure();
+ ctx.complete("PreWarm config published.");
}
PreWarmConfigParams *
diff --git a/src/proxy/http/remap/unit-tests/CMakeLists.txt b/src/proxy/http/remap/unit-tests/CMakeLists.txt
index 4de87e8f08..3a7bb2f607 100644
--- a/src/proxy/http/remap/unit-tests/CMakeLists.txt
+++ b/src/proxy/http/remap/unit-tests/CMakeLists.txt
@@ -201,10 +201,20 @@ target_compile_definitions(
target_include_directories(test_NextHopStrategyFactory PRIVATE ${PROJECT_SOURCE_DIR}/tests/include)
target_link_libraries(
- test_NextHopStrategyFactory PRIVATE Catch2::Catch2WithMain ts::hdrs ts::inkutils tscore libswoc::libswoc
- yaml-cpp::yaml-cpp
+ test_NextHopStrategyFactory
+ PRIVATE Catch2::Catch2WithMain
+ ts::hdrs
+ ts::inkutils
+ tscore
+ libswoc::libswoc
+ yaml-cpp::yaml-cpp
+ configmanager
)
+if(NOT APPLE)
+ target_link_options(test_NextHopStrategyFactory PRIVATE -Wl,--allow-multiple-definition)
+endif()
+
add_catch2_test(NAME test_NextHopStrategyFactory COMMAND $<TARGET_FILE:test_NextHopStrategyFactory>)
### test_NextHopRoundRobin ########################################################################
@@ -234,8 +244,13 @@ target_link_libraries(
tscore
libswoc::libswoc
yaml-cpp::yaml-cpp
+ configmanager
)
+if(NOT APPLE)
+ target_link_options(test_NextHopRoundRobin PRIVATE -Wl,--allow-multiple-definition)
+endif()
+
add_catch2_test(NAME test_NextHopRoundRobin COMMAND $<TARGET_FILE:test_NextHopRoundRobin>)
### test_NextHopConsistentHash ########################################################################
@@ -267,8 +282,13 @@ target_link_libraries(
ts::inkutils
libswoc::libswoc
yaml-cpp::yaml-cpp
+ configmanager
)
+if(NOT APPLE)
+ target_link_options(test_NextHopConsistentHash PRIVATE -Wl,--allow-multiple-definition)
+endif()
+
add_catch2_test(NAME test_NextHopConsistentHash COMMAND $<TARGET_FILE:test_NextHopConsistentHash>)
### test_RemapRules ########################################################################
diff --git a/src/proxy/http2/CMakeLists.txt b/src/proxy/http2/CMakeLists.txt
index e769fe3622..b302a0dcbe 100644
--- a/src/proxy/http2/CMakeLists.txt
+++ b/src/proxy/http2/CMakeLists.txt
@@ -49,7 +49,7 @@ if(BUILD_TESTING)
unit_tests/test_Http2Frame.cc
unit_tests/test_HpackIndexingTable.cc
)
- target_link_libraries(test_http2 PRIVATE Catch2::Catch2WithMain records tscore hdrs inkevent)
+ target_link_libraries(test_http2 PRIVATE Catch2::Catch2WithMain records tscore hdrs inkevent configmanager)
add_catch2_test(NAME test_http2 COMMAND test_http2)
add_executable(test_Http2DependencyTree unit_tests/test_Http2DependencyTree.cc)
@@ -57,7 +57,7 @@ if(BUILD_TESTING)
add_catch2_test(NAME test_Http2DependencyTree COMMAND test_Http2DependencyTree)
add_executable(test_HPACK test_HPACK.cc HPACK.cc)
- target_link_libraries(test_HPACK PRIVATE tscore hdrs inkevent)
+ target_link_libraries(test_HPACK PRIVATE tscore hdrs inkevent configmanager)
add_test(NAME test_HPACK COMMAND test_HPACK -i ${CMAKE_CURRENT_SOURCE_DIR}/hpack-tests -o ./results)
endif()
diff --git a/src/proxy/logging/LogConfig.cc b/src/proxy/logging/LogConfig.cc
index dfa20f7d51..9af71a7e40 100644
--- a/src/proxy/logging/LogConfig.cc
+++ b/src/proxy/logging/LogConfig.cc
@@ -48,6 +48,7 @@ using namespace std::literals;
#include "tscore/SimpleTokenizer.h"
#include "proxy/logging/YamlLogConfig.h"
+#include "mgmt/config/ConfigRegistry.h"
#define DISK_IS_CONFIG_FULL_MESSAGE \
"Access logging to local log directory suspended - " \
@@ -286,6 +287,13 @@ LogConfig::init(LogConfig *prev_config)
ink_assert(!initialized);
+ // Inherit the reload context so evaluate_config() can log parse details
+ // and access RPC-supplied YAML content. At startup prev_config is nullptr,
+ // so reload_ctx stays default-constructed (all calls are safe no-ops).
+ if (prev_config) {
+ reload_ctx = prev_config->reload_ctx;
+ }
+
update_space_used();
// create log objects
@@ -411,13 +419,13 @@ LogConfig::setup_log_objects()
function from the logging thread.
-------------------------------------------------------------------------*/
-int
-LogConfig::reconfigure(const char * /* name ATS_UNUSED */, RecDataT /* data_type ATS_UNUSED */, RecData /* data ATS_UNUSED */,
- void * /* cookie ATS_UNUSED */)
+void
+LogConfig::reconfigure(ConfigContext ctx)
{
Dbg(dbg_ctl_log_config, "Reconfiguration request accepted");
+
Log::config->reconfiguration_needed = true;
- return 0;
+ Log::config->reload_ctx = ctx;
}
/*-------------------------------------------------------------------------
@@ -455,8 +463,13 @@ LogConfig::register_config_callbacks()
"proxy.config.diags.debug.throttling_interval_msec",
};
+ auto ®istry = config::ConfigRegistry::Get_Instance();
+ registry.register_config(
+ "logging", ts::filename::LOGGING, "proxy.config.log.config.filename", [](ConfigContext ctx) { LogConfig::reconfigure(ctx); },
+ config::ConfigSource::FileOnly);
+
for (unsigned i = 0; i < countof(names); ++i) {
- RecRegisterConfigUpdateCb(names[i], &LogConfig::reconfigure, nullptr);
+ registry.attach("logging", names[i]);
}
}
@@ -762,6 +775,7 @@ LogConfig::evaluate_config()
struct stat sbuf;
if (stat(path.get(), &sbuf) == -1 && errno == ENOENT) {
Warning("logging configuration '%s' doesn't exist", path.get());
+ reload_ctx.fail("logging configuration '{}' doesn't exist", path.get());
return false;
}
@@ -771,8 +785,10 @@ LogConfig::evaluate_config()
bool zret = y.parse(path.get());
if (zret) {
Note("%s finished loading", path.get());
+ reload_ctx.complete("{} finished loading", path.get());
} else {
Note("%s failed to load", path.get());
+ reload_ctx.fail("{} failed to load", path.get());
}
return zret;
diff --git a/src/records/CMakeLists.txt b/src/records/CMakeLists.txt
index 907ec4f24c..e168b7dce1 100644
--- a/src/records/CMakeLists.txt
+++ b/src/records/CMakeLists.txt
@@ -30,21 +30,25 @@ add_library(
RecordsConfig.cc
RecordsConfigUtils.cc
RecRawStats.cc
+ # Reload infrastructure
+ ${CMAKE_SOURCE_DIR}/src/mgmt/config/ReloadCoordinator.cc
+ ${CMAKE_SOURCE_DIR}/src/mgmt/config/ConfigReloadTrace.cc
+ ${CMAKE_SOURCE_DIR}/src/mgmt/config/ConfigContext.cc
)
add_library(ts::records ALIAS records)
target_link_libraries(
records
- PUBLIC ts::tscore yaml-cpp::yaml-cpp
+ PUBLIC ts::tscore yaml-cpp::yaml-cpp ts::inkevent
PRIVATE ts::tsutil
)
if(BUILD_TESTING)
add_executable(
test_records unit_tests/unit_test_main.cc unit_tests/test_RecHttp.cc unit_tests/test_RecUtils.cc
- unit_tests/test_RecRegister.cc
+ unit_tests/test_RecRegister.cc unit_tests/test_ConfigReloadTask.cc unit_tests/test_ConfigRegistry.cc
)
- target_link_libraries(test_records PRIVATE records Catch2::Catch2 ts::tscore libswoc::libswoc ts::inkevent)
+ target_link_libraries(test_records PRIVATE records configmanager inkevent Catch2::Catch2 ts::tscore libswoc::libswoc)
add_catch2_test(NAME test_records COMMAND test_records)
endif()
diff --git a/src/records/P_RecCore.cc b/src/records/P_RecCore.cc
index ebc071d284..40e8de7e87 100644
--- a/src/records/P_RecCore.cc
+++ b/src/records/P_RecCore.cc
@@ -544,3 +544,9 @@ RecSetSyncRequired(const char *name, bool lock)
return err;
}
+
+void
+RecFlushConfigUpdateCbs()
+{
+ RecExecConfigUpdateCbs(REC_PROCESS_UPDATE_REQUIRED);
+}
diff --git a/src/records/RecCore.cc b/src/records/RecCore.cc
index cf816550c4..9b5da228b8 100644
--- a/src/records/RecCore.cc
+++ b/src/records/RecCore.cc
@@ -1072,16 +1072,20 @@ RecConfigReadPersistentStatsPath()
//-------------------------------------------------------------------------
/// Generate a warning if the record is a configuration name/value but is not registered.
void
-RecConfigWarnIfUnregistered()
+RecConfigWarnIfUnregistered(ConfigContext ctx)
{
RecDumpRecords(
RECT_CONFIG,
- [](RecT, void *, int registered_p, const char *name, int, RecData *) -> void {
+ [](RecT, void *edata, int registered_p, const char *name, int, RecData *) -> void {
if (!registered_p) {
- Warning("Unrecognized configuration value '%s'", name);
+ std::string err;
+ swoc::bwprint(err, "Unrecognized configuration value '{}'", name);
+ Warning("%s", err.c_str());
+ auto *ctx_ptr = static_cast<ConfigContext *>(edata);
+ ctx_ptr->log(err);
}
},
- nullptr);
+ &ctx);
}
//-------------------------------------------------------------------------
diff --git a/src/records/RecordsConfig.cc b/src/records/RecordsConfig.cc
index a0d9e6f749..85da374f0c 100644
--- a/src/records/RecordsConfig.cc
+++ b/src/records/RecordsConfig.cc
@@ -261,6 +261,12 @@ static constexpr RecordElement RecordsConfig[] =
//##############################################################################
{RECT_CONFIG, "proxy.config.admin.user_id", RECD_STRING, TS_PKGSYSUSER, RECU_NULL, RR_REQUIRED, RECC_NULL, nullptr, RECA_READ_ONLY}
,
+ //# Config reload timeout - supports duration strings: "30s", "5min", "1h", "0" (disabled)
+ {RECT_CONFIG, "proxy.config.admin.reload.timeout", RECD_STRING, "1h", RECU_DYNAMIC, RR_NULL, RECC_NULL, nullptr, RECA_NULL}
+ ,
+ //# Config reload check interval - how often to check task progress (min: 1s)
+ {RECT_CONFIG, "proxy.config.admin.reload.check_interval", RECD_STRING, "2s", RECU_DYNAMIC, RR_NULL, RECC_NULL, nullptr, RECA_NULL}
+ ,
//##############################################################################
//#
//# UDP configuration stuff: hidden variables
diff --git a/src/records/unit_tests/test_ConfigRegistry.cc b/src/records/unit_tests/test_ConfigRegistry.cc
new file mode 100644
index 0000000000..29e26de9c4
--- /dev/null
+++ b/src/records/unit_tests/test_ConfigRegistry.cc
@@ -0,0 +1,207 @@
+/** @file
+
+ Unit tests for ConfigRegistry: resolve(), add_file_and_node_dependency(), dependency key routing.
+
+ @section license License
+
+ Licensed to the Apache Software Foundation (ASF) under one
+ or more contributor license agreements. See the NOTICE file
+ distributed with this work for additional information
+ regarding copyright ownership. The ASF licenses this file
+ to you under the Apache License, Version 2.0 (the
+ "License"); you may not use this file except in compliance
+ with the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+*/
+
+#include <catch2/catch_test_macros.hpp>
+
+#include "mgmt/config/ConfigRegistry.h"
+#include "records/RecCore.h"
+
+using config::ConfigRegistry;
+using config::ConfigSource;
+
+// Shared no-op handler for test registrations
+static config::ConfigReloadHandler noop_handler = [](ConfigContext) {};
+
+namespace
+{
+// Register test-specific records so RecRegisterConfigUpdateCb succeeds.
+// Called once; RecRegisterConfigUpdateCb requires the record to exist in g_records_ht.
+void
+ensure_test_records()
+{
+ static bool done = false;
+ if (done) {
+ return;
+ }
+ done = true;
+ RecRegisterConfigString(RECT_CONFIG, "test.registry.dep.filename1", const_cast<char *>("test_sni.yaml"), RECU_NULL, RECC_NULL,
+ nullptr, REC_SOURCE_DEFAULT);
+ RecRegisterConfigString(RECT_CONFIG, "test.registry.dep.filename2", const_cast<char *>("test_multicert.config"), RECU_NULL,
+ RECC_NULL, nullptr, REC_SOURCE_DEFAULT);
+ RecRegisterConfigString(RECT_CONFIG, "test.registry.dep.filename3", const_cast<char *>("test_child_a.yaml"), RECU_NULL, RECC_NULL,
+ nullptr, REC_SOURCE_DEFAULT);
+ RecRegisterConfigString(RECT_CONFIG, "test.registry.dep.filename4", const_cast<char *>("test_child_b.config"), RECU_NULL,
+ RECC_NULL, nullptr, REC_SOURCE_DEFAULT);
+ RecRegisterConfigString(RECT_CONFIG, "test.registry.dep.filename5", const_cast<char *>("test_dep_for_b.yaml"), RECU_NULL,
+ RECC_NULL, nullptr, REC_SOURCE_DEFAULT);
+ RecRegisterConfigString(RECT_CONFIG, "test.registry.dep.dup", const_cast<char *>("dup.yaml"), RECU_NULL, RECC_NULL, nullptr,
+ REC_SOURCE_DEFAULT);
+}
+} // namespace
+
+// ─── Direct entry resolution (no Records/FileManager needed) ──────────────────
+
+TEST_CASE("ConfigRegistry resolve() with direct entries", "[config][registry][resolve]")
+{
+ auto ® = ConfigRegistry::Get_Instance();
+
+ // No file, no triggers — pure map operation
+ reg.register_config("test_direct_resolve", "", "", noop_handler, ConfigSource::FileOnly, {});
+
+ SECTION("Direct entry found")
+ {
+ auto [parent_key, entry] = reg.resolve("test_direct_resolve");
+ REQUIRE(entry != nullptr);
+ REQUIRE(parent_key == "test_direct_resolve");
+ REQUIRE(entry->key == "test_direct_resolve");
+ }
+
+ SECTION("Unknown key returns nullptr")
+ {
+ auto [parent_key, entry] = reg.resolve("nonexistent_key_xyz");
+ REQUIRE(entry == nullptr);
+ REQUIRE(parent_key.empty());
+ }
+}
+
+// ─── add_file_and_node_dependency: basic ──────────────────────────────────────
+
+TEST_CASE("ConfigRegistry add_file_and_node_dependency resolves to parent", "[config][registry][dependency]")
+{
+ ensure_test_records();
+ auto ® = ConfigRegistry::Get_Instance();
+
+ reg.register_config("test_coordinator", "", "", noop_handler, ConfigSource::FileAndRpc, {});
+
+ int ret =
+ reg.add_file_and_node_dependency("test_coordinator", "test_dep_sni", "test.registry.dep.filename1", "test_sni.yaml", false);
+ REQUIRE(ret == 0);
+
+ // The dep_key resolves to the parent entry
+ auto [parent_key, entry] = reg.resolve("test_dep_sni");
+ REQUIRE(entry != nullptr);
+ REQUIRE(parent_key == "test_coordinator");
+ REQUIRE(entry->key == "test_coordinator");
+ REQUIRE(entry->source == ConfigSource::FileAndRpc);
+
+ // find() and contains() should NOT find dep_keys — only resolve() does
+ REQUIRE(reg.find("test_dep_sni") == nullptr);
+ REQUIRE_FALSE(reg.contains("test_dep_sni"));
+}
+
+// ─── add_file_and_node_dependency: rejection cases ────────────────────────────
+
+TEST_CASE("ConfigRegistry add_file_and_node_dependency rejects duplicates", "[config][registry][dependency]")
+{
+ ensure_test_records();
+ auto ® = ConfigRegistry::Get_Instance();
+
+ reg.register_config("test_coord_dup", "", "", noop_handler, ConfigSource::FileAndRpc, {});
+
+ int ret1 = reg.add_file_and_node_dependency("test_coord_dup", "test_dup_dep", "test.registry.dep.dup", "dup.yaml", false);
+ REQUIRE(ret1 == 0);
+ // Same dep_key again should fail
+ int ret2 = reg.add_file_and_node_dependency("test_coord_dup", "test_dup_dep", "test.registry.dep.dup", "dup.yaml", false);
+ REQUIRE(ret2 == -1);
+}
+
+TEST_CASE("ConfigRegistry add_file_and_node_dependency rejects dep colliding with entry", "[config][registry][dependency]")
+{
+ ensure_test_records();
+ auto ® = ConfigRegistry::Get_Instance();
+
+ reg.register_config("test_coord_coll", "", "", noop_handler, ConfigSource::FileAndRpc, {});
+ reg.register_config("test_collision_entry", "", "", noop_handler, ConfigSource::FileOnly, {});
+
+ // Dep_key same name as existing entry should fail
+ int ret = reg.add_file_and_node_dependency("test_coord_coll", "test_collision_entry", "test.registry.dep.filename2",
+ "test_multicert.config", false);
+ REQUIRE(ret == -1);
+}
+
+TEST_CASE("ConfigRegistry add_file_and_node_dependency rejects unknown parent", "[config][registry][dependency]")
+{
+ ensure_test_records();
+ auto ® = ConfigRegistry::Get_Instance();
+
+ int ret = reg.add_file_and_node_dependency("nonexistent_parent", "test_orphan_dep", "test.registry.dep.filename1",
+ "test_sni.yaml", false);
+ REQUIRE(ret == -1);
+}
+
+// ─── Multiple dep_keys for same parent ────────────────────────────────────────
+
+TEST_CASE("ConfigRegistry multiple dep_keys resolve to same parent", "[config][registry][dependency][grouping]")
+{
+ ensure_test_records();
+ auto ® = ConfigRegistry::Get_Instance();
+
+ reg.register_config("test_multi_parent", "", "", noop_handler, ConfigSource::FileAndRpc, {});
+
+ int ret1 =
+ reg.add_file_and_node_dependency("test_multi_parent", "test_child_a", "test.registry.dep.filename3", "child_a.yaml", false);
+ int ret2 =
+ reg.add_file_and_node_dependency("test_multi_parent", "test_child_b", "test.registry.dep.filename4", "child_b.config", false);
+ REQUIRE(ret1 == 0);
+ REQUIRE(ret2 == 0);
+
+ // Both dep_keys resolve to the same parent
+ auto [key_a, entry_a] = reg.resolve("test_child_a");
+ auto [key_b, entry_b] = reg.resolve("test_child_b");
+
+ REQUIRE(entry_a != nullptr);
+ REQUIRE(entry_b != nullptr);
+ REQUIRE(key_a == "test_multi_parent");
+ REQUIRE(key_b == "test_multi_parent");
+ REQUIRE(entry_a == entry_b); // same Entry*
+
+ // Parent itself still resolves directly
+ auto [parent_key, entry] = reg.resolve("test_multi_parent");
+ REQUIRE(entry != nullptr);
+ REQUIRE(parent_key == "test_multi_parent");
+}
+
+// ─── resolve() with mixed entries and deps ────────────────────────────────────
+
+TEST_CASE("ConfigRegistry resolve() does not confuse entries and deps", "[config][registry][resolve]")
+{
+ ensure_test_records();
+ auto ® = ConfigRegistry::Get_Instance();
+
+ reg.register_config("test_entry_a", "", "", noop_handler, ConfigSource::FileOnly, {});
+ reg.register_config("test_entry_b", "", "", noop_handler, ConfigSource::FileAndRpc, {});
+
+ int ret = reg.add_file_and_node_dependency("test_entry_b", "test_dep_for_b", "test.registry.dep.filename5", "dep_b.yaml", false);
+ REQUIRE(ret == 0);
+
+ // Direct entry resolves to itself
+ auto [key_a, entry_a] = reg.resolve("test_entry_a");
+ REQUIRE(entry_a != nullptr);
+ REQUIRE(key_a == "test_entry_a");
+
+ // Dep key resolves to its parent, not other entries
+ auto [key_b, entry_b] = reg.resolve("test_dep_for_b");
+ REQUIRE(entry_b != nullptr);
+ REQUIRE(key_b == "test_entry_b");
+ REQUIRE(entry_b->source == ConfigSource::FileAndRpc);
+}
diff --git a/src/records/unit_tests/test_ConfigReloadTask.cc b/src/records/unit_tests/test_ConfigReloadTask.cc
new file mode 100644
index 0000000000..9fa1704b31
--- /dev/null
+++ b/src/records/unit_tests/test_ConfigReloadTask.cc
@@ -0,0 +1,148 @@
+/** @file
+
+ Unit tests for ConfigReloadProgress timeout configuration and ReloadCoordinator::cancel_reload
+
+ @section license License
+
+ Licensed to the Apache Software Foundation (ASF) under one
+ or more contributor license agreements. See the NOTICE file
+ distributed with this work for additional information
+ regarding copyright ownership. The ASF licenses this file
+ to you under the Apache License, Version 2.0 (the
+ "License"); you may not use this file except in compliance
+ with the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+*/
+
+#include <catch2/catch_test_macros.hpp>
+
+#include "mgmt/config/ConfigReloadTrace.h"
+#include "mgmt/config/ReloadCoordinator.h"
+
+// Note: These tests verify the default values and basic logic.
+// Full integration testing with records is done via autest.
+
+TEST_CASE("ConfigReloadProgress default timeout", "[config][reload][timeout]")
+{
+ SECTION("Default timeout is 1 hour")
+ {
+ // Default should be "1h" which equals 3600000ms
+ REQUIRE(std::string(ConfigReloadProgress::DEFAULT_TIMEOUT) == "1h");
+ }
+}
+
+TEST_CASE("ConfigReloadProgress constants", "[config][reload][timeout]")
+{
+ SECTION("Record names are correct")
+ {
+ REQUIRE(std::string(ConfigReloadProgress::RECORD_TIMEOUT) == "proxy.config.admin.reload.timeout");
+ REQUIRE(std::string(ConfigReloadProgress::RECORD_CHECK_INTERVAL) == "proxy.config.admin.reload.check_interval");
+ }
+
+ SECTION("Default values are sensible")
+ {
+ // Default timeout should be "1h"
+ REQUIRE(std::string(ConfigReloadProgress::DEFAULT_TIMEOUT) == "1h");
+ // Default check interval should be "2s"
+ REQUIRE(std::string(ConfigReloadProgress::DEFAULT_CHECK_INTERVAL) == "2s");
+ // Minimum check interval should be 1 second
+ REQUIRE(ConfigReloadProgress::MIN_CHECK_INTERVAL_MS == 1000);
+ }
+}
+
+TEST_CASE("ReloadCoordinator mark_task_as_stale with no task", "[config][reload][stale]")
+{
+ auto &coord = ReloadCoordinator::Get_Instance();
+
+ SECTION("mark_task_as_stale returns false when no current task")
+ {
+ // Ensure no task is running (might have leftover from previous tests)
+ // Note: In a real scenario, we'd wait for any existing task to complete
+
+ // Try to mark stale with non-existent token
+ bool marked = coord.mark_task_as_stale("nonexistent-token-xyz", "Test stale");
+ REQUIRE(marked == false);
+ }
+}
+
+TEST_CASE("ConfigReloadTask state transitions", "[config][reload][state]")
+{
+ SECTION("Task can be marked as timeout (bad state)")
+ {
+ auto task = std::make_shared<ConfigReloadTask>("test-token", "test task", false, nullptr);
+
+ // Initial state should be CREATED
+ REQUIRE(task->get_state() == ConfigReloadTask::State::CREATED);
+
+ // Mark as in progress first
+ task->set_in_progress();
+ REQUIRE(task->get_state() == ConfigReloadTask::State::IN_PROGRESS);
+
+ // Now mark as bad state (timeout)
+ task->mark_as_bad_state("Test timeout");
+ REQUIRE(task->get_state() == ConfigReloadTask::State::TIMEOUT);
+
+ // Verify logs contain the reason
+ auto logs = task->get_logs();
+ REQUIRE(!logs.empty());
+ REQUIRE(logs.back().find("Test timeout") != std::string::npos);
+ }
+
+ SECTION("Terminal states cannot be changed via mark_as_bad_state")
+ {
+ auto task = std::make_shared<ConfigReloadTask>("test-token-2", "test task 2", false, nullptr);
+
+ // Set to SUCCESS (terminal state)
+ task->set_completed();
+ REQUIRE(task->get_state() == ConfigReloadTask::State::SUCCESS);
+
+ // Try to mark as timeout — terminal guard rejects the transition
+ task->mark_as_bad_state("Should not apply");
+ REQUIRE(task->get_state() == ConfigReloadTask::State::SUCCESS);
+
+ // Verify the rejected reason was NOT added to logs
+ auto logs = task->get_logs();
+ for (const auto &log : logs) {
+ REQUIRE(log.find("Should not apply") == std::string::npos);
+ }
+ }
+
+ SECTION("Terminal states cannot be changed via set_state_and_notify")
+ {
+ auto task = std::make_shared<ConfigReloadTask>("test-token-3", "test task 3", false, nullptr);
+
+ // Set to FAIL (terminal state)
+ task->set_failed();
+ REQUIRE(task->get_state() == ConfigReloadTask::State::FAIL);
+
+ // Try to transition to SUCCESS — rejected
+ task->set_completed();
+ REQUIRE(task->get_state() == ConfigReloadTask::State::FAIL);
+
+ // Try to transition to IN_PROGRESS — rejected
+ task->set_in_progress();
+ REQUIRE(task->get_state() == ConfigReloadTask::State::FAIL);
+ }
+}
+
+TEST_CASE("State to string conversion", "[config][reload][state]")
+{
+ // Runtime checks
+ REQUIRE(ConfigReloadTask::state_to_string(ConfigReloadTask::State::INVALID) == "invalid");
+ REQUIRE(ConfigReloadTask::state_to_string(ConfigReloadTask::State::CREATED) == "created");
+ REQUIRE(ConfigReloadTask::state_to_string(ConfigReloadTask::State::IN_PROGRESS) == "in_progress");
+ REQUIRE(ConfigReloadTask::state_to_string(ConfigReloadTask::State::SUCCESS) == "success");
+ REQUIRE(ConfigReloadTask::state_to_string(ConfigReloadTask::State::FAIL) == "fail");
+ REQUIRE(ConfigReloadTask::state_to_string(ConfigReloadTask::State::TIMEOUT) == "timeout");
+
+ // Compile-time verification (constexpr)
+ static_assert(ConfigReloadTask::state_to_string(ConfigReloadTask::State::SUCCESS) == "success");
+ static_assert(ConfigReloadTask::state_to_string(ConfigReloadTask::State::FAIL) == "fail");
+}
diff --git a/src/traffic_ctl/CtrlCommands.cc b/src/traffic_ctl/CtrlCommands.cc
index 6bd568492e..659bf4f1e7 100644
--- a/src/traffic_ctl/CtrlCommands.cc
+++ b/src/traffic_ctl/CtrlCommands.cc
@@ -34,6 +34,8 @@
#include "jsonrpc/CtrlRPCRequests.h"
#include "jsonrpc/ctrl_yaml_codecs.h"
+#include "mgmt/config/ConfigReloadErrors.h"
+#include "tsutil/ts_time_parser.h"
#include "TrafficCtlStatus.h"
namespace
{
@@ -60,6 +62,22 @@ yaml_to_record_name(std::string_view path)
}
return std::string{path};
}
+
+void
+display_errors(BasePrinter *printer, std::vector<ConfigReloadResponse::Error> const &errors)
+{
+ std::string text;
+ if (auto iter = std::begin(errors); iter != std::end(errors)) {
+ auto print_error = [&](auto &&e) { printer->write_output(swoc::bwprint(text, "Message: {}, Code: {}", e.message, e.code)); };
+ printer->write_output("------------ Errors ----------");
+ print_error(*iter);
+ ++iter;
+ for (; iter != std::end(errors); ++iter) {
+ printer->write_output("--");
+ print_error(*iter);
+ }
+ }
+}
} // namespace
BasePrinter::Options::FormatFlags
@@ -161,7 +179,7 @@ ConfigCommand::ConfigCommand(ts::Arguments *args) : RecordCommand(args)
_printer = std::make_unique<ConfigSetPrinter>(printOpts);
_invoked_func = [&]() { config_reset(); };
} else if (args->get(STATUS_STR)) {
- _printer = std::make_unique<ConfigStatusPrinter>(printOpts);
+ _printer = std::make_unique<ConfigReloadPrinter>(printOpts);
_invoked_func = [&]() { config_status(); };
} else if (args->get(RELOAD_STR)) {
_printer = std::make_unique<ConfigReloadPrinter>(printOpts);
@@ -238,9 +256,30 @@ ConfigCommand::config_diff()
void
ConfigCommand::config_status()
{
- ConfigStatusRequest request;
- shared::rpc::JSONRPCResponse response = invoke_rpc(request);
- _printer->write_output(response);
+ std::string token = get_parsed_arguments()->get("token").value();
+ std::string count = get_parsed_arguments()->get("count").value();
+
+ if (!count.empty() && !token.empty()) {
+ // can't use both.
+ if (!_printer->is_json_format()) {
+ _printer->write_output("You can't use both --token and --count options together. Ignoring --count");
+ }
+ count = ""; // server will ignore this if token is set anyways.
+ }
+
+ auto resp = fetch_config_reload(token, count);
+
+ if (resp.error.size()) {
+ display_errors(_printer.get(), resp.error);
+ App_Exit_Status_Code = CTRL_EX_ERROR;
+ return;
+ }
+
+ if (resp.tasks.size() > 0) {
+ for (const auto &task : resp.tasks) {
+ _printer->as<ConfigReloadPrinter>()->print_reload_report(task, true);
+ }
+ }
}
void
@@ -255,6 +294,134 @@ ConfigCommand::config_set()
_printer->write_output(response);
}
+ConfigReloadResponse
+ConfigCommand::fetch_config_reload(std::string const &token, std::string const &count)
+{
+ // traffic_ctl config status [--token <token>] [--count <n>]
+
+ FetchConfigReloadStatusRequest request{
+ FetchConfigReloadStatusRequest::Params{token, count}
+ };
+
+ auto response = invoke_rpc(request); // server will handle if token is empty or not.
+
+ _printer->write_output(response); // in case of errors.
+ return response.result.as<ConfigReloadResponse>();
+}
+
+void
+ConfigCommand::track_config_reload_progress(std::string const &token, std::chrono::milliseconds refresh_interval,
+ std::chrono::milliseconds timeout, std::string const &timeout_str)
+{
+ FetchConfigReloadStatusRequest request{
+ FetchConfigReloadStatusRequest::Params{token, "1" /* last reload if any*/}
+ };
+ auto resp = invoke_rpc(request);
+
+ if (resp.is_error()) {
+ _printer->write_output(resp);
+ return;
+ }
+
+ auto start_time = std::chrono::steady_clock::now();
+
+ while (!Signal_Flagged.load()) {
+ auto decoded_response = resp.result.as<ConfigReloadResponse>();
+
+ _printer->write_output(resp);
+ if (decoded_response.tasks.empty()) {
+ _printer->write_output(resp);
+ App_Exit_Status_Code = CTRL_EX_ERROR;
+ return;
+ }
+
+ ConfigReloadResponse::ReloadInfo current_task = decoded_response.tasks[0];
+ _printer->as<ConfigReloadPrinter>()->write_progress_line(current_task);
+
+ // Check if reload has reached a terminal state
+ if (current_task.status == "success" || current_task.status == "fail" || current_task.status == "timeout") {
+ std::cout << "\n";
+ if (current_task.status != "success") {
+ App_Exit_Status_Code = CTRL_EX_ERROR;
+ std::string hint;
+ _printer->write_output(swoc::bwprint(hint, "\n Details : traffic_ctl config status -t {}", current_task.config_token));
+ }
+ return;
+ }
+
+ // Check timeout (0 means no timeout)
+ if (timeout.count() > 0) {
+ auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - start_time);
+ if (elapsed >= timeout) {
+ std::cout << "\n";
+ std::string text;
+ _printer->write_output(swoc::bwprint(text, "Monitor timed out after {} waiting for reload completion.", timeout_str));
+ _printer->write_output(swoc::bwprint(text, " Details : traffic_ctl config status -t {}", token));
+ App_Exit_Status_Code = CTRL_EX_TEMPFAIL;
+ return;
+ }
+ }
+
+ std::this_thread::sleep_for(refresh_interval);
+
+ request = FetchConfigReloadStatusRequest{
+ FetchConfigReloadStatusRequest::Params{token, "1" /* last reload if any*/}
+ };
+ resp = invoke_rpc(request);
+ if (resp.is_error()) {
+ _printer->write_output(resp);
+ App_Exit_Status_Code = CTRL_EX_ERROR;
+ return;
+ }
+ }
+
+ // Signal received (e.g. Ctrl+C) — assume reload still in progress.
+ if (Signal_Flagged.load()) {
+ App_Exit_Status_Code = CTRL_EX_TEMPFAIL;
+ }
+}
+
+std::string
+ConfigCommand::read_data_input(std::string const &data_arg)
+{
+ if (data_arg.empty()) {
+ return {};
+ }
+
+ // @- means stdin
+ if (data_arg == "@-") {
+ std::istreambuf_iterator<char> begin(std::cin), end;
+ return std::string(begin, end);
+ }
+
+ // @filename means read from file
+ if (data_arg[0] == '@') {
+ std::string filename = data_arg.substr(1);
+ std::ifstream file(filename);
+ if (!file) {
+ _printer->write_output("Error: Cannot open file '" + filename + "'");
+ App_Exit_Status_Code = CTRL_EX_ERROR;
+ return {};
+ }
+ std::istreambuf_iterator<char> begin(file), end;
+ return std::string(begin, end);
+ }
+
+ // Otherwise, treat as inline YAML string
+ return data_arg;
+}
+
+ConfigReloadResponse
+ConfigCommand::config_reload(std::string const &token, bool force, YAML::Node const &configs)
+{
+ auto resp = invoke_rpc(ConfigReloadRequest{
+ ConfigReloadRequest::Params{token, force, configs}
+ });
+ // base class method will handle error and json output if needed.
+ _printer->write_output(resp);
+ return resp.result.as<ConfigReloadResponse>();
+}
+
void
ConfigCommand::config_reset()
{
@@ -301,8 +468,195 @@ ConfigCommand::config_reset()
void
ConfigCommand::config_reload()
{
- _printer->write_output(invoke_rpc(ConfigReloadRequest{}));
+ std::string token = get_parsed_arguments()->get("token").value();
+ bool force = get_parsed_arguments()->get("force") ? true : false;
+ auto data_args = get_parsed_arguments()->get("data");
+
+ bool show_details = get_parsed_arguments()->get("show-details") ? true : false;
+ bool monitor = get_parsed_arguments()->get("monitor") ? true : false;
+
+ float refresh_secs = std::stof(get_parsed_arguments()->get("refresh-int").value());
+ float initial_wait_secs = std::stof(get_parsed_arguments()->get("initial-wait").value());
+ // Parse timeout using ts::time_parser (supports: 30s, 1m, 500ms, etc.)
+ std::chrono::milliseconds timeout_ms{0};
+ std::string timeout_str = get_parsed_arguments()->get("timeout").value();
+ if (timeout_str != "0") {
+ auto &&[ns, errata] = ts::time_parser(swoc::TextView{timeout_str});
+ if (!errata.is_ok()) {
+ _printer->write_output("Error: Invalid timeout value '" + timeout_str + "'. Use duration format: 30s, 1m, 500ms, etc.");
+ App_Exit_Status_Code = CTRL_EX_ERROR;
+ return;
+ }
+ timeout_ms = std::chrono::duration_cast<std::chrono::milliseconds>(ns);
+ }
+
+ if (monitor && show_details) {
+ // ignore monitor if details is set.
+ monitor = false;
+ }
+
+ // Warn about --force behavior
+ if (force) {
+ _printer->write_output("Warning: --force does not stop running handlers.");
+ _printer->write_output(" If a reload is actively processing, handlers may run in parallel.");
+ _printer->write_output("");
+ }
+
+ // Parse inline config data if provided (supports multiple -d arguments)
+ YAML::Node configs;
+ for (auto const &data_arg : data_args) {
+ if (data_arg.empty()) {
+ continue;
+ }
+
+ std::string data_content = read_data_input(data_arg);
+ if (data_content.empty() && App_Exit_Status_Code == CTRL_EX_ERROR) {
+ return; // Error already reported by read_data_input
+ }
+
+ try {
+ YAML::Node parsed = YAML::Load(data_content);
+ if (!parsed.IsMap()) {
+ _printer->write_output("Error: Data must be a YAML map with config keys (e.g., ip_allow, sni)");
+ App_Exit_Status_Code = CTRL_EX_ERROR;
+ return;
+ }
+ // Merge parsed content into configs (later files override earlier ones)
+ for (auto const &kv : parsed) {
+ configs[kv.first.as<std::string>()] = kv.second;
+ }
+ } catch (YAML::Exception const &ex) {
+ _printer->write_output(std::string("Error: Invalid YAML data in '") + data_arg + "': " + ex.what());
+ App_Exit_Status_Code = CTRL_EX_ERROR;
+ return;
+ }
+ }
+
+ using ConfigError = config::reload::errors::ConfigReloadError;
+
+ auto contains_error = [](std::vector<ConfigReloadResponse::Error> const &errors, ConfigError error) -> bool {
+ const int code = static_cast<int>(error);
+ for (auto const &n : errors) {
+ if (n.code == code) {
+ return true;
+ }
+ }
+ return false;
+ };
+
+ std::string text;
+ bool token_exist{false};
+ bool in_progress{false};
+
+ if (show_details) {
+ bool include_logs = get_parsed_arguments()->get("include-logs") ? true : false;
+
+ ConfigReloadResponse resp = config_reload(token, force, configs);
+ if (contains_error(resp.error, ConfigError::RELOAD_IN_PROGRESS)) {
+ App_Exit_Status_Code = CTRL_EX_TEMPFAIL;
+ if (resp.tasks.size() > 0) {
+ const auto &task = resp.tasks[0];
+ _printer->write_output(swoc::bwprint(text, "\xe2\x9f\xb3 Reload in progress [{}]", task.config_token));
+ _printer->as<ConfigReloadPrinter>()->print_reload_report(task, include_logs);
+ }
+ return;
+ } else if (contains_error(resp.error, ConfigError::TOKEN_ALREADY_EXISTS)) {
+ App_Exit_Status_Code = CTRL_EX_ERROR;
+ token_exist = true;
+ } else if (resp.error.size()) {
+ display_errors(_printer.get(), resp.error);
+ App_Exit_Status_Code = CTRL_EX_ERROR;
+ return;
+ }
+
+ if (token_exist) {
+ _printer->write_output(swoc::bwprint(text, "\xe2\x9c\x97 Token '{}' already in use", token));
+ } else {
+ _printer->write_output(swoc::bwprint(text, "\xe2\x9c\x94 Reload scheduled [{}]. Waiting for details...", resp.config_token));
+ std::this_thread::sleep_for(std::chrono::milliseconds(static_cast<int>(initial_wait_secs * 1000)));
+ }
+
+ resp = fetch_config_reload(token);
+ if (resp.error.size()) {
+ display_errors(_printer.get(), resp.error);
+ App_Exit_Status_Code = CTRL_EX_ERROR;
+ return;
+ }
+
+ if (resp.tasks.size() > 0) {
+ const auto &task = resp.tasks[0];
+ // _printer->as<ConfigReloadPrinter>()->print_basic_ri_line(task, true, true, 0);
+ _printer->as<ConfigReloadPrinter>()->print_reload_report(task, include_logs);
+ }
+ } else if (monitor) {
+ _printer->disable_json_format(); // monitor output is not json.
+ ConfigReloadResponse resp = config_reload(token, force, configs);
+
+ if (contains_error(resp.error, ConfigError::RELOAD_IN_PROGRESS)) {
+ in_progress = true;
+ if (!resp.tasks.empty()) {
+ _printer->write_output(swoc::bwprint(text, "\xe2\x9f\xb3 Reload in progress [{}]", resp.tasks[0].config_token));
+ }
+ } else if (contains_error(resp.error, ConfigError::TOKEN_ALREADY_EXISTS)) {
+ App_Exit_Status_Code = CTRL_EX_ERROR;
+ _printer->write_output(swoc::bwprint(text, "\xe2\x9c\x97 Token '{}' already in use\n", token));
+ _printer->write_output(swoc::bwprint(text, " Status : traffic_ctl config status -t {}", token));
+ _printer->write_output(" Retry : traffic_ctl config reload");
+ return;
+ } else if (resp.error.size()) {
+ display_errors(_printer.get(), resp.error);
+ App_Exit_Status_Code = CTRL_EX_ERROR;
+ return;
+ } else {
+ _printer->write_output(swoc::bwprint(text, "\xe2\x9c\x94 Reload scheduled [{}]", resp.config_token));
+ }
+
+ if (!in_progress) {
+ std::this_thread::sleep_for(std::chrono::milliseconds(static_cast<int>(initial_wait_secs * 1000))); // wait before first poll
+ } // else no need to wait, we can start fetching right away.
+
+ track_config_reload_progress(resp.config_token, std::chrono::milliseconds(static_cast<int>(refresh_secs * 1000)), timeout_ms,
+ timeout_str);
+ } else {
+ ConfigReloadResponse resp = config_reload(token, force, configs);
+ if (contains_error(resp.error, ConfigError::RELOAD_IN_PROGRESS)) {
+ App_Exit_Status_Code = CTRL_EX_TEMPFAIL;
+ if (!resp.tasks.empty()) {
+ std::string tk = resp.tasks[0].config_token;
+ _printer->write_output(swoc::bwprint(text, "\xe2\x9f\xb3 Reload in progress [{}]\n", tk));
+ _printer->write_output(swoc::bwprint(text, " Monitor : traffic_ctl config reload -t {} -m", tk));
+ _printer->write_output(swoc::bwprint(text, " Details : traffic_ctl config status -t {}", tk));
+ _printer->write_output(" Force : traffic_ctl config reload --force (may conflict with the running reload)");
+ }
+ } else if (contains_error(resp.error, ConfigError::TOKEN_ALREADY_EXISTS)) {
+ App_Exit_Status_Code = CTRL_EX_ERROR;
+ _printer->write_output(swoc::bwprint(text, "\xe2\x9c\x97 Token '{}' already in use\n", token));
+ _printer->write_output(swoc::bwprint(text, " Status : traffic_ctl config status -t {}", token));
+ _printer->write_output(" Retry : traffic_ctl config reload");
+ } else if (resp.error.size()) {
+ display_errors(_printer.get(), resp.error);
+ App_Exit_Status_Code = CTRL_EX_ERROR;
+ return;
+ } else {
+ _printer->write_output(swoc::bwprint(text, "\xe2\x9c\x94 Reload scheduled [{}]\n", resp.config_token));
+ _printer->write_output(swoc::bwprint(text, " Monitor : traffic_ctl config reload -t {} -m", resp.config_token));
+ _printer->write_output(swoc::bwprint(text, " Details : traffic_ctl config reload -t {} -s -l", resp.config_token));
+ }
+
+ if (resp.tasks.size() > 0) {
+ const auto &task = resp.tasks[0];
+ _printer->as<ConfigReloadPrinter>()->print_reload_report(task);
+ }
+ }
+
+ // Show warning for inline config (not persisted to disk)
+ if (configs.size() > 0 && App_Exit_Status_Code != CTRL_EX_ERROR) {
+ _printer->write_output("");
+ _printer->write_output("Note: Inline configuration is NOT persisted to disk.");
+ _printer->write_output(" Server restart will revert to file-based configuration.");
+ }
}
+
void
ConfigCommand::config_show_file_registry()
{
@@ -390,7 +744,7 @@ MetricCommand::metric_monitor()
};
std::unordered_map<std::string, ctx> summary;
-
+ _printer->disable_json_format(); // monitor is not json.
while (!Signal_Flagged.load()) {
// Request will hold all metrics in a single message.
shared::rpc::JSONRPCResponse const &resp = record_fetch(arg, shared::rpc::NOT_REGEX, RecordQueryType::METRIC);
@@ -585,6 +939,7 @@ DirectRPCCommand::from_file_request()
{
// TODO: remove all the output messages from here if possible
auto filenames = get_parsed_arguments()->get(FILE_STR);
+
for (auto &&filename : filenames) {
std::string text;
// run some basic validation on the passed files, they should
@@ -600,7 +955,7 @@ DirectRPCCommand::from_file_request()
std::string const &response = invoke_rpc(content);
if (_printer->is_json_format()) {
// as we have the raw json in here, we cna just directly print it
- _printer->write_output(response);
+ _printer->write_debug(response);
} else {
_printer->write_output(swoc::bwprint(text, "\n[ {} ]\n --> \n{}\n", filename, content));
_printer->write_output(swoc::bwprint(text, "<--\n{}\n", response));
diff --git a/src/traffic_ctl/CtrlCommands.h b/src/traffic_ctl/CtrlCommands.h
index 8d5fc2b931..82036f10c5 100644
--- a/src/traffic_ctl/CtrlCommands.h
+++ b/src/traffic_ctl/CtrlCommands.h
@@ -147,6 +147,15 @@ class ConfigCommand : public RecordCommand
void config_reload();
void config_show_file_registry();
+ // Helper functions for config reload
+ ConfigReloadResponse fetch_config_reload(std::string const &token, std::string const &count = "1");
+ void track_config_reload_progress(std::string const &token, std::chrono::milliseconds refresh_interval,
+ std::chrono::milliseconds timeout, std::string const &timeout_str);
+ ConfigReloadResponse config_reload(std::string const &token, bool force, YAML::Node const &configs);
+
+ // Helper to read data from file, stdin, or inline string
+ std::string read_data_input(std::string const &data_arg);
+
public:
ConfigCommand(ts::Arguments *args);
};
diff --git a/src/traffic_ctl/CtrlPrinters.cc b/src/traffic_ctl/CtrlPrinters.cc
index 55e51de20e..8e82fe77a9 100644
--- a/src/traffic_ctl/CtrlPrinters.cc
+++ b/src/traffic_ctl/CtrlPrinters.cc
@@ -85,6 +85,11 @@ BasePrinter::write_output(shared::rpc::JSONRPCResponse const &response)
void
BasePrinter::write_output(std::string_view output) const
{
+ if (is_json_format()) {
+ // if json format, no other output is expected to avoid mixing formats.
+ // Specially if you consume the json output with a tool.
+ return;
+ }
std::cout << output << '\n';
}
@@ -99,7 +104,7 @@ BasePrinter::write_output_json(YAML::Node const &node) const
YAML::Emitter out;
out << YAML::DoubleQuoted << YAML::Flow;
out << node;
- write_output(std::string_view{out.c_str()});
+ std::cout << out.c_str() << '\n';
}
//------------------------------------------------------------------------------------------------------------------------------------
void
@@ -174,7 +179,285 @@ DiffConfigPrinter::write_output(YAML::Node const &result)
void
ConfigReloadPrinter::write_output([[maybe_unused]] YAML::Node const &result)
{
+ // no op, ctrl command will handle the output directly.
+ // BasePrinter will handle the error and the json output if needed.
+}
+namespace
+{
+void
+group_files(const ConfigReloadResponse::ReloadInfo &info, std::vector<const ConfigReloadResponse::ReloadInfo *> &files)
+{
+ if (!info.meta.is_main_task) {
+ files.push_back(&info);
+ }
+ for (const auto &sub : info.sub_tasks) {
+ group_files(sub, files);
+ }
+}
+
+// Calculate duration in milliseconds from ms-since-epoch timestamps
+inline int
+duration_ms(int64_t start_ms, int64_t end_ms)
+{
+ return (end_ms >= start_ms) ? static_cast<int>(end_ms - start_ms) : -1;
+}
+
+// Format millisecond timestamp as human-readable date with milliseconds
+// Output format: "YYYY Mon DD HH:MM:SS.mmm"
+std::string
+format_time_ms(int64_t ms_timestamp)
+{
+ if (ms_timestamp <= 0) {
+ return "-";
+ }
+ std::time_t seconds = ms_timestamp / 1000;
+ int millis = ms_timestamp % 1000;
+
+ std::string buf;
+ swoc::bwprint(buf, "{}.{:03d}", swoc::bwf::Date(seconds), millis);
+ return buf;
+}
+
+// Build a UTF-8 progress bar. @a width = number of visual characters.
+std::string
+build_progress_bar(int done, int total, int width = 20)
+{
+ int filled = total > 0 ? (done * width / total) : 0;
+ std::string bar;
+ bar.reserve(width * 3);
+ for (int i = 0; i < width; ++i) {
+ bar += (i < filled) ? "\xe2\x96\x88" : "\xe2\x96\x91"; // █ or ░
+ }
+ return bar;
+}
+
+// Human-readable duration string from milliseconds.
+std::string
+format_duration(int ms)
+{
+ if (ms < 0) {
+ return "-";
+ }
+ if (ms < 1000) {
+ return std::to_string(ms) + "ms";
+ }
+ if (ms < 60000) {
+ return std::to_string(ms / 1000) + "." + std::to_string((ms % 1000) / 100) + "s";
+ }
+ return std::to_string(ms / 60000) + "m " + std::to_string((ms % 60000) / 1000) + "s";
+}
+
+// Map task status string to a single-character icon for compact display.
+const char *
+status_icon(const std::string &status)
+{
+ if (status == "success") {
+ return "\xe2\x9c\x94"; // ✔
+ }
+ if (status == "fail") {
+ return "\xe2\x9c\x97"; // ✗
+ }
+ if (status == "in_progress" || status == "created") {
+ return "\xe2\x97\x8c"; // ◌
+ }
+ if (status == "timeout") {
+ return "\xe2\x9f\xb3"; // ⟳
+ }
+ return "?";
+}
+
+// Approximate visual width of a UTF-8 string (each code point counts as 1 column).
+int
+visual_width(const std::string &s)
+{
+ int w = 0;
+ for (size_t i = 0; i < s.size();) {
+ auto c = static_cast<unsigned char>(s[i]);
+ if (c < 0x80) {
+ ++i;
+ } else if (c < 0xE0) {
+ i += 2;
+ } else if (c < 0xF0) {
+ i += 3;
+ } else {
+ i += 4;
+ }
+ ++w;
+ }
+ return w;
+}
+
+// Build a dot-leader string: " ···· " of the given visual width (min 2).
+std::string
+dot_fill(int width)
+{
+ if (width < 2) {
+ width = 2;
+ }
+ std::string out(" ");
+ for (int i = 1; i < width - 1; ++i) {
+ out += "\xc2\xb7"; // · (middle dot U+00B7)
+ }
+ out += ' ';
+ return out;
+}
+
+// Recursively print a task and its children using tree-drawing characters.
+// @param prefix characters printed before this task's icon (tree connectors from parent)
+// @param child_prefix base prefix for this task's log lines and its children's connectors
+// @param content_width visual columns available for icon+name+dots+duration (shrinks per nesting)
+void
+print_task_tree(const ConfigReloadResponse::ReloadInfo &f, bool full_report, const std::string &prefix,
+ const std::string &child_prefix, int content_width = 55)
+{
+ std::string fname;
+ if (f.filename.empty() || f.filename == "<none>") {
+ fname = f.description;
+ } else {
+ fname = f.filename;
+ }
+
+ int dur_ms = duration_ms(f.meta.created_time_ms, f.meta.last_updated_time_ms);
+
+ // Build label and right-aligned duration
+ std::string label = std::string(status_icon(f.status)) + " " + fname;
+ std::string dur_str = format_duration(dur_ms);
+
+ // Right-pad duration to fixed width so values align
+ constexpr int DUR_COL = 6;
+ while (static_cast<int>(dur_str.size()) < DUR_COL) {
+ dur_str = " " + dur_str;
+ }
+
+ // Dot fill between label and duration
+ int label_vw = visual_width(label);
+ int gap = content_width - label_vw - DUR_COL;
+
+ std::cout << prefix << label << dot_fill(gap) << dur_str;
+
+ // Annotate non-success terminal states so failures stand out
+ if (f.status == "fail") {
+ std::cout << " \xe2\x9c\x97 FAIL";
+ } else if (f.status == "timeout") {
+ std::cout << " \xe2\x9f\xb3 TIMEOUT";
+ }
+ std::cout << "\n";
+
+ bool has_children = !f.sub_tasks.empty();
+
+ // Log lines: indented under the task, with tree continuation line if children follow.
+ if (full_report && !f.logs.empty()) {
+ std::string log_pfx = has_children ? (child_prefix + "\xe2\x94\x82 ") : (child_prefix + " ");
+ for (const auto &log : f.logs) {
+ std::cout << log_pfx << log << '\n';
+ }
+ }
+
+ // Children: draw tree connectors. Each nesting level eats 3 visual columns.
+ for (size_t i = 0; i < f.sub_tasks.size(); ++i) {
+ bool is_last = (i == f.sub_tasks.size() - 1);
+ std::string sub_prefix = child_prefix + (is_last ? "\xe2\x94\x94\xe2\x94\x80 " : "\xe2\x94\x9c\xe2\x94\x80 ");
+ std::string sub_child_prefix = child_prefix + (is_last ? " " : "\xe2\x94\x82 ");
+ print_task_tree(f.sub_tasks[i], full_report, sub_prefix, sub_child_prefix, content_width - 3);
+ }
+}
+
+} // namespace
+void
+ConfigReloadPrinter::write_progress_line(const ConfigReloadResponse::ReloadInfo &info)
+{
+ if (this->is_json_format()) {
+ return;
+ }
+
+ int done{0}, total{0};
+
+ auto count_tasks = [&](auto &&self, const ConfigReloadResponse::ReloadInfo &ri) -> void {
+ if (ri.sub_tasks.empty()) {
+ if (ri.status == "success" || ri.status == "fail") {
+ done++;
+ }
+ total++;
+ }
+ for (const auto &sub : ri.sub_tasks) {
+ self(self, sub);
+ }
+ };
+ count_tasks(count_tasks, info);
+
+ bool terminal = (info.status == "success" || info.status == "fail" || info.status == "timeout");
+
+ int dur_ms = duration_ms(info.meta.created_time_ms, info.meta.last_updated_time_ms);
+
+ std::string bar = build_progress_bar(done, total);
+
+ // \r + ANSI clear-to-EOL overwrites the previous line in place.
+ std::cout << "\r\033[K" << status_icon(info.status) << " [" << info.config_token << "] " << bar << " " << done << "/" << total
+ << " " << info.status;
+ if (terminal) {
+ std::cout << " (" << format_duration(dur_ms) << ")";
+ }
+ std::cout << std::flush;
+}
+
+void
+ConfigReloadPrinter::print_reload_report(const ConfigReloadResponse::ReloadInfo &info, bool full_report)
+{
+ if (this->is_json_format()) {
+ return;
+ }
+
+ int overall_duration = duration_ms(info.meta.created_time_ms, info.meta.last_updated_time_ms);
+
+ int total{0}, completed{0}, failed{0}, created{0}, in_progress{0};
+
+ auto calculate_summary = [&](auto &&self, const ConfigReloadResponse::ReloadInfo &ri) -> void {
+ if (ri.sub_tasks.empty()) {
+ if (ri.status == "success") {
+ completed++;
+ } else if (ri.status == "fail") {
+ failed++;
+ } else if (ri.status == "created") {
+ created++;
+ } else if (ri.status == "in_progress") {
+ in_progress++;
+ }
+ total++;
+ }
+ if (!ri.sub_tasks.empty()) {
+ for (const auto &sub : ri.sub_tasks) {
+ self(self, sub);
+ }
+ }
+ };
+
+ std::vector<const ConfigReloadResponse::ReloadInfo *> files;
+ group_files(info, files);
+ calculate_summary(calculate_summary, info);
+
+ std::string start_time_str = format_time_ms(info.meta.created_time_ms);
+ std::string end_time_str = format_time_ms(info.meta.last_updated_time_ms);
+
+ // ── Header ──
+ std::cout << status_icon(info.status) << " Reload [" << info.status << "] \xe2\x80\x94 " << info.config_token << "\n";
+ std::cout << " Started : " << start_time_str << '\n';
+ std::cout << " Finished: " << end_time_str << '\n';
+ std::cout << " Duration: " << format_duration(overall_duration) << "\n\n";
+
+ // ── Summary ──
+ std::cout << " \xe2\x9c\x94 " << completed << " success \xe2\x97\x8c " << in_progress << " in-progress \xe2\x9c\x97 " << failed
+ << " failed (" << total << " total)\n";
+
+ // ── Task tree ──
+ if (!files.empty()) {
+ std::cout << "\n Tasks:\n";
+ }
+ const std::string base_prefix(" ");
+ for (const auto &sub : info.sub_tasks) {
+ print_task_tree(sub, full_report, base_prefix, base_prefix);
+ }
}
+
//------------------------------------------------------------------------------------------------------------------------------------
void
ConfigShowFileRegistryPrinter::write_output(YAML::Node const &result)
diff --git a/src/traffic_ctl/CtrlPrinters.h b/src/traffic_ctl/CtrlPrinters.h
index 0c724942d8..050cb705e3 100644
--- a/src/traffic_ctl/CtrlPrinters.h
+++ b/src/traffic_ctl/CtrlPrinters.h
@@ -24,6 +24,8 @@
#include <string_view>
#include <yaml-cpp/yaml.h>
+#include "jsonrpc/CtrlRPCRequests.h"
+#include "jsonrpc/ctrl_yaml_codecs.h"
#include "shared/rpc/RPCRequests.h"
#include <swoc/BufferWriter.h>
@@ -112,8 +114,16 @@ public:
Options::FormatFlags get_format() const;
bool print_rpc_message() const;
bool is_json_format() const;
- bool is_records_format() const;
- bool should_include_default() const;
+ void disable_json_format();
+
+ bool is_records_format() const;
+ bool should_include_default() const;
+
+ /// In case a derived class needs to call derived class functions. Ugly but works.
+ /// Note: CRTP may worth a try.
+ template <typename Derived> // TODO, move it down the file.
+ const Derived *as() const;
+ template <typename Derived> Derived *as();
protected:
void write_output_json(YAML::Node const &node) const;
@@ -156,6 +166,12 @@ BasePrinter::is_json_format() const
return _printOpt._format & Options::FormatFlags::JSON;
}
+inline void
+BasePrinter::disable_json_format()
+{
+ _printOpt._format = static_cast<Options::FormatFlags>(_printOpt._format & ~Options::FormatFlags::JSON);
+}
+
inline bool
BasePrinter::is_records_format() const
{
@@ -211,6 +227,9 @@ class ConfigReloadPrinter : public BasePrinter
public:
ConfigReloadPrinter(BasePrinter::Options opt) : BasePrinter(opt) {}
+
+ void print_reload_report(const ConfigReloadResponse::ReloadInfo &info, bool full_report = false);
+ void write_progress_line(const ConfigReloadResponse::ReloadInfo &info);
};
//------------------------------------------------------------------------------------------------------------------------------------
class ConfigShowFileRegistryPrinter : public BasePrinter
@@ -293,7 +312,6 @@ public:
RPCAPIPrinter(BasePrinter::Options opt) : BasePrinter(opt) {}
};
//------------------------------------------------------------------------------------------------------------------------------------
-//------------------------------------------------------------------------------------------------------------------------------------
class ServerStatusPrinter : public BasePrinter
{
void write_output(YAML::Node const &result) override;
@@ -302,3 +320,26 @@ public:
ServerStatusPrinter(BasePrinter::Options opt) : BasePrinter(opt) {}
};
//------------------------------------------------------------------------------------------------------------------------------------
+
+/// In case a derived class needs to call derived class functions. Ugly but works.
+/// Note: CRTP may worth a try.
+template <typename Derived> // TODO, move it down the file.
+const Derived *
+BasePrinter::as() const
+{
+ auto r = dynamic_cast<const Derived *>(this);
+ if (!r) {
+ throw std::runtime_error("Internal error: Couldn't get Derived instance");
+ }
+ return r;
+}
+template <typename Derived>
+Derived *
+BasePrinter::as()
+{
+ auto r = dynamic_cast<Derived *>(this);
+ if (!r) {
+ throw std::runtime_error("Internal error: Couldn't get Derived instance");
+ }
+ return r;
+}
diff --git a/src/traffic_ctl/TrafficCtlStatus.h b/src/traffic_ctl/TrafficCtlStatus.h
index b7d758fd25..61e84a8054 100644
--- a/src/traffic_ctl/TrafficCtlStatus.h
+++ b/src/traffic_ctl/TrafficCtlStatus.h
@@ -24,5 +24,6 @@ constexpr int CTRL_EX_OK = 0;
// EXIT_FAILURE can also be used.
constexpr int CTRL_EX_ERROR = 2;
constexpr int CTRL_EX_UNIMPLEMENTED = 3;
+constexpr int CTRL_EX_TEMPFAIL = 75; ///< Temporary failure — operation in progress, retry later (EX_TEMPFAIL from sysexits.h).
extern int App_Exit_Status_Code; //!< Global variable to store the exit status code of the application.
diff --git a/src/traffic_ctl/jsonrpc/CtrlRPCRequests.h b/src/traffic_ctl/jsonrpc/CtrlRPCRequests.h
index 7e11670856..5644f288a1 100644
--- a/src/traffic_ctl/jsonrpc/CtrlRPCRequests.h
+++ b/src/traffic_ctl/jsonrpc/CtrlRPCRequests.h
@@ -24,6 +24,8 @@
// We base on the common client types.
#include "shared/rpc/RPCRequests.h"
+#include <yaml-cpp/yaml.h>
+
/// This file defines all the traffic_ctl API client request and responses objects needed to model the jsonrpc messages used in the
/// TS JSONRPC Node API.
@@ -39,15 +41,67 @@ struct GetAllRecordsRequest : shared::rpc::RecordLookupRequest {
};
//------------------------------------------------------------------------------------------------------------------------------------
///
-/// @brief Models the config reload request. No params are needed.
+/// @brief Models the config reload request. Supports both file-based and rpc-supplied modes.
+/// rpc-supplied mode is triggered when configs is present.
///
struct ConfigReloadRequest : shared::rpc::ClientRequest {
+ struct Params {
+ std::string token;
+ bool force{false};
+ YAML::Node configs; // Optional: if present, triggers inline mode
+ };
+ ConfigReloadRequest(Params p) { super::params = std::move(p); }
std::string
get_method() const override
{
return "admin_config_reload";
}
};
+
+// Full list of reload tasks, could be nested.
+struct ConfigReloadResponse {
+ // Existing reload task info, could be nested.
+ struct ReloadInfo {
+ std::string config_token;
+ std::string status;
+ std::string description;
+ std::string filename;
+ std::vector<std::string> logs;
+ std::vector<ReloadInfo> sub_tasks;
+ struct Meta { // internal info.
+ int64_t created_time_ms{0};
+ int64_t last_updated_time_ms{0};
+ bool is_main_task{false};
+ } meta;
+ };
+
+ struct Error {
+ int code;
+ std::string message;
+ };
+ std::vector<Error> error; ///< Error list, if any.
+
+ // when requesting existing tasks.
+ std::vector<ReloadInfo> tasks;
+
+ std::string created_time;
+ std::vector<std::string> messages;
+ std::string config_token;
+};
+
+struct FetchConfigReloadStatusRequest : shared::rpc::ClientRequest {
+ struct Params {
+ std::string token;
+ std::string count{"1"}; // number of latest reloads to return, 0 means all.
+ };
+ FetchConfigReloadStatusRequest(Params p) { super::params = std::move(p); }
+ std::string
+ get_method() const override
+ {
+ return "get_reload_config_status";
+ }
+};
+
//------------------------------------------------------------------------------------------------------------------------------------
///
/// @brief To fetch config file registry from the RPC node.
diff --git a/src/traffic_ctl/jsonrpc/ctrl_yaml_codecs.h b/src/traffic_ctl/jsonrpc/ctrl_yaml_codecs.h
index 1bf7ebac52..d128915e7d 100644
--- a/src/traffic_ctl/jsonrpc/ctrl_yaml_codecs.h
+++ b/src/traffic_ctl/jsonrpc/ctrl_yaml_codecs.h
@@ -41,6 +41,107 @@ template <> struct convert<ConfigSetRecordRequest::Params> {
return node;
}
};
+//------------------------------------------------------------------------------------------------------------------------------------
+
+template <> struct convert<ConfigReloadRequest::Params> {
+ static Node
+ encode(ConfigReloadRequest::Params const ¶ms)
+ {
+ Node node;
+ if (!params.token.empty()) {
+ node["token"] = params.token;
+ }
+
+ if (params.force) {
+ node["force"] = params.force;
+ }
+
+ // Include configs if present (triggers inline mode on server)
+ if (params.configs && params.configs.IsMap() && params.configs.size() > 0) {
+ node["configs"] = params.configs;
+ }
+
+ return node;
+ }
+};
+
+template <> struct convert<FetchConfigReloadStatusRequest::Params> {
+ static Node
+ encode(FetchConfigReloadStatusRequest::Params const ¶ms)
+ {
+ Node node;
+ auto is_number = [](const std::string &s) {
+ return !s.empty() && std::find_if(s.begin(), s.end(), [](unsigned char c) { return !std::isdigit(c); }) == s.end();
+ };
+ // either passed values or defaults.
+ node["token"] = params.token;
+
+ if (!params.count.empty() && (!is_number(params.count) && params.count != "all")) {
+ throw std::invalid_argument("Invalid 'count' value, must be numeric or 'all'");
+ }
+
+ if (!params.count.empty()) {
+ if (params.count == "all") {
+ node["count"] = 0; // 0 means all.
+ } else {
+ node["count"] = std::stoi(params.count);
+ }
+ }
+
+ return node;
+ }
+};
+
+template <> struct convert<ConfigReloadResponse> {
+ static bool
+ decode(Node const &node, ConfigReloadResponse &out)
+ {
+ auto get_info = [](auto &&self, YAML::Node const &from) -> ConfigReloadResponse::ReloadInfo {
+ ConfigReloadResponse::ReloadInfo info;
+ info.config_token = helper::try_extract<std::string>(from, "config_token");
+ info.status = helper::try_extract<std::string>(from, "status");
+ info.description = helper::try_extract<std::string>(from, "description", false, std::string{"<none>"});
+ info.filename = helper::try_extract<std::string>(from, "filename", false, std::string{"<none>"});
+ for (auto &&log : from["logs"]) {
+ info.logs.push_back(log.as<std::string>());
+ }
+
+ for (auto &&sub : from["sub_tasks"]) {
+ info.sub_tasks.push_back(self(self, sub));
+ }
+
+ if (auto meta = from["meta"]) {
+ info.meta.created_time_ms = helper::try_extract<int64_t>(meta, "created_time_ms");
+ info.meta.last_updated_time_ms = helper::try_extract<int64_t>(meta, "last_updated_time_ms");
+ info.meta.is_main_task = helper::try_extract<bool>(meta, "main_task");
+ }
+ return info;
+ };
+
+ // Server sends "errors" (plural)
+ if (node["errors"]) {
+ for (auto &&err : node["errors"]) {
+ ConfigReloadResponse::Error e;
+ e.code = helper::try_extract<int>(err, "code");
+ e.message = helper::try_extract<std::string>(err, "message");
+ out.error.push_back(std::move(e));
+ }
+ }
+ out.created_time = helper::try_extract<std::string>(node, "created_time");
+ for (auto &&msg : node["message"]) {
+ out.messages.push_back(msg.as<std::string>());
+ }
+ out.config_token = helper::try_extract<std::string>(node, "token");
+
+ for (auto &&element : node["tasks"]) {
+ ConfigReloadResponse::ReloadInfo task = get_info(get_info, element);
+ out.tasks.push_back(std::move(task));
+ }
+
+ return true;
+ }
+};
+
//------------------------------------------------------------------------------------------------------------------------------------
template <> struct convert<HostSetStatusRequest::Params::Op> {
static Node
diff --git a/src/traffic_ctl/traffic_ctl.cc b/src/traffic_ctl/traffic_ctl.cc
index 9ac5900925..b2842beb4c 100644
--- a/src/traffic_ctl/traffic_ctl.cc
+++ b/src/traffic_ctl/traffic_ctl.cc
@@ -90,7 +90,8 @@ main([[maybe_unused]] int argc, const char **argv)
.add_option("--run-root", "", "using TS_RUNROOT as sandbox", "TS_RUNROOT", 1)
.add_option("--format", "-f", "Use a specific output format {json|rpc}", "", 1, "", "format")
.add_option("--read-timeout-ms", "", "Read timeout for RPC (in milliseconds)", "", 1, "10000", "read-timeout")
- .add_option("--read-attempts", "", "Read attempts for RPC", "", 1, "100", "read-attempts");
+ .add_option("--read-attempts", "", "Read attempts for RPC", "", 1, "100", "read-attempts")
+ .add_option("--watch", "-w", "Execute a program periodically. Watch interval(in seconds) can be passed.", "", 1, "-1", "watch");
auto &config_command = parser.add_command("config", "Manipulate configuration records").require_commands();
auto &metric_command = parser.add_command("metric", "Manipulate performance metrics").require_commands();
@@ -122,9 +123,60 @@ main([[maybe_unused]] int argc, const char **argv)
.add_example_usage("traffic_ctl config match [OPTIONS] REGEX [REGEX ...]")
.add_option("--records", "", "Emit output in YAML format")
.add_option("--default", "", "Include the default value");
- config_command.add_command("reload", "Request a configuration reload", Command_Execute)
- .add_example_usage("traffic_ctl config reload");
- config_command.add_command("status", "Check the configuration status", Command_Execute)
+
+ //
+ // Start a new reload. If used without any extra options, it will start a new reload
+ // or show the details of the current reload if one is in progress.
+ // A new token will be assigned by the server if no token is provided.
+ config_command.add_command("reload", "Request a configuration reload", [&]() { command->execute(); })
+ .add_example_usage("traffic_ctl config reload")
+ //
+ // Start a new reload with a specific token. If no token is provided, the server will assign one.
+ // If a reload is already in progress, it will try to show the details of the current reload.
+ // If token already exists, you must use another token, or let the server assign one.
+ .add_option("--token", "-t", "Configuration token to reload.", "", 1, "")
+ //
+ // Start a new reload and monitor its progress until completion.
+ // Polls the server at regular intervals (see --refresh-int).
+ // If a reload is already in progress, monitors that one instead.
+ .add_option("--monitor", "-m", "Monitor reload progress until completion")
+ //
+ // Start a new reload. if one in progress it will show de details of the current reload.
+ // if no reload in progress, it will start a new one and it will show the details of it.
+ // This cannot be used with --monitor, if both are set, --show-details will be ignored.
+ .add_option("--show-details", "-s", "Show detailed information of the reload.")
+ .add_option("--include-logs", "-l", "include logs in the details. only work together with --show-details")
+
+ //
+ // Refresh interval in seconds used with --monitor.
+ // Controls how often to poll the server for reload status.
+ .add_option("--refresh-int", "-r", "Refresh interval in seconds (used with --monitor). Accepts fractional values (e.g. 0.5)",
+ "", 1, "0.5")
+ //
+ // The server will not let you start two reload at the same time. This option will force a new reload
+ // even if there is one in progress. Use with caution as this may have unexpected results.
+ // This is mostly for debugging and testing purposes. note: Should we keep it here?
+ .add_option("--force", "-F", "Force reload even if there are unsaved changes")
+ //
+ // Pass inline config data for reload. Like curl's -d flag:
+ // -d @file.yaml - read config from file
+ // -d @file1.yaml @file2.yaml - read multiple files
+ // -d @- - read config from stdin
+ // -d "yaml: content" - inline yaml string
+ .add_option("--data", "-d", "Inline config data (@file, @- for stdin, or yaml string)", "", MORE_THAN_ZERO_ARG_N, "")
+ .add_option(
+ "--initial-wait", "-w",
+ "Initial wait before first poll, giving the server time to schedule all handlers (seconds). Accepts fractional values", "", 1,
+ "2")
+ .add_option("--timeout", "-T",
+ "Maximum time to wait for reload completion (used with --monitor). "
+ "Accepts duration units: 30s, 1m, 500ms, etc. 0 means no timeout",
+ "", 1, "0")
+ .with_required("--monitor");
+
+ config_command.add_command("status", "Check the configuration status", [&]() { command->execute(); })
+ .add_option("--token", "-t", "Configuration token to check status.", "", 1, "")
+ .add_option("--count", "-c", "Number of status records to return. Use numeric or 'all' to get the full history", "", 1, "")
.add_example_usage("traffic_ctl config status");
config_command.add_command("set", "Set a configuration value", "", 2, Command_Execute)
.add_option("--cold", "-c",
diff --git a/src/traffic_logstats/CMakeLists.txt b/src/traffic_logstats/CMakeLists.txt
index f14d2b5381..c51118454d 100644
--- a/src/traffic_logstats/CMakeLists.txt
+++ b/src/traffic_logstats/CMakeLists.txt
@@ -16,7 +16,7 @@
#######################
add_executable(traffic_logstats logstats.cc)
-target_link_libraries(traffic_logstats PRIVATE ts::logging ts::tscore ts::diagsconfig ts::configmanager)
+target_link_libraries(traffic_logstats PRIVATE ts::logging ts::tscore ts::diagsconfig ts::records ts::configmanager)
install(TARGETS traffic_logstats)
diff --git a/src/traffic_server/CMakeLists.txt b/src/traffic_server/CMakeLists.txt
index 8bd5b8f284..f50ff2ef82 100644
--- a/src/traffic_server/CMakeLists.txt
+++ b/src/traffic_server/CMakeLists.txt
@@ -27,7 +27,6 @@ target_link_libraries(
ts::http2
ts::logging
ts::hdrs
- ts::configmanager
ts::diagsconfig
ts::inkutils
ts::inkdns
@@ -42,6 +41,7 @@ target_link_libraries(
ts::jsonrpc_protocol
ts::jsonrpc_server
ts::rpcpublichandlers
+ ts::configmanager
)
if(NOT APPLE)
# Skipping apple because macOS doesn't seem to provide an equivalent option
diff --git a/src/traffic_server/RpcAdminPubHandlers.cc b/src/traffic_server/RpcAdminPubHandlers.cc
index 4ab2706f44..f68f7f2f67 100644
--- a/src/traffic_server/RpcAdminPubHandlers.cc
+++ b/src/traffic_server/RpcAdminPubHandlers.cc
@@ -38,7 +38,10 @@ register_admin_jsonrpc_handlers()
using namespace rpc::handlers::config;
rpc::add_method_handler("admin_config_set_records", &set_config_records, &core_ats_rpc_service_provider_handle,
{{rpc::RESTRICTED_API}});
+ // Unified reload handler - supports both file-based and rpc-supplied modes.
rpc::add_method_handler("admin_config_reload", &reload_config, &core_ats_rpc_service_provider_handle, {{rpc::RESTRICTED_API}});
+ rpc::add_method_handler("get_reload_config_status", &get_reload_config_status, &core_ats_rpc_service_provider_handle,
+ {{rpc::RESTRICTED_API}});
// HostDB
using namespace rpc::handlers::hostdb;
diff --git a/src/traffic_server/traffic_server.cc b/src/traffic_server/traffic_server.cc
index 811539f143..831ac7f055 100644
--- a/src/traffic_server/traffic_server.cc
+++ b/src/traffic_server/traffic_server.cc
@@ -91,6 +91,8 @@ extern "C" int plock(int);
#include "iocore/eventsystem/RecProcess.h"
#include "proxy/Transform.h"
#include "iocore/eventsystem/ConfigProcessor.h"
+#include "mgmt/config/ConfigRegistry.h"
+#include "mgmt/config/ConfigContext.h"
#include "proxy/http/HttpProxyServerMain.h"
#include "proxy/http/HttpBodyFactory.h"
#include "proxy/ProxySession.h"
@@ -138,8 +140,6 @@ extern void load_config_file_callback(const char *parent_file, const char *remap
extern HttpBodyFactory *body_factory;
-extern void initializeRegistry();
-
extern void Initialize_Errata_Settings();
namespace
@@ -264,7 +264,7 @@ DbgCtl dbg_ctl_diags{"diags"};
DbgCtl dbg_ctl_hugepages{"hugepages"};
DbgCtl dbg_ctl_rpc_init{"rpc.init"};
DbgCtl dbg_ctl_statsproc{"statsproc"};
-
+DbgCtl dbg_ctl_conf_reload{"confreload"};
struct AutoStopCont : public Continuation {
int
mainEvent(int /* event */, Event * /* e */)
@@ -727,10 +727,59 @@ initialize_records()
ts::Metrics::StaticString::createString("proxy.process.version.server.build_person", version.build_person());
}
+// register_config_files
+//
+// Registration point for records.yaml and static (non-reloadable) config files.
+//
+// Most reloadable config files (ip_allow, sni, logging, etc.) register
+// themselves via ConfigRegistry::register_config() in their own modules
+// (IPAllow.cc, SSLClientCoordinator.cc, LogConfig.cc, etc.).
+//
+// records.yaml is special:
+// - It is first read at startup inside RecCoreInit() (src/records/RecCore.cc),
+// which is called through RecProcessInit() → initialize_records() well before
+// this function.
+// - On reload (file change detected by FileManager), process_config_update() in
+// FileManager.cc delegates to ConfigRegistry::execute_reload("records"), which
+// invokes the handler below.
+// - The handler calls RecReadYamlConfigFile() (src/records/P_RecCore.cc), the same
+// function used at startup, to re-parse the file.
+//
+// Static/non-reloadable files (storage.config, socks.config, volume.config,
+// plugin.config, jsonrpc.yaml) are registered via register_static_file() for
+// inventory purposes (filemanager.get_files_registry RPC endpoint and future work).
+//
void
-initialize_file_manager()
+register_config_files()
{
- initializeRegistry();
+ using namespace config;
+ auto ® = ConfigRegistry::Get_Instance();
+
+ // records.yaml — reloadable.
+ // First read happens at startup in RecCoreInit() (src/records/RecCore.cc:244).
+ // This handler is only invoked on runtime reload via ConfigRegistry::execute_reload("records").
+ reg.register_config(
+ "records", ts::filename::RECORDS, ts::filename::RECORDS,
+ [](ConfigContext ctx) {
+ if (auto zret = RecReadYamlConfigFile(); zret) {
+ RecConfigWarnIfUnregistered(ctx);
+ } else {
+ ctx.log("{}", zret);
+ if (zret.severity() >= ERRATA_ERROR) {
+ ctx.fail("Failed to reload records.yaml");
+ return;
+ }
+ }
+ ctx.complete();
+ },
+ ConfigSource::FileOnly);
+
+ // Static (non-reloadable) files only.
+ reg.register_static_file("storage", ts::filename::STORAGE, {}, true);
+ reg.register_static_file("socks", ts::filename::SOCKS, "proxy.config.socks.socks_config_file");
+ reg.register_static_file("volume", ts::filename::VOLUME);
+ reg.register_static_file("plugin", ts::filename::PLUGIN);
+ reg.register_static_file("jsonrpc", ts::filename::JSONRPC, "proxy.config.jsonrpc.filename");
}
std::tuple<bool, std::string>
@@ -1864,8 +1913,8 @@ main(int /* argc ATS_UNUSED */, const char **argv)
// Records init
initialize_records();
- // Initialize file manager for TS.
- initialize_file_manager();
+ // Register non reloadable config files and records.yaml.
+ register_config_files();
// Set the core limit for the process
init_core_size();
@@ -2238,7 +2287,7 @@ main(int /* argc ATS_UNUSED */, const char **argv)
#if TS_USE_QUIC == 1
quic_NetProcessor.start(-1, stacksize);
#endif
- FileManager::instance().registerConfigPluginCallbacks(global_config_cbs);
+ FileManager::instance().registerConfigPluginCallbacks([&]() { global_config_cbs->invoke(); });
cacheProcessor.afterInitCallbackSet(&CB_After_Cache_Init);
cacheProcessor.start();
diff --git a/src/tscore/ArgParser.cc b/src/tscore/ArgParser.cc
index 65298317a6..170ec885d3 100644
--- a/src/tscore/ArgParser.cc
+++ b/src/tscore/ArgParser.cc
@@ -725,7 +725,14 @@ ArgParser::Command::append_option_data(Arguments &ret, AP_StrVec &args, int inde
help_message(std::to_string(_option_list.at(it.first).arg_num) + " arguments expected by " + it.first);
}
}
- // put in the default value of options
+}
+
+// Apply default values for options not explicitly set by the user.
+// This must be called AFTER validate_dependencies() so that default values
+// (e.g. --timeout "0") don't falsely trigger dependency checks.
+void
+ArgParser::Command::apply_option_defaults(Arguments &ret)
+{
for (const auto &it : _option_list) {
if (!it.second.default_value.empty() && ret.get(it.second.key).empty()) {
std::istringstream ss(it.second.default_value);
@@ -771,6 +778,11 @@ ArgParser::Command::parse(Arguments &ret, AP_StrVec &args)
// Validate option dependencies
validate_dependencies(ret);
+
+ // Apply default values after validation so that defaults don't
+ // trigger dependency checks (e.g. --timeout with default "0"
+ // should not require --monitor when not explicitly used).
+ apply_option_defaults(ret);
}
if (command_called) {
diff --git a/src/tscore/unit_tests/test_ArgParser.cc b/src/tscore/unit_tests/test_ArgParser.cc
index 672a702a28..0a32502e96 100644
--- a/src/tscore/unit_tests/test_ArgParser.cc
+++ b/src/tscore/unit_tests/test_ArgParser.cc
@@ -148,3 +148,72 @@ TEST_CASE("Invoke test", "[invoke]")
parsed_data.invoke();
REQUIRE(global == 2);
}
+
+TEST_CASE("Case sensitive short options", "[parse]")
+{
+ ts::ArgParser cs_parser;
+ cs_parser.add_global_usage("test_prog [--SWITCH]");
+
+ // Add a command with two options that differ only in case: -t and -T
+ ts::ArgParser::Command &cmd = cs_parser.add_command("process", "process data");
+ cmd.add_option("--tag", "-t", "a label", "", 1, "");
+ cmd.add_option("--threshold", "-T", "a numeric value", "", 1, "100");
+
+ ts::Arguments parsed;
+
+ // Use lowercase -t: should set "tag" only
+ const char *argv1[] = {"test_prog", "process", "-t", "my_tag", nullptr};
+ parsed = cs_parser.parse(argv1);
+ REQUIRE(parsed.get("tag") == true);
+ REQUIRE(parsed.get("tag").value() == "my_tag");
+ // threshold should still have its default
+ REQUIRE(parsed.get("threshold").value() == "100");
+
+ // Use uppercase -T: should set "threshold" only
+ const char *argv2[] = {"test_prog", "process", "-T", "200", nullptr};
+ parsed = cs_parser.parse(argv2);
+ REQUIRE(parsed.get("threshold") == true);
+ REQUIRE(parsed.get("threshold").value() == "200");
+ // tag should be empty (no default)
+ REQUIRE(parsed.get("tag").value() == "");
+
+ // Use both -t and -T together
+ const char *argv3[] = {"test_prog", "process", "-t", "foo", "-T", "500", nullptr};
+ parsed = cs_parser.parse(argv3);
+ REQUIRE(parsed.get("tag") == true);
+ REQUIRE(parsed.get("tag").value() == "foo");
+ REQUIRE(parsed.get("threshold") == true);
+ REQUIRE(parsed.get("threshold").value() == "500");
+}
+
+TEST_CASE("with_required does not trigger on default values", "[parse]")
+{
+ ts::ArgParser parser;
+ parser.add_global_usage("test_prog [OPTIONS]");
+
+ ts::ArgParser::Command &cmd = parser.add_command("scan", "scan targets");
+ cmd.add_option("--tag", "-t", "a label", "", 1, "");
+ cmd.add_option("--verbose", "-v", "enable verbose output");
+ cmd.add_option("--threshold", "-T", "a numeric value", "", 1, "100").with_required("--verbose");
+
+ // -t alone should NOT trigger --threshold's dependency on --verbose.
+ // The default value "100" for --threshold must not count as "explicitly used".
+ const char *argv1[] = {"test_prog", "scan", "-t", "my_tag", nullptr};
+ ts::Arguments parsed = parser.parse(argv1);
+ REQUIRE(parsed.get("tag").value() == "my_tag");
+ // threshold default should still be applied after validation
+ REQUIRE(parsed.get("threshold").value() == "100");
+
+ // -T with -v should work fine
+ const char *argv2[] = {"test_prog", "scan", "-T", "200", "-v", nullptr};
+ parsed = parser.parse(argv2);
+ REQUIRE(parsed.get("threshold").value() == "200");
+ REQUIRE(parsed.get("verbose") == true);
+
+ // -t and -T together with -v should work
+ const char *argv3[] = {"test_prog", "scan", "-t", "foo", "-T", "300", "-v", nullptr};
+ parsed = parser.parse(argv3);
+ REQUIRE(parsed.get("tag").value() == "foo");
+ REQUIRE(parsed.get("threshold").value() == "300");
+ REQUIRE(parsed.get("verbose") == true);
+}
diff --git a/tests/gold_tests/cache/cache_config_reload.test.py b/tests/gold_tests/cache/cache_config_reload.test.py
new file mode 100644
index 0000000000..21bb799828
--- /dev/null
+++ b/tests/gold_tests/cache/cache_config_reload.test.py
@@ -0,0 +1,72 @@
+'''
+Test cache.config and hosting.config reload via ConfigRegistry.
+
+Verifies that:
+1. cache.config reload works after file touch
+2. hosting.config reload works after file touch (requires cache to be initialized)
+'''
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import os
+
+Test.Summary = '''
+Test cache.config and hosting.config reload via ConfigRegistry.
+'''
+
+Test.ContinueOnFail = True
+
+# Create ATS with cache enabled (needed for hosting.config registration in open_done)
+ts = Test.MakeATSProcess("ts", enable_cache=True)
+ts.Disk.records_config.update({
+ 'proxy.config.diags.debug.enabled': 1,
+ 'proxy.config.diags.debug.tags': 'rpc|config',
+})
+
+# Set up initial cache.config with a caching rule
+ts.Disk.cache_config.AddLine('dest_domain=example.com ttl-in-cache=30d')
+
+config_dir = ts.Variables.CONFIGDIR
+
+# --- Test 1: Touch cache.config and reload ---
+
+tr = Test.AddTestRun("Touch cache.config to trigger change detection")
+tr.Processes.Default.StartBefore(ts)
+tr.Processes.Default.Command = f"touch {os.path.join(config_dir, 'cache.config')} && sleep 2"
+tr.Processes.Default.ReturnCode = 0
+tr.StillRunningAfter = ts
+
+tr = Test.AddTestRun("Reload after cache.config touch")
+tr.Processes.Default.Env = ts.Env
+tr.Processes.Default.Command = 'traffic_ctl config reload --show-details --token reload_cache_test'
+tr.Processes.Default.ReturnCode = Any(0, 2)
+tr.StillRunningAfter = ts
+tr.Processes.Default.Streams.stdout = Testers.ContainsExpression("cache.config", "Reload output should reference cache.config")
+
+# --- Test 2: Touch hosting.config and reload ---
+
+tr = Test.AddTestRun("Touch hosting.config to trigger change detection")
+tr.DelayStart = 3
+tr.Processes.Default.Command = f"touch {os.path.join(config_dir, 'hosting.config')} && sleep 2"
+tr.Processes.Default.ReturnCode = 0
+tr.StillRunningAfter = ts
+
+tr = Test.AddTestRun("Reload after hosting.config touch")
+tr.Processes.Default.Env = ts.Env
+tr.Processes.Default.Command = 'traffic_ctl config reload --show-details --token reload_hosting_test'
+tr.Processes.Default.ReturnCode = Any(0, 2)
+tr.StillRunningAfter = ts
+tr.Processes.Default.Streams.stdout = Testers.ContainsExpression("hosting.config", "Reload output should reference hosting.config")
diff --git a/tests/gold_tests/dns/splitdns_reload.test.py b/tests/gold_tests/dns/splitdns_reload.test.py
new file mode 100644
index 0000000000..aa05867530
--- /dev/null
+++ b/tests/gold_tests/dns/splitdns_reload.test.py
@@ -0,0 +1,90 @@
+'''
+Test splitdns.config reload via ConfigRegistry.
+
+Verifies that:
+1. splitdns.config reload works after file touch
+2. The reload handler is invoked (diags log check)
+'''
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import os
+
+Test.Summary = 'Test splitdns.config reload via ConfigRegistry.'
+Test.ContinueOnFail = True
+
+
+class SplitDNSReloadTest:
+
+ def __init__(self):
+ self.setupDNSServer()
+ self.setupOriginServer()
+ self.setupTS()
+
+ def setupDNSServer(self):
+ self.dns = Test.MakeDNServer("dns")
+ self.dns.addRecords(records={'foo.ts.a.o.': ['127.0.0.1']})
+
+ def setupOriginServer(self):
+ self.origin_server = Test.MakeOriginServer("origin_server")
+ self.origin_server.addResponse(
+ "sessionlog.json", {"headers": "GET / HTTP/1.1\r\nHost: localhost\r\n\r\n"},
+ {"headers": "HTTP/1.1 200 OK\r\nServer: microserver\r\nConnection: close\r\n\r\n"})
+
+ def setupTS(self):
+ self.ts = Test.MakeATSProcess("ts", enable_cache=False)
+ self.ts.Disk.records_config.update(
+ {
+ 'proxy.config.dns.splitDNS.enabled': 1,
+ 'proxy.config.diags.debug.enabled': 1,
+ 'proxy.config.diags.debug.tags': 'splitdns|config',
+ })
+ self.ts.Disk.splitdns_config.AddLine(f"dest_domain=foo.ts.a.o named=127.0.0.1:{self.dns.Variables.Port}")
+ self.ts.Disk.remap_config.AddLine(f"map /foo/ http://foo.ts.a.o:{self.origin_server.Variables.Port}/")
+
+ def run(self):
+ config_dir = self.ts.Variables.CONFIGDIR
+
+ # Test 1: Verify basic SplitDNS works (startup loads config)
+ tr = Test.AddTestRun("Verify SplitDNS works at startup")
+ tr.MakeCurlCommand(f"-v http://localhost:{self.ts.Variables.port}/foo/", ts=self.ts)
+ tr.Processes.Default.ReturnCode = 0
+ tr.Processes.Default.StartBefore(self.dns)
+ tr.Processes.Default.StartBefore(self.origin_server)
+ tr.Processes.Default.StartBefore(self.ts)
+ tr.StillRunningAfter = self.ts
+
+ # Test 2: Touch splitdns.config -> reload -> handler fires
+ tr = Test.AddTestRun("Touch splitdns.config")
+ tr.Processes.Default.Command = (f"touch {os.path.join(config_dir, 'splitdns.config')} && sleep 1")
+ tr.Processes.Default.ReturnCode = 0
+ tr.StillRunningAfter = self.ts
+
+ tr = Test.AddTestRun("Reload after splitdns.config touch")
+ p = tr.Processes.Process("reload-1")
+ p.Command = 'traffic_ctl config reload; sleep 30'
+ p.Env = self.ts.Env
+ p.ReturnCode = Any(0, -2)
+ # Wait for 2nd "finished loading" (1st is startup)
+ p.Ready = When.FileContains(self.ts.Disk.diags_log.Name, "splitdns.config finished loading", 2)
+ p.Timeout = 20
+ tr.Processes.Default.StartBefore(p)
+ tr.Processes.Default.Command = ('echo "waiting for splitdns.config reload"')
+ tr.TimeOut = 25
+ tr.StillRunningAfter = self.ts
+
+
+SplitDNSReloadTest().run()
diff --git a/tests/gold_tests/ip_allow/ip_allow_reload_triggered.test.py b/tests/gold_tests/ip_allow/ip_allow_reload_triggered.test.py
new file mode 100644
index 0000000000..3466e9de06
--- /dev/null
+++ b/tests/gold_tests/ip_allow/ip_allow_reload_triggered.test.py
@@ -0,0 +1,256 @@
+'''
+Test ip_allow and ip_categories reload via ConfigRegistry.
+
+Verifies that:
+1. ip_allow.yaml touch triggers ip_allow reload
+2. ip_categories touch triggers ip_allow reload (via add_file_dependency)
+3. Unrelated config touch (hosting.config) does NOT trigger ip_allow reload
+4. ip_categories content change causes actual behavior change after reload
+5. Changing ip_categories record value (traffic_ctl config set) triggers ip_allow reload
+'''
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import os
+import shutil
+
+Test.Summary = '''
+Test ip_allow and ip_categories reload via ConfigRegistry add_file_dependency.
+'''
+
+Test.ContinueOnFail = True
+
+# --- Setup: origin server ---
+server = Test.MakeOriginServer("server", ssl=False)
+request = {"headers": "GET /test HTTP/1.1\r\nHost: www.example.com\r\n\r\n", "timestamp": "1469733493.993", "body": ""}
+response = {
+ "headers": "HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\n",
+ "timestamp": "1469733493.993",
+ "body": "ok"
+}
+server.addResponse("sessionlog.json", request, response)
+
+# --- Setup: ip_categories file variants ---
+
+# Version A: 127.0.0.1 is INTERNAL (requests allowed)
+categories_allow = os.path.join(Test.RunDirectory, 'categories_allow.yaml')
+with open(categories_allow, 'w') as f:
+ f.write('ip_categories:\n - name: INTERNAL\n ip_addrs: 127.0.0.1\n')
+
+# Version B: 127.0.0.1 is NOT INTERNAL (GET denied, only HEAD allowed by catch-all)
+categories_deny = os.path.join(Test.RunDirectory, 'categories_deny.yaml')
+with open(categories_deny, 'w') as f:
+ f.write('ip_categories:\n - name: INTERNAL\n ip_addrs: 1.2.3.4\n')
+
+# Version C: 127.0.0.1 back in INTERNAL (for record value change test)
+categories_restore = os.path.join(Test.RunDirectory, 'categories_restore.yaml')
+with open(categories_restore, 'w') as f:
+ f.write('ip_categories:\n - name: INTERNAL\n ip_addrs: 127.0.0.1\n')
+
+# Active ip_categories file that the record points to (start with allow version)
+categories_file = os.path.join(Test.RunDirectory, 'ip_categories.yaml')
+shutil.copy(categories_allow, categories_file)
+
+# --- Setup: ATS ---
+ts = Test.MakeATSProcess("ts", enable_cache=True)
+
+ts.Disk.records_config.update(
+ {
+ 'proxy.config.diags.debug.enabled': 1,
+ 'proxy.config.diags.debug.tags': 'ip_allow|config',
+ 'proxy.config.cache.ip_categories.filename': categories_file,
+ })
+
+# ip_allow config:
+# Rule 1: INTERNAL category → allow ALL methods
+# Rule 2: catch-all 0/0 → allow only HEAD
+#
+# Effect:
+# 127.0.0.1 in INTERNAL → GET /test → 200 (rule 1 matches)
+# 127.0.0.1 NOT in INTERNAL → GET /test → 403 (rule 2 matches, GET not allowed)
+ts.Disk.ip_allow_yaml.AddLines(
+ '''ip_allow:
+ - apply: in
+ ip_categories: INTERNAL
+ action: allow
+ methods: ALL
+ - apply: in
+ ip_addrs: 0/0
+ action: allow
+ methods:
+ - HEAD
+'''.split("\n"))
+
+ts.Disk.remap_config.AddLine(f'map / http://127.0.0.1:{server.Variables.Port}')
+
+config_dir = ts.Variables.CONFIGDIR
+reload_counter = 0
+
+# ================================================================
+# Test 1: Touch ip_allow.yaml → reload → ip_allow reloads (count 2)
+# ================================================================
+
+tr = Test.AddTestRun("Touch ip_allow.yaml")
+tr.Processes.Default.StartBefore(server, ready=When.PortOpen(server.Variables.Port))
+tr.Processes.Default.StartBefore(ts)
+tr.Processes.Default.Command = f"sleep 3 && touch {os.path.join(config_dir, 'ip_allow.yaml')} && sleep 1"
+tr.Processes.Default.ReturnCode = 0
+tr.StillRunningAfter = ts
+tr.StillRunningAfter = server
+
+reload_counter += 1
+tr = Test.AddTestRun("Reload after ip_allow.yaml touch")
+p = tr.Processes.Process(f"reload-{reload_counter}")
+p.Command = 'traffic_ctl config reload; sleep 30'
+p.Env = ts.Env
+p.ReturnCode = Any(0, -2)
+p.Ready = When.FileContains(ts.Disk.diags_log.Name, "ip_allow.yaml finished loading", 1 + reload_counter)
+p.Timeout = 20
+tr.Processes.Default.StartBefore(p)
+tr.Processes.Default.Command = 'echo "waiting for ip_allow reload after ip_allow.yaml touch"'
+tr.TimeOut = 25
+tr.StillRunningAfter = ts
+
+# ================================================================
+# Test 2: Touch ip_categories → reload → ip_allow reloads (count 3)
+# Verifies add_file_dependency() correctly wired ip_categories
+# to trigger ip_allow reload via FileManager mtime detection.
+# ================================================================
+
+tr = Test.AddTestRun("Touch ip_categories")
+tr.Processes.Default.Command = f"touch {categories_file} && sleep 1"
+tr.Processes.Default.ReturnCode = 0
+tr.StillRunningAfter = ts
+
+reload_counter += 1
+tr = Test.AddTestRun("Reload after ip_categories touch")
+p = tr.Processes.Process(f"reload-{reload_counter}")
+p.Command = 'traffic_ctl config reload; sleep 30'
+p.Env = ts.Env
+p.ReturnCode = Any(0, -2)
+p.Ready = When.FileContains(ts.Disk.diags_log.Name, "ip_allow.yaml finished loading", 1 + reload_counter)
+p.Timeout = 20
+tr.Processes.Default.StartBefore(p)
+tr.Processes.Default.Command = 'echo "waiting for ip_allow reload after ip_categories touch"'
+tr.TimeOut = 25
+tr.StillRunningAfter = ts
+
+# ================================================================
+# Test 3: Touch hosting.config → reload → ip_allow NOT triggered
+# Verifies the fix for the false trigger bug where changing
+# any file in the config directory spuriously triggered
+# ip_allow reload (due to FileManager watching the directory
+# instead of ip_categories.yaml when the record was "").
+# ================================================================
+
+tr = Test.AddTestRun("Touch hosting.config and reload (should NOT trigger ip_allow)")
+tr.Processes.Default.Command = (
+ f"touch {os.path.join(config_dir, 'hosting.config')} && "
+ f"sleep 1 && "
+ f"traffic_ctl config reload && "
+ f"sleep 5")
+tr.Processes.Default.Env = ts.Env
+tr.Processes.Default.ReturnCode = Any(0, -2)
+tr.Processes.Default.Timeout = 15
+tr.StillRunningAfter = ts
+
+tr = Test.AddTestRun("Verify ip_allow loaded exactly 3 times (no false trigger)")
+tr.DelayStart = 3
+tr.Processes.Default.Command = (f"grep -c 'ip_allow.yaml finished loading' {ts.Disk.diags_log.Name} "
+ f"| grep -qx 3")
+tr.Processes.Default.ReturnCode = 0
+tr.StillRunningAfter = ts
+
+# ================================================================
+# Test 4: Functional — change ip_categories content, verify behavior
+# Proves that add_file_dependency() not only triggers the
+# reload but that the handler actually re-reads the updated
+# ip_categories file.
+# ================================================================
+
+# 4a: Verify initial state: GET → 200 (127.0.0.1 is in INTERNAL)
+tr = Test.AddTestRun("GET should succeed (127.0.0.1 in INTERNAL category)")
+tr.Processes.Default.Command = (f"curl -s -o /dev/null -w '%{{http_code}}' "
+ f"http://127.0.0.1:{ts.Variables.port}/test")
+tr.Processes.Default.ReturnCode = 0
+tr.Processes.Default.Streams.stdout = Testers.ContainsExpression("200", "Should get 200 when 127.0.0.1 is in INTERNAL category")
+tr.StillRunningAfter = ts
+tr.StillRunningAfter = server
+
+# 4b: Swap ip_categories to deny version (127.0.0.1 NOT in INTERNAL)
+tr = Test.AddTestRun("Change ip_categories to deny 127.0.0.1")
+tr.Processes.Default.Command = f"cp {categories_deny} {categories_file}"
+tr.Processes.Default.ReturnCode = 0
+tr.StillRunningAfter = ts
+
+# 4c: Reload and wait for ip_allow to pick up the change
+reload_counter += 1
+tr = Test.AddTestRun("Reload after ip_categories content change")
+p = tr.Processes.Process(f"reload-{reload_counter}")
+p.Command = 'traffic_ctl config reload; sleep 30'
+p.Env = ts.Env
+p.ReturnCode = Any(0, -2)
+p.Ready = When.FileContains(ts.Disk.diags_log.Name, "ip_allow.yaml finished loading", 1 + reload_counter)
+p.Timeout = 20
+tr.Processes.Default.StartBefore(p)
+tr.Processes.Default.Command = 'echo "waiting for reload after ip_categories content change"'
+tr.TimeOut = 25
+tr.StillRunningAfter = ts
+
+# 4d: GET should now be denied (falls to catch-all: only HEAD allowed)
+tr = Test.AddTestRun("GET should be denied (127.0.0.1 NOT in INTERNAL)")
+tr.Processes.Default.Command = (f"curl -s -o /dev/null -w '%{{http_code}}' "
+ f"http://127.0.0.1:{ts.Variables.port}/test")
+tr.Processes.Default.ReturnCode = 0
+tr.Processes.Default.Streams.stdout = Testers.ContainsExpression("403", "Should get 403 when 127.0.0.1 is not in INTERNAL category")
+tr.StillRunningAfter = ts
+tr.StillRunningAfter = server
+
+# ================================================================
+# Test 5: Record value change triggers ip_allow reload
+# Changes the ip_categories filename record via traffic_ctl
+# config set (no explicit config reload). The callback
+# registered by add_file_dependency() fires when the record
+# value changes, triggering ip_allow reload with the new file.
+# ================================================================
+
+# 5a: Change the ip_categories filename record to point to categories_restore
+# (which has 127.0.0.1 back in INTERNAL).
+# No traffic_ctl config reload — the RecRegisterConfigUpdateCb fires
+# automatically via config_update_cont when the record value changes.
+reload_counter += 1
+tr = Test.AddTestRun("Change ip_categories record value to new file")
+p = tr.Processes.Process(f"reload-{reload_counter}")
+p.Command = (f"traffic_ctl config set proxy.config.cache.ip_categories.filename "
+ f"'{categories_restore}'; sleep 30")
+p.Env = ts.Env
+p.ReturnCode = Any(0, -2)
+p.Ready = When.FileContains(ts.Disk.diags_log.Name, "ip_allow.yaml finished loading", 1 + reload_counter)
+p.Timeout = 20
+tr.Processes.Default.StartBefore(p)
+tr.Processes.Default.Command = 'echo "waiting for ip_allow reload after record value change"'
+tr.TimeOut = 25
+tr.StillRunningAfter = ts
+
+# 5b: GET should succeed again (new file has 127.0.0.1 in INTERNAL)
+tr = Test.AddTestRun("GET should succeed after record value change")
+tr.Processes.Default.Command = (f"curl -s -o /dev/null -w '%{{http_code}}' "
+ f"http://127.0.0.1:{ts.Variables.port}/test")
+tr.Processes.Default.ReturnCode = 0
+tr.Processes.Default.Streams.stdout = Testers.ContainsExpression(
+ "200", "Should get 200 after restoring INTERNAL category via record change")
+tr.StillRunningAfter = ts
+tr.StillRunningAfter = server
diff --git a/tests/gold_tests/ip_allow/ip_category.test.py b/tests/gold_tests/ip_allow/ip_category.test.py
index 3e0f29bd1c..13a9899e80 100644
--- a/tests/gold_tests/ip_allow/ip_category.test.py
+++ b/tests/gold_tests/ip_allow/ip_category.test.py
@@ -228,7 +228,7 @@ ssl_multicert:
ts.Disk.records_config.update(
{
'proxy.config.diags.debug.enabled': 1,
- 'proxy.config.diags.debug.tags': 'http|ip_allow',
+ 'proxy.config.diags.debug.tags': 'http|ip_allow|config.reload',
'proxy.config.cache.ip_categories.filename': Test_ip_category._categories_filename,
'proxy.config.http.push_method_enabled': 1,
'proxy.config.ssl.server.cert.path': ts.Variables.SSLDir,
diff --git a/tests/gold_tests/jsonrpc/config_reload_dedup.test.py b/tests/gold_tests/jsonrpc/config_reload_dedup.test.py
new file mode 100644
index 0000000000..1426aed481
--- /dev/null
+++ b/tests/gold_tests/jsonrpc/config_reload_dedup.test.py
@@ -0,0 +1,160 @@
+'''
+Test that a trigger-record value change in records.yaml is handled correctly
+during a reload, including deduplication when the 3s config_update_cont timer
+fires the same on_record_change callback again.
+
+Scenario:
+ 1. Change proxy.config.ssl.server.session_ticket.enable in records.yaml
+ via --cold. This is a trigger record for ssl_client_coordinator
+ (registered via register_record_config with 11 trigger records).
+
+ 2. Touch sni.yaml — this also triggers ssl_client_coordinator via
+ add_file_and_node_dependency (proxy.config.ssl.servername.filename).
+ So ssl_client_coordinator gets hit from TWO paths: the value change
+ callback AND the file-mtime callback.
+
+ 3. Touch other config files (ip_allow, logging) for broader coverage.
+
+ 4. Trigger a reload and wait for completion.
+
+ 5. Wait long enough (>6s) for the 3s config_update_cont timer to fire
+ at least once during or after the reload. When it fires:
+ a. If the reload is still in progress — create_config_context()
+ finds the existing subtask and logs "Duplicate reload …skipping".
+ b. If the reload already completed (SUCCESS) — create_config_context()
+ may create a new subtask, the handler runs again, and the task
+ re-settles to SUCCESS.
+ Either way, no crash, no stuck tasks, no state-transition conflicts.
+
+ 6. Verify:
+ - "Reserved subtask" messages present (reserve_subtask worked)
+ - ssl_client_coordinator subtask completed successfully
+ - No "ignoring transition from" messages (no state corruption)
+ - Final status is success (even if briefly flickered)
+'''
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+Test.Summary = 'Verify trigger-record value change + file-mtime dedup during reload'
+Test.ContinueOnFail = True
+
+# --- Setup ---
+ts = Test.MakeATSProcess("ts", enable_cache=True)
+ts.StartupTimeout = 30
+
+ts.Disk.records_config.update(
+ {
+ 'proxy.config.diags.debug.enabled': 1,
+ 'proxy.config.diags.debug.tags': 'rpc|config|config.reload|configproc',
+ })
+
+# Provide valid content for config files whose handlers reject empty input.
+ts.Disk.ip_allow_yaml.AddLines([
+ 'ip_allow:',
+ '- apply: in',
+ ' ip_addrs: 0/0',
+ ' action: allow',
+ ' methods: ALL',
+])
+ts.Disk.logging_yaml.AddLines([
+ 'logging:',
+ ' formats:',
+ ' - name: dedup_test',
+ ' format: "%<cqtq>"',
+])
+ts.Disk.sni_yaml.AddLines([
+ 'sni:',
+ '- fqdn: "*.example.com"',
+ ' verify_client: NONE',
+])
+
+# Files to touch — sni.yaml is key because it also triggers
+# ssl_client_coordinator via add_file_and_node_dependency.
+files_to_touch = [
+ ts.Disk.ip_allow_yaml,
+ ts.Disk.logging_yaml,
+ ts.Disk.sni_yaml,
+]
+touch_cmd = "touch " + " ".join([f.AbsRunTimePath for f in files_to_touch])
+
+# ============================================================================
+# Test 1: Change a trigger-record VALUE in records.yaml via --cold
+#
+# proxy.config.ssl.server.session_ticket.enable is a trigger record for
+# ssl_client_coordinator. Toggling it from 1→0 modifies records.yaml on
+# disk. When the reload fires, rereadConfig → RecReadYamlConfigFile →
+# RecSetRecord sets update_required on this record. RecFlushConfigUpdateCbs
+# fires the on_record_change callback. Later the 3s timer may fire it again.
+# ============================================================================
+tr = Test.AddTestRun("Change trigger record value in records.yaml via --cold")
+tr.Processes.Default.StartBefore(ts)
+tr.Processes.Default.Command = ('sleep 3 && traffic_ctl config set proxy.config.ssl.server.session_ticket.enable 0 --cold')
+tr.Processes.Default.Env = ts.Env
+tr.Processes.Default.ReturnCode = 0
+tr.StillRunningAfter = ts
+
+# ============================================================================
+# Test 2: Touch config files — sni.yaml is the critical one
+#
+# sni.yaml's mtime change triggers RecSetSyncRequired on
+# proxy.config.ssl.servername.filename, which is wired to
+# ssl_client_coordinator. So ssl_client_coordinator gets hit from two paths:
+# 1. proxy.config.ssl.server.session_ticket.enable value change (from records.yaml)
+# 2. proxy.config.ssl.servername.filename sync-required (from sni.yaml mtime)
+# This exercises the fan-in deduplication in on_record_change / reserve_subtask.
+# ============================================================================
+tr = Test.AddTestRun("Touch config files including sni.yaml")
+tr.Processes.Default.Command = touch_cmd
+tr.Processes.Default.ReturnCode = 0
+tr.StillRunningAfter = ts
+
+# ============================================================================
+# Test 3: Trigger reload
+# ============================================================================
+tr = Test.AddTestRun("Trigger reload with named token")
+tr.Processes.Default.Command = "traffic_ctl config reload -t dedup_test"
+tr.Processes.Default.Env = ts.Env
+tr.Processes.Default.ReturnCode = 0
+tr.StillRunningAfter = ts
+
+# ============================================================================
+# Test 4: Wait long enough for the 3s timer to fire at least twice
+#
+# The config_update_cont timer fires every 3s. We wait 15s to ensure:
+# - All subtasks complete (ip_allow, logging, remap, ssl, etc.)
+# - The 3s timer fires at least 4 times during/after the reload
+# - Any duplicate on_record_change callbacks have been processed
+# ============================================================================
+tr = Test.AddTestRun("Verify reload completed — no tasks stuck in progress")
+tr.DelayStart = 15
+tr.Processes.Default.Command = "traffic_ctl config status -t dedup_test"
+tr.Processes.Default.Env = ts.Env
+tr.Processes.Default.ReturnCode = 0
+tr.Processes.Default.Streams.stdout += Testers.ExcludesExpression(
+ "in_progress", "No task should remain in progress after 15s delay")
+# ssl_client_coordinator must be present in the output (it was triggered)
+tr.Processes.Default.Streams.stdout += Testers.ContainsExpression(
+ "ssl_client_coordinator", "ssl_client_coordinator subtask must appear in status")
+tr.Processes.Default.Streams.stdout += Testers.ContainsExpression("success", "Final status must be success")
+tr.StillRunningAfter = ts
+
+# ============================================================================
+# Test 5: No state-transition conflicts anywhere in the logs
+# ============================================================================
+ts.Disk.traffic_out.Content += Testers.ExcludesExpression(
+ "ignoring transition from", "No state-transition conflicts should appear in traffic.out")
+ts.Disk.traffic_out.Content += Testers.ContainsExpression(
+ "Reserved subtask", "reserve_subtask() must log pre-registration messages")
diff --git a/tests/gold_tests/jsonrpc/config_reload_failures.test.py b/tests/gold_tests/jsonrpc/config_reload_failures.test.py
new file mode 100644
index 0000000000..b000176f4d
--- /dev/null
+++ b/tests/gold_tests/jsonrpc/config_reload_failures.test.py
@@ -0,0 +1,429 @@
+'''
+Test config reload failure scenarios.
+
+Tests:
+1. Failed tasks (invalid config content)
+2. Failed subtasks (invalid SSL certificates)
+3. Incomplete subtasks (timeout scenarios)
+4. Status propagation when subtasks fail
+'''
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from jsonrpc import Request, Response
+import os
+
+Test.Summary = 'Test config reload failure scenarios and status propagation'
+Test.ContinueOnFail = True
+
+ts = Test.MakeATSProcess('ts', dump_runroot=True, enable_tls=True)
+
+Test.testName = 'config_reload_failures'
+
+# Enable debugging
+ts.Disk.records_config.update(
+ {
+ 'proxy.config.diags.debug.enabled': 1,
+ 'proxy.config.diags.debug.tags': 'config|ssl|ip_allow',
+ 'proxy.config.ssl.server.cert.path': ts.Variables.SSLDir,
+ 'proxy.config.ssl.server.private_key.path': ts.Variables.SSLDir,
+ })
+
+# Add valid SSL certs for baseline
+ts.addDefaultSSLFiles()
+
+ts.Disk.ssl_multicert_yaml.AddLines(
+ [
+ 'ssl_multicert:',
+ ' - dest_ip: "*"',
+ ' ssl_cert_name: server.pem',
+ ' ssl_key_name: server.key',
+ ])
+
+# Override default diags check — this test intentionally triggers SSL errors
+ts.Disk.diags_log.Content = Testers.ContainsExpression("ERROR", "Expected errors from invalid SSL cert injection")
+
+# ============================================================================
+# Test 1: Baseline - successful reload
+# ============================================================================
+tr = Test.AddTestRun("Baseline - successful reload")
+tr.Processes.Default.StartBefore(ts)
+tr.DelayStart = 2
+tr.AddJsonRPCClientRequest(ts, Request.admin_config_reload(force=True))
+
+
+def validate_baseline(resp: Response):
+ '''Verify baseline reload succeeds'''
+ if resp.is_error():
+ return (False, f"Baseline failed: {resp.error_as_str()}")
+
+ result = resp.result
+ token = result.get('token', '')
+ return (True, f"Baseline succeeded: token={token}")
+
+
+tr.Processes.Default.Streams.stdout = Testers.CustomJSONRPCResponse(validate_baseline)
+tr.StillRunningAfter = ts
+
+# ============================================================================
+# Test 2: Wait and check baseline completed successfully
+# ============================================================================
+tr = Test.AddTestRun("Verify baseline completed with success status")
+tr.DelayStart = 3
+tr.AddJsonRPCClientRequest(ts, Request.admin_config_reload())
+
+
+def validate_baseline_status(resp: Response):
+ '''Check baseline reload status'''
+ if resp.is_error():
+ error = resp.error_as_str()
+ if 'in progress' in error.lower():
+ return (True, f"Still in progress: {error}")
+ return (True, f"Query result: {error}")
+
+ result = resp.result
+ tasks = result.get('tasks', [])
+
+ # Check for any failed tasks
+ def find_failures(task_list):
+ failures = []
+ for t in task_list:
+ if t.get('status') == 'fail':
+ failures.append(t.get('description', 'unknown'))
+ failures.extend(find_failures(t.get('sub_tasks', [])))
+ return failures
+
+ failures = find_failures(tasks)
+ if failures:
+ return (True, f"Found failures (may be expected): {failures}")
+
+ return (True, f"Baseline status OK, {len(tasks)} tasks")
+
+
+tr.Processes.Default.Streams.stdout = Testers.CustomJSONRPCResponse(validate_baseline_status)
+tr.StillRunningAfter = ts
+
+# ============================================================================
+# Test 3: Inject invalid ip_allow config (should fail)
+# ============================================================================
+tr = Test.AddTestRun("Inject invalid ip_allow config")
+tr.DelayStart = 2
+
+# Invalid ip_allow YAML - missing required fields
+invalid_ip_allow = """ip_allow:
+ - apply: invalid_value
+ action: not_a_valid_action
+"""
+
+# This should trigger a validation error in IpAllow
+# Note: The actual behavior depends on how strict the parser is
+tr.AddJsonRPCClientRequest(ts, Request.admin_config_reload(force=True))
+
+
+def validate_after_invalid_config(resp: Response):
+ '''Check reload after invalid config injection'''
+ if resp.is_error():
+ return (True, f"Reload error (may be expected): {resp.error_as_str()}")
+
+ result = resp.result
+ token = result.get('token', '')
+ errors = result.get('error', [])
+
+ if errors:
+ return (True, f"Reload reported errors: {errors}")
+
+ return (True, f"Reload started: {token}")
+
+
+tr.Processes.Default.Streams.stdout = Testers.CustomJSONRPCResponse(validate_after_invalid_config)
+tr.StillRunningAfter = ts
+
+# ============================================================================
+# Test 4: Add invalid SSL cert reference (subtask failure)
+# ============================================================================
+tr = Test.AddTestRun("Configure invalid SSL cert path")
+tr.DelayStart = 2
+
+# Add a bad cert reference to ssl_multicert.yaml
+# This should cause the SSL subtask to fail
+sslcertpath = ts.Disk.ssl_multicert_yaml.AbsPath
+tr.Disk.File(sslcertpath, id="ssl_multicert_yaml", typename="ats:config")
+tr.Disk.ssl_multicert_yaml.AddLines(
+ [
+ 'ssl_multicert:',
+ ' - dest_ip: "*"',
+ ' ssl_cert_name: server.pem',
+ ' ssl_key_name: server.key',
+ ' - dest_ip: 1.2.3.4',
+ ' ssl_cert_name: /nonexistent/bad.pem',
+ ' ssl_key_name: /nonexistent/bad.key',
+ ])
+
+tr.AddJsonRPCClientRequest(ts, Request.admin_config_reload(force=True))
+
+
+def validate_ssl_failure(resp: Response):
+ '''Check reload with bad SSL config'''
+ if resp.is_error():
+ return (True, f"SSL reload error: {resp.error_as_str()}")
+
+ result = resp.result
+ token = result.get('token', '')
+ return (True, f"SSL reload started: {token}")
+
+
+tr.Processes.Default.Streams.stdout = Testers.CustomJSONRPCResponse(validate_ssl_failure)
+tr.StillRunningAfter = ts
+
+# ============================================================================
+# Test 5: Check for failed subtasks after SSL reload
+# ============================================================================
+tr = Test.AddTestRun("Check for failed SSL subtasks")
+tr.DelayStart = 3
+tr.AddJsonRPCClientRequest(ts, Request.admin_config_reload())
+
+
+def validate_failed_subtasks(resp: Response):
+ '''Check if SSL subtasks show failure'''
+ if resp.is_error():
+ error = resp.error_as_str()
+ if 'in progress' in error.lower():
+ return (True, f"Still in progress: {error}")
+ return (True, f"Query: {error}")
+
+ result = resp.result
+ tasks = result.get('tasks', [])
+
+ def analyze_tasks(task_list, depth=0):
+ analysis = []
+ for t in task_list:
+ desc = t.get('description', 'unknown')
+ status = t.get('status', 'unknown')
+ logs = t.get('logs', [])
+
+ info = f"{' '*depth}{desc}: {status}"
+ if status == 'fail' and logs:
+ info += f" - {logs[0][:50]}..."
+
+ analysis.append(info)
+
+ # Recurse into subtasks
+ analysis.extend(analyze_tasks(t.get('sub_tasks', []), depth + 1))
+
+ return analysis
+
+ task_info = analyze_tasks(tasks)
+ return (True, f"Task analysis:\n" + "\n".join(task_info[:10]))
+
+
+tr.Processes.Default.Streams.stdout = Testers.CustomJSONRPCResponse(validate_failed_subtasks)
+tr.StillRunningAfter = ts
+
+# ============================================================================
+# Test 6: Verify parent status reflects subtask failure
+# ============================================================================
+tr = Test.AddTestRun("Verify status propagation from subtask to parent")
+tr.DelayStart = 1
+tr.AddJsonRPCClientRequest(ts, Request.admin_config_reload())
+
+
+def validate_status_propagation(resp: Response):
+ '''Verify failed subtask propagates to parent'''
+ if resp.is_error():
+ error = resp.error_as_str()
+ if 'in progress' in error.lower():
+ return (True, f"In progress: {error}")
+ return (True, f"Query: {error}")
+
+ result = resp.result
+ tasks = result.get('tasks', [])
+
+ def check_propagation(task_list):
+ """
+ For each task with subtasks, verify:
+ - If any subtask is 'fail', parent should be 'fail'
+ - If any subtask is 'in_progress', parent should be 'in_progress'
+ - If all subtasks are 'success', parent should be 'success'
+ """
+ issues = []
+ for t in task_list:
+ sub_tasks = t.get('sub_tasks', [])
+ if not sub_tasks:
+ continue
+
+ parent_status = t.get('status', '')
+ sub_statuses = [st.get('status', '') for st in sub_tasks]
+
+ if 'fail' in sub_statuses and parent_status != 'fail':
+ issues.append(f"{t.get('description')}: has failed subtask but parent is '{parent_status}'")
+
+ if 'in_progress' in sub_statuses and parent_status != 'in_progress':
+ issues.append(f"{t.get('description')}: has in_progress subtask but parent is '{parent_status}'")
+
+ # Recurse
+ issues.extend(check_propagation(sub_tasks))
+
+ return issues
+
+ issues = check_propagation(tasks)
+ if issues:
+ return (True, f"Propagation issues found: {issues}")
+
+ return (True, "Status propagation verified correctly")
+
+
+tr.Processes.Default.Streams.stdout = Testers.CustomJSONRPCResponse(validate_status_propagation)
+tr.StillRunningAfter = ts
+
+# ============================================================================
+# Test 7: Check task logs contain error details
+# ============================================================================
+tr = Test.AddTestRun("Check failed tasks have error logs")
+tr.DelayStart = 1
+tr.AddJsonRPCClientRequest(ts, Request.admin_config_reload())
+
+
+def validate_error_logs(resp: Response):
+ '''Verify failed tasks have descriptive logs'''
+ if resp.is_error():
+ return (True, f"Query: {resp.error_as_str()}")
+
+ result = resp.result
+ tasks = result.get('tasks', [])
+
+ def find_failed_with_logs(task_list):
+ results = []
+ for t in task_list:
+ if t.get('status') == 'fail':
+ logs = t.get('logs', [])
+ desc = t.get('description', 'unknown')
+ if logs:
+ results.append(f"{desc}: {logs}")
+ else:
+ results.append(f"{desc}: NO LOGS (should have error details)")
+
+ results.extend(find_failed_with_logs(t.get('sub_tasks', [])))
+ return results
+
+ failed_info = find_failed_with_logs(tasks)
+ if failed_info:
+ return (True, f"Failed tasks with logs: {failed_info}")
+
+ return (True, "No failed tasks found (baseline may have recovered)")
+
+
+tr.Processes.Default.Streams.stdout = Testers.CustomJSONRPCResponse(validate_error_logs)
+tr.StillRunningAfter = ts
+
+# ============================================================================
+# Test 8: Force reload to reset state
+# ============================================================================
+tr = Test.AddTestRun("Force reload to reset")
+tr.DelayStart = 2
+
+# Reset ssl_multicert.yaml to valid state
+sslcertpath = ts.Disk.ssl_multicert_yaml.AbsPath
+tr.Disk.File(sslcertpath, id="ssl_multicert_yaml", typename="ats:config")
+tr.Disk.ssl_multicert_yaml.AddLines(
+ [
+ 'ssl_multicert:',
+ ' - dest_ip: "*"',
+ ' ssl_cert_name: server.pem',
+ ' ssl_key_name: server.key',
+ ])
+
+tr.AddJsonRPCClientRequest(ts, Request.admin_config_reload(force=True))
+
+
+def validate_reset(resp: Response):
+ '''Reset to clean state'''
+ if resp.is_error():
+ return (True, f"Reset: {resp.error_as_str()}")
+
+ result = resp.result
+ token = result.get('token', '')
+ return (True, f"Reset reload started: {token}")
+
+
+tr.Processes.Default.Streams.stdout = Testers.CustomJSONRPCResponse(validate_reset)
+tr.StillRunningAfter = ts
+
+# ============================================================================
+# Test 9: Verify clean state after reset
+# ============================================================================
+tr = Test.AddTestRun("Verify clean state after reset")
+tr.DelayStart = 3
+tr.AddJsonRPCClientRequest(ts, Request.admin_config_reload())
+
+
+def validate_clean_state(resp: Response):
+ '''Verify we're back to clean state'''
+ if resp.is_error():
+ error = resp.error_as_str()
+ if 'in progress' in error.lower():
+ return (True, f"In progress: {error}")
+ return (True, f"Query: {error}")
+
+ result = resp.result
+ tasks = result.get('tasks', [])
+
+ # Count failures
+ def count_failures(task_list):
+ count = 0
+ for t in task_list:
+ if t.get('status') == 'fail':
+ count += 1
+ count += count_failures(t.get('sub_tasks', []))
+ return count
+
+ failures = count_failures(tasks)
+ if failures > 0:
+ return (True, f"Still have {failures} failed tasks (may need more time)")
+
+ return (True, "Clean state - no failures")
+
+
+tr.Processes.Default.Streams.stdout = Testers.CustomJSONRPCResponse(validate_clean_state)
+tr.StillRunningAfter = ts
+
+# ============================================================================
+# Test 10: Summary
+# ============================================================================
+tr = Test.AddTestRun("Final summary")
+tr.DelayStart = 1
+tr.AddJsonRPCClientRequest(ts, Request.admin_config_reload())
+
+
+def validate_summary(resp: Response):
+ '''Final summary of failure testing'''
+ if resp.is_error():
+ return (True, f"Final: {resp.error_as_str()}")
+
+ result = resp.result
+
+ summary = """
+ Config Reload Failure Testing Summary:
+ - Failed tasks: Detected when config validation fails
+ - Failed subtasks: SSL cert failures propagate to parent
+ - Status propagation: Parent status reflects worst subtask status
+ - Error logs: Failed tasks should include error details
+ """
+
+ return (True, f"Test complete. Token: {result.get('token', 'none')}")
+
+
+tr.Processes.Default.Streams.stdout = Testers.CustomJSONRPCResponse(validate_summary)
+tr.StillRunningAfter = ts
diff --git a/tests/gold_tests/jsonrpc/config_reload_full_smoke.test.py b/tests/gold_tests/jsonrpc/config_reload_full_smoke.test.py
new file mode 100644
index 0000000000..e1788b3a15
--- /dev/null
+++ b/tests/gold_tests/jsonrpc/config_reload_full_smoke.test.py
@@ -0,0 +1,165 @@
+'''
+Full reload smoke test.
+
+Verifies that ALL registered config handlers complete properly by:
+ Part A: Touching every registered config file, triggering a reload with a
+ named token, and verifying all deferred handlers reach a terminal
+ state (no in_progress after a delay).
+ Part B: Changing one record per module via traffic_ctl config set, waiting,
+ then verifying no terminal-state conflicts appear in diags.log.
+
+Registered configs at time of writing:
+ Files: ip_allow.yaml, parent.config, cache.config, hosting.config,
+ splitdns.config, logging.yaml, sni.yaml, ssl_multicert.yaml
+ Record-only: ssl_ticket_key (proxy.config.ssl.server.ticket_key.filename)
+
+The key assertion is that diags.log does NOT contain:
+ "ignoring transition from" — means two code paths disagree about task outcome
+'''
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+Test.Summary = 'Full reload smoke test: all config files + record triggers'
+Test.ContinueOnFail = True
+
+# --- Setup ---
+ts = Test.MakeATSProcess("ts", enable_cache=True)
+ts.Disk.records_config.update({
+ 'proxy.config.diags.debug.enabled': 1,
+ 'proxy.config.diags.debug.tags': 'rpc|config|reload',
+})
+
+# ============================================================================
+# Part A: File-based full reload
+#
+# ATS starts with valid config content (written via AddLines before start).
+# We then touch every file to bump mtime and trigger a reload — this exercises
+# the full parse path of each handler.
+# ============================================================================
+
+# Provide valid content for files whose handlers reject empty input.
+ts.Disk.ip_allow_yaml.AddLines([
+ 'ip_allow:',
+ '- apply: in',
+ ' ip_addrs: 0/0',
+ ' action: allow',
+ ' methods: ALL',
+])
+ts.Disk.logging_yaml.AddLines([
+ 'logging:',
+ ' formats:',
+ ' - name: smoke',
+ ' format: "%<cqtq>"',
+])
+ts.Disk.sni_yaml.AddLines([
+ 'sni:',
+ '- fqdn: "*.example.com"',
+ ' verify_client: NONE',
+])
+# parent.config, cache.config, hosting.config, splitdns.config,
+# ssl_multicert.yaml are fine empty — handlers accept empty/comment-only files.
+
+# All registered config files whose mtime we'll bump to trigger reload.
+files_to_touch = [
+ ts.Disk.ip_allow_yaml,
+ ts.Disk.parent_config,
+ ts.Disk.cache_config,
+ ts.Disk.hosting_config,
+ ts.Disk.splitdns_config,
+ ts.Disk.logging_yaml,
+ ts.Disk.sni_yaml,
+ ts.Disk.ssl_multicert_yaml,
+]
+touch_cmd = "touch " + " ".join([f.AbsRunTimePath for f in files_to_touch])
+# Modify records.yaml via traffic_ctl --cold to trigger a real records reload.
+records_cmd = 'traffic_ctl config set proxy.config.diags.debug.tags "rpc|config|reload|upd" --cold'
+
+# Test 1: Start ATS, wait for it to settle, update records.yaml on disk
+tr = Test.AddTestRun("Update records.yaml via --cold")
+tr.Processes.Default.StartBefore(ts)
+tr.Processes.Default.Command = f"sleep 3 && {records_cmd}"
+tr.Processes.Default.Env = ts.Env
+tr.Processes.Default.ReturnCode = 0
+tr.StillRunningAfter = ts
+
+# Test 2: Touch all other config files to bump mtime
+tr = Test.AddTestRun("Touch all registered config files")
+tr.Processes.Default.Command = touch_cmd
+tr.Processes.Default.ReturnCode = 0
+tr.StillRunningAfter = ts
+
+# Test 3: Reload with token — all handlers re-read from disk
+tr = Test.AddTestRun("Reload with token - show details")
+tr.Processes.Default.Command = "traffic_ctl config reload -t full_reload_smoke"
+tr.Processes.Default.Env = ts.Env
+tr.Processes.Default.ReturnCode = 0
+tr.StillRunningAfter = ts
+
+# Test 4: Query status after delay — all deferred handlers (e.g. logging) should have
+# reached a terminal state by now.
+tr = Test.AddTestRun("Verify no tasks stuck in progress after delay")
+tr.DelayStart = 15
+tr.Processes.Default.Command = "traffic_ctl config status -t full_reload_smoke"
+tr.Processes.Default.Env = ts.Env
+tr.Processes.Default.ReturnCode = 0
+tr.Processes.Default.Streams.stdout += Testers.ExcludesExpression("in_progress", "No task should remain in progress after 15s")
+tr.StillRunningAfter = ts
+
+# ============================================================================
+# Part B: Record-triggered reloads (tracing ENABLED — default)
+#
+# Change one record per module to exercise the RecordTriggeredReloadContinuation path.
+# With proxy.config.admin.reload.trace_record_triggers=1 (default), each
+# record-triggered reload creates a "rec-" parent task visible in status/history.
+# ============================================================================
+
+# One safe record per module:
+records_to_change = [
+ # (record_name, new_value) — pick values that won't break ATS
+ ("proxy.config.log.sampling_frequency", "2"), # logging
+ ("proxy.config.ssl.server.session_ticket.enable", "0"), # ssl_client_coordinator
+]
+
+for record_name, new_value in records_to_change:
+ tr = Test.AddTestRun(f"Set {record_name}={new_value}")
+ tr.DelayStart = 2
+ tr.Processes.Default.Command = f"traffic_ctl config set {record_name} {new_value}"
+ tr.Processes.Default.Env = ts.Env
+ tr.Processes.Default.ReturnCode = 0
+ tr.StillRunningAfter = ts
+
+# Wait for record-triggered reloads to complete
+tr = Test.AddTestRun("Wait for record-triggered reloads")
+tr.DelayStart = 10
+tr.Processes.Default.Command = "echo 'Waiting for record-triggered reloads to settle'"
+tr.Processes.Default.ReturnCode = 0
+tr.StillRunningAfter = ts
+
+# Final dump of all reload history
+tr = Test.AddTestRun("Fetch all reload history")
+tr.Processes.Default.Command = "traffic_ctl config status -c all"
+tr.Processes.Default.Env = ts.Env
+tr.Processes.Default.ReturnCode = 0
+tr.StillRunningAfter = ts
+
+# ============================================================================
+# Global assertions on diags.log
+# ============================================================================
+
+# No handler should have conflicting terminal state transitions.
+# This catches bugs where e.g. evaluate_config() calls fail() and then
+# change_configuration() calls complete() — the guard rejects the second call.
+ts.Disk.diags_log.Content = Testers.ExcludesExpression("ignoring transition from", "No handler should fight over terminal states")
diff --git a/tests/gold_tests/jsonrpc/config_reload_reserve_subtask.test.py b/tests/gold_tests/jsonrpc/config_reload_reserve_subtask.test.py
new file mode 100644
index 0000000000..d4b5b17c39
--- /dev/null
+++ b/tests/gold_tests/jsonrpc/config_reload_reserve_subtask.test.py
@@ -0,0 +1,134 @@
+'''
+Test that reserve_subtask correctly pre-registers subtasks during a reload.
+
+When records.yaml is changed alongside other config files, the "records"
+subtask completes first (records.yaml is always processed first in
+rereadConfig). This pushes the main task to SUCCESS before other
+file-based or record-triggered handlers have a chance to register their
+subtasks. reserve_subtask() must accept a SUCCESS parent and pull it back
+to IN_PROGRESS by adding a CREATED child.
+
+This test:
+ 1. Modifies records.yaml on disk (--cold) to change a trigger record so
+ that a record-triggered handler fires during the next reload.
+ 2. Touches additional config files so file-based handlers also fire.
+ 3. Triggers a reload with a named token.
+ 4. Verifies that traffic.out contains "Reserved subtask" messages — proving
+ reserve_subtask() succeeded despite the parent being SUCCESS.
+ 5. Verifies no "ignoring transition" warnings (no state conflicts).
+ 6. Verifies the reload reaches a terminal state with all subtasks tracked.
+'''
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+Test.Summary = 'Verify reserve_subtask pre-registers subtasks when records.yaml is first'
+Test.ContinueOnFail = True
+
+# --- Setup ---
+ts = Test.MakeATSProcess("ts", enable_cache=True)
+# Allow extra startup time — cache clearing can take ~10s in some environments.
+ts.StartupTimeout = 30
+ts.Disk.records_config.update(
+ {
+ 'proxy.config.diags.debug.enabled': 1,
+ 'proxy.config.diags.debug.tags': 'rpc|config|config.reload|filemanager',
+ })
+
+# Provide valid content for files whose handlers reject empty input.
+ts.Disk.ip_allow_yaml.AddLines([
+ 'ip_allow:',
+ '- apply: in',
+ ' ip_addrs: 0/0',
+ ' action: allow',
+ ' methods: ALL',
+])
+ts.Disk.logging_yaml.AddLines([
+ 'logging:',
+ ' formats:',
+ ' - name: reserve_test',
+ ' format: "%<cqtq>"',
+])
+ts.Disk.sni_yaml.AddLines([
+ 'sni:',
+ '- fqdn: "*.example.com"',
+ ' verify_client: NONE',
+])
+
+# Files to touch to trigger file-based handlers during reload.
+files_to_touch = [
+ ts.Disk.ip_allow_yaml,
+ ts.Disk.logging_yaml,
+ ts.Disk.sni_yaml,
+ ts.Disk.cache_config,
+]
+touch_cmd = "touch " + " ".join([f.AbsRunTimePath for f in files_to_touch])
+
+# ============================================================================
+# Test 1: Start ATS, let it settle, then modify records.yaml on disk
+# ============================================================================
+tr = Test.AddTestRun("Modify records.yaml via --cold to change a trigger record")
+tr.Processes.Default.StartBefore(ts)
+# Change debug tags — this touches records.yaml on disk so rereadConfig
+# detects it as changed. The --cold flag modifies the file without
+# notifying the running process (the reload will pick it up).
+tr.Processes.Default.Command = (
+ 'sleep 3 && traffic_ctl config set proxy.config.diags.debug.tags '
+ '"rpc|config|config.reload|filemanager|upd" --cold')
+tr.Processes.Default.Env = ts.Env
+tr.Processes.Default.ReturnCode = 0
+tr.StillRunningAfter = ts
+
+# ============================================================================
+# Test 2: Touch additional config files to bump mtime
+# ============================================================================
+tr = Test.AddTestRun("Touch config files to trigger file-based handlers")
+tr.Processes.Default.Command = touch_cmd
+tr.Processes.Default.ReturnCode = 0
+tr.StillRunningAfter = ts
+
+# ============================================================================
+# Test 3: Trigger reload with a named token
+# ============================================================================
+tr = Test.AddTestRun("Trigger reload with named token")
+tr.Processes.Default.Command = "traffic_ctl config reload -t reserve_subtask_test"
+tr.Processes.Default.Env = ts.Env
+tr.Processes.Default.ReturnCode = 0
+tr.StillRunningAfter = ts
+
+# ============================================================================
+# Test 4: Wait for all handlers to complete, then query status
+# ============================================================================
+tr = Test.AddTestRun("Verify reload completed — no tasks stuck in progress")
+tr.DelayStart = 15
+tr.Processes.Default.Command = "traffic_ctl config status -t reserve_subtask_test"
+tr.Processes.Default.Env = ts.Env
+tr.Processes.Default.ReturnCode = 0
+# No subtask should still be in_progress after 15s.
+tr.Processes.Default.Streams.stdout += Testers.ExcludesExpression(
+ "in_progress", "No task should remain in progress after 15s delay")
+tr.Processes.Default.Streams.stdout += Testers.ContainsExpression("success", "Final reload status must be success")
+tr.StillRunningAfter = ts
+
+# ============================================================================
+# Test 5: Verify no state-transition conflicts in traffic.out
+#
+# "ignoring transition from" means two code paths disagree about a task's
+# outcome. This must never happen.
+# ============================================================================
+ts.Disk.traffic_out.Content += Testers.ExcludesExpression(
+ "ignoring transition from", "No state-transition conflicts should appear in traffic.out")
+ts.Disk.traffic_out.Content += Testers.ContainsExpression(
+ "Reserved subtask", "reserve_subtask() must log pre-registration messages")
diff --git a/tests/gold_tests/jsonrpc/config_reload_rpc.test.py b/tests/gold_tests/jsonrpc/config_reload_rpc.test.py
new file mode 100644
index 0000000000..bf5f3265f6
--- /dev/null
+++ b/tests/gold_tests/jsonrpc/config_reload_rpc.test.py
@@ -0,0 +1,397 @@
+'''
+Test inline config reload functionality via unified admin_config_reload RPC method.
+
+Inline mode is triggered by passing the "configs" parameter.
+Tests the following features:
+1. Basic inline reload with single config
+2. Multiple configs in single request
+3. File-based vs inline mode detection
+4. Unknown config key error handling
+5. Invalid YAML content handling
+6. Reload while another is in progress
+7. Verify config is actually applied
+'''
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from jsonrpc import Request, Response
+
+Test.Summary = 'Test inline config reload via RPC'
+Test.ContinueOnFail = True
+
+ts = Test.MakeATSProcess('ts', dump_runroot=True)
+
+Test.testName = 'config_reload_rpc'
+
+# Initial configuration
+ts.Disk.records_config.update({
+ 'proxy.config.diags.debug.enabled': 1,
+ 'proxy.config.diags.debug.tags': 'rpc|config',
+})
+
+# ============================================================================
+# Test 1: File-based reload (no configs parameter)
+# ============================================================================
+tr = Test.AddTestRun("File-based reload without configs parameter")
+tr.Processes.Default.StartBefore(ts)
+tr.AddJsonRPCClientRequest(ts, Request.admin_config_reload())
+
+
+def validate_file_based(resp: Response):
+ '''Verify file-based reload works when configs is not provided'''
+ result = resp.result
+ token = result.get('token', '')
+ message = result.get('message', [])
+
+ if token:
+ return (True, f"File-based reload started: token={token}")
+
+ errors = result.get('errors', [])
+ if errors:
+ return (True, f"File-based reload response: {errors}")
+
+ return (True, f"Response: {result}")
+
+
+tr.Processes.Default.Streams.stdout = Testers.CustomJSONRPCResponse(validate_file_based)
+tr.StillRunningAfter = ts
+
+# ============================================================================
+# Test 2: Empty configs map (should trigger inline mode but process 0 configs)
+# ============================================================================
+tr = Test.AddTestRun("Empty configs map")
+tr.DelayStart = 2
+tr.AddJsonRPCClientRequest(ts, Request.admin_config_reload(configs={}))
+
+
+def validate_empty_configs(resp: Response):
+ '''Verify behavior with empty configs'''
+ result = resp.result
+
+ # Empty configs should succeed but with 0 changes
+ success = result.get('success', -1)
+ failed = result.get('failed', -1)
+
+ if success == 0 and failed == 0:
+ return (True, f"Empty configs handled: success={success}, failed={failed}")
+
+ # Or it might be an error
+ errors = result.get('errors', [])
+ if errors:
+ return (True, f"Empty configs rejected: {errors}")
+
+ return (True, f"Result: {result}")
+
+
+tr.Processes.Default.Streams.stdout = Testers.CustomJSONRPCResponse(validate_empty_configs)
+tr.StillRunningAfter = ts
+
+# ============================================================================
+# Test 3: Unknown config key (error code 6010)
+# ============================================================================
+tr = Test.AddTestRun("Unknown config key should error with code 6010")
+tr.DelayStart = 2
+tr.AddJsonRPCClientRequest(ts, Request.admin_config_reload(configs={"unknown_config_key": {"some": "data"}}))
+
+
+def validate_unknown_key(resp: Response):
+ '''Verify error for unknown config key - should return error code 6010'''
+ result = resp.result
+ errors = result.get('errors', [])
+
+ if not errors:
+ return (False, f"Expected error for unknown key, got: {result}")
+
+ error_str = str(errors)
+ if '6010' in error_str or 'not registered' in error_str:
+ return (True, f"Unknown key rejected with code 6010: {errors}")
+ return (False, f"Expected error 6010, got: {errors}")
+
+
+tr.Processes.Default.Streams.stdout = Testers.CustomJSONRPCResponse(validate_unknown_key)
+tr.StillRunningAfter = ts
+
+# ============================================================================
+# Test 3b: Unregistered config rejected (error code 6010)
+# Note: remap.config is not registered in ConfigRegistry
+# ============================================================================
+tr = Test.AddTestRun("Unregistered config should error with code 6010")
+tr.DelayStart = 1
+tr.AddJsonRPCClientRequest(ts, Request.admin_config_reload(configs={"remap.config": {"some": "data"}}))
+
+
+def validate_legacy_not_supported(resp: Response):
+ '''Verify unregistered config returns error code 6010'''
+ result = resp.result
+ errors = result.get('errors', [])
+
+ if not errors:
+ return (False, f"Expected rejection for unregistered config, got: {result}")
+
+ error_str = str(errors)
+ if '6010' in error_str or 'not registered' in error_str:
+ return (True, f"Unregistered config correctly rejected: {errors}")
+ return (False, f"Expected error 6010, got: {errors}")
+
+
+tr.Processes.Default.Streams.stdout = Testers.CustomJSONRPCResponse(validate_legacy_not_supported)
+tr.StillRunningAfter = ts
+
+# ============================================================================
+# Test 4: RPC-injected content rejected for FileOnly config (ip_allow)
+# ip_allow is registered with ConfigSource::FileOnly — RPC content must be rejected
+# ============================================================================
+tr = Test.AddTestRun("RPC-injected content rejected for FileOnly config (ip_allow)")
+tr.DelayStart = 2
+tr.AddJsonRPCClientRequest(
+ ts,
+ Request.admin_config_reload(
+ configs={"ip_allow": [{
+ "apply": "in",
+ "ip_addrs": "127.0.0.1",
+ "action": "allow",
+ "methods": ["GET", "HEAD"]
+ }]}))
+
+
+def validate_rpc_inject_rejected(resp: Response):
+ '''ip_allow is registered as FileOnly — RPC-injected content must be rejected with 6011'''
+ result = resp.result
+ errors = result.get('errors', [])
+
+ if not errors:
+ return (False, f"Expected rejection for FileOnly config, got: {result}")
+
+ error_str = str(errors)
+ if '6011' in error_str or 'does not support RPC' in error_str:
+ return (True, f"FileOnly config correctly rejected RPC injection: {errors}")
+ return (False, f"Expected error 6011, got: {errors}")
+
+
+tr.Processes.Default.Streams.stdout = Testers.CustomJSONRPCResponse(validate_rpc_inject_rejected)
+tr.StillRunningAfter = ts
+
+# ============================================================================
+# Test 5: Multiple configs in single request
+# ============================================================================
+tr = Test.AddTestRun("Multiple configs in single request")
+tr.DelayStart = 2
+tr.AddJsonRPCClientRequest(
+ ts,
+ Request.admin_config_reload(
+ configs={
+ "ip_allow": [{
+ "apply": "in",
+ "ip_addrs": "0.0.0.0/0",
+ "action": "allow"
+ }],
+ "sni": [{
+ "fqdn": "*.test.com",
+ "verify_client": "NONE"
+ }],
+ "records": {
+ "diags": {
+ "debug": {
+ "enabled": 1
+ }
+ }
+ }
+ }))
+
+
+def validate_multiple_configs(resp: Response):
+ '''All configs should be rejected — none support RPC content source at this stage'''
+ result = resp.result
+ errors = result.get('errors', [])
+
+ if not errors:
+ return (False, f"Expected rejections for all configs, got: {result}")
+
+ # Each config should produce an error (6010=not registered, 6011=RPC source not supported)
+ error_str = str(errors)
+ if '6010' in error_str or '6011' in error_str:
+ return (True, f"All configs rejected as expected: {len(errors)} errors")
+ return (False, f"Unexpected errors: {errors}")
+
+
+tr.Processes.Default.Streams.stdout = Testers.CustomJSONRPCResponse(validate_multiple_configs)
+tr.StillRunningAfter = ts
+
+# ============================================================================
+# Test 6: Reload while another is in progress
+# ============================================================================
+tr = Test.AddTestRun("First reload request")
+tr.DelayStart = 1
+tr.AddJsonRPCClientRequest(ts, Request.admin_config_reload())
+
+
+def validate_first_reload(resp: Response):
+ '''Start a regular reload'''
+ result = resp.result
+ token = result.get('token', '')
+ return (True, f"First reload started: token={token}")
+
+
+tr.Processes.Default.Streams.stdout = Testers.CustomJSONRPCResponse(validate_first_reload)
+tr.StillRunningAfter = ts
+
+# Immediately try inline reload
+tr = Test.AddTestRun("Inline reload while regular reload in progress")
+tr.DelayStart = 0 # No delay - immediately after
+tr.AddJsonRPCClientRequest(ts, Request.admin_config_reload(configs={"ip_allow": [{"apply": "in", "ip_addrs": "10.0.0.0/8"}]}))
+
+
+def validate_in_progress_rejection(resp: Response):
+ '''Should be rejected for RPC source not supported or reload in progress'''
+ result = resp.result
+ errors = result.get('errors', [])
+
+ if not errors:
+ return (False, f"Expected rejection, got: {result}")
+
+ error_str = str(errors)
+ # Either 6011 (RPC source not supported) or 6004 (reload in progress)
+ if '6011' in error_str or '6004' in error_str:
+ return (True, f"Correctly rejected: {errors}")
+ return (False, f"Unexpected error: {errors}")
+
+
+tr.Processes.Default.Streams.stdout = Testers.CustomJSONRPCResponse(validate_in_progress_rejection)
+tr.StillRunningAfter = ts
+
+# ============================================================================
+# Test 7: Verify token is returned with inline- prefix
+# ============================================================================
+tr = Test.AddTestRun("Verify inline token prefix")
+tr.DelayStart = 3 # Wait for previous reloads to complete
+tr.AddJsonRPCClientRequest(ts, Request.admin_config_reload(configs={"unknown_for_token_test": {"data": "value"}}))
+
+
+def validate_inline_token(resp: Response):
+ '''Verify token has inline- prefix'''
+ result = resp.result
+ token = result.get('token', '')
+
+ if token and token.startswith('inline-'):
+ return (True, f"Token has correct prefix: {token}")
+
+ if not token:
+ # Check if there's an error (which is fine)
+ errors = result.get('errors', [])
+ if errors:
+ return (True, f"No token (error case): {errors}")
+
+ return (True, f"Token result: {token}")
+
+
+tr.Processes.Default.Streams.stdout = Testers.CustomJSONRPCResponse(validate_inline_token)
+tr.StillRunningAfter = ts
+
+# ============================================================================
+# Test 8: Nested YAML structure (records.diags.debug)
+# ============================================================================
+tr = Test.AddTestRun("Nested YAML structure")
+tr.DelayStart = 2
+tr.AddJsonRPCClientRequest(
+ ts,
+ Request.admin_config_reload(
+ configs={"records": {
+ "diags": {
+ "debug": {
+ "enabled": 1,
+ "tags": "http|rpc|test"
+ }
+ },
+ "http": {
+ "cache": {
+ "http": 1
+ }
+ }
+ }}))
+
+
+def validate_nested_yaml(resp: Response):
+ '''Verify nested YAML handling'''
+ result = resp.result
+ success = result.get('success', 0)
+ failed = result.get('failed', 0)
+ errors = result.get('errors', [])
+
+ return (True, f"Nested YAML: success={success}, failed={failed}, errors={errors}")
+
+
+tr.Processes.Default.Streams.stdout = Testers.CustomJSONRPCResponse(validate_nested_yaml)
+tr.StillRunningAfter = ts
+
+# ============================================================================
+# Test 9: Query status after inline reload
+# ============================================================================
+tr = Test.AddTestRun("Query status after inline reload")
+tr.DelayStart = 2
+tr.AddJsonRPCClientRequest(ts, Request.get_reload_config_status())
+
+
+def validate_status_after_inline(resp: Response):
+ '''Check status includes inline reload info'''
+ if resp.is_error():
+ return (True, f"Status query error (may be expected): {resp.error_as_str()}")
+
+ result = resp.result
+ tasks = result.get('tasks', [])
+
+ if tasks:
+ # Check if any task has inline- prefix
+ for task in tasks:
+ token = task.get('token', '')
... 867 lines suppressed ...