Repository navigation
mgr/cephadm: normalize inventory and host-cache keys at load time to fix upgrade regression - #70346
Conversation
There was a problem hiding this comment.
Pull request overview
Normalizes cephadm hostname handling to address upgrade-time mismatches between HostSpec and persisted inventory/cache keys.
Changes:
- Normalizes loaded inventory, host-cache, and offline-host keys.
- Makes host operations and placement patterns case-insensitive.
- Adds hostname normalization tests.
Reviewed changes
Copilot reviewed 5 out of 5 changed files in this pull request and generated 4 comments.
Show a summary per file
| File | Description |
|---|---|
src/python-common/ceph/deployment/service_spec.py |
Normalizes fnmatch host patterns. |
src/pybind/mgr/cephadm/inventory.py |
Normalizes inventory and cache keys during loading. |
src/pybind/mgr/cephadm/module.py |
Normalizes host command inputs. |
src/pybind/mgr/cephadm/ssh.py |
Stores offline hostnames in lowercase. |
src/pybind/mgr/cephadm/tests/test_facts.py |
Adds case-normalization tests. |
| host)) | ||
| self.mgr.set_store(k, None) | ||
| try: | ||
| host = host.lower() |
There was a problem hiding this comment.
This PR only normalizes inventory/host-cache keys needed for hostname resolution. Migrating device-cache keys is outside the scope of this fix and not required for the reported regression.
| else: | ||
| osds_to_zap: List[str] = [] | ||
| if hostname not in list(self.inventory.keys()): | ||
| if hostname.lower() not in list(self.inventory.keys()): |
There was a problem hiding this comment.
The hostname is normalized where it is used for inventory lookups. Canonicalizing the input throughout this method would broaden the scope of this fix and is not required for the reported regression.
| def test_inventory_load_normalizes_keys(cephadm_module: CephadmOrchestrator): | ||
| """Verify that inventory load normalizes uppercase keys to lowercase.""" | ||
| inv = cephadm_module.inventory | ||
| inv._inventory = {} | ||
| raw_data = { |
There was a problem hiding this comment.
The test is intended to verify the hostname normalization logic in isolation. Reinitializing the full inventory would add unnecessary setup without increasing coverage for the behavior being validated.
| def test_host_had_daemon_refresh_hostname_case(cephadm_module: CephadmOrchestrator): | ||
| """With load-time normalization, cache keys are always lowercase.""" | ||
| cache = cephadm_module.cache | ||
| cache.daemons = {'ceph-node-00': {}} | ||
| cache.last_daemon_update = { |
There was a problem hiding this comment.
This test verifies the lookup behavior after normalization. Migration of persisted cache entries is covered separately, so reloading the full host cache is unnecessary here.
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 5 out of 5 changed files in this pull request and generated 1 comment.
Comments suppressed due to low confidence (4)
src/pybind/mgr/cephadm/inventory.py:104
- Case-folding can collapse two persisted entries (for example,
HOST1andhost1) onto the same key, and this assignment silently keeps whichever JSON entry is iterated last. Older versions allowed case-distinct inventory keys, so this migration can permanently discard one entry's address, labels, or status when it immediately saves. Detect collisions and merge them deterministically or stop with a diagnostic instead of overwriting.
self._inventory[normalized_key] = v
src/pybind/mgr/cephadm/inventory.py:841
- Two persisted cache records whose names differ only by case now target the same in-memory dictionaries. Each record resets and repopulates those dictionaries, so iteration order decides which daemons, devices, scheduled actions, and timestamps survive; the uppercase branch can also overwrite an existing lowercase record. Detect this collision and apply an explicit merge/preference policy before loading or migrating either record.
original_host = host
host = host.lower()
src/pybind/mgr/cephadm/inventory.py:897
- The migration deletes the only persisted source record and its device chunks before writing the normalized replacement. If
save_host()fails, the broad exception handler only logs the failure and the cache data is permanently gone. Write the normalized record first, then remove the old keys so a failed migration remains retryable.
self.mgr.set_store(k, None)
for dk, _dv in self.mgr.get_store_prefix(
HOST_CACHE_PREFIX + original_host + '.devices.').items():
self.mgr.set_store(dk, None)
self.save_host(host)
src/pybind/mgr/cephadm/tests/test_facts.py:54
- This setup stores a lowercase key, so it never enters the uppercase-key migration branch described by the test. Moreover,
load()intentionally ignores persistedlast_daemon_update, and the persisted daemon map is empty, sohost_had_daemon_refresh()is false and the assertion on line 54 fails. Store an uppercase key and assert the actual in-memory and persisted key migration instead.
cephadm_module.set_store(HOST_CACHE_PREFIX + 'ceph-node-00', host_data)
cache.load()
assert cache.host_had_daemon_refresh('ceph-node-00') is True
| from ceph.utils import datetime_now | ||
|
|
There was a problem hiding this comment.
Fixed in a later commit. The unused import has been removed.
| normalized_key = k.lower() | ||
| if normalized_key != k or v.get('hostname', '') != normalized_key: | ||
| needs_save = True | ||
| if 'hostname' not in v: | ||
| v['hostname'] = k | ||
| v['hostname'] = normalized_key | ||
| else: | ||
| v['hostname'] = v['hostname'].lower() | ||
| self._inventory[normalized_key] = v |
There was a problem hiding this comment.
This PR intentionally limits migration to the inventory, host cache, and placement data required for the reported regression. Migrating other host-keyed caches would broaden the scope without addressing this issue.
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 5 out of 5 changed files in this pull request and generated 2 comments.
Comments suppressed due to low confidence (2)
src/pybind/mgr/cephadm/inventory.py:841
- The upgrade remains broken for agent-enabled clusters.
HostCachenow exposes only the lowercase host, butAgentCache.load()still loads persistedagent.<UPPERCASE>entries under uppercase keys, while an already-deployed agent also reports the uppercase host from its old config.check_request_fields()then either rejects that host against lowercasecache.get_hosts()or cannot find its keyring. Normalize/migrate AgentCache keys and normalize the incoming agent hostname at the same boundary.
original_host = host
host = host.lower()
src/pybind/mgr/cephadm/inventory.py:1687
- This case-insensitive membership check keeps a legacy uppercase node-proxy record, but
self.data[host]below still stores it under that uppercase key. Since_resolve_hosts()performs exact lookup, querying with the newly normalized inventory hostname reports that no node-proxy data exists. Normalize and migrate the node-proxy data key (and the correspondingoob/keyringsentries) rather than only changing the membership test.
if host not in self.mgr.inventory:
| for k, v in raw_inventory.items(): | ||
| normalized_key = k.lower() | ||
| if normalized_key != k or v.get('hostname', '') != normalized_key: | ||
| needs_save = True | ||
| if 'hostname' not in v: |
There was a problem hiding this comment.
Considered this scenario, but the fix intentionally preserves the existing migration behavior and focuses on normalizing persisted hostnames for the reported regression. Collision handling is outside the scope of this change.
| original_host = host | ||
| host = host.lower() |
There was a problem hiding this comment.
Fixed in a later update. The original hostname is preserved for CRUSH operations, while the normalized hostname is used only for inventory lookups.
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 7 out of 7 changed files in this pull request and generated 1 comment.
Comments suppressed due to low confidence (2)
src/pybind/mgr/cephadm/inventory.py:104
- Normalizing directly into this dict silently drops a persisted host when two legacy keys differ only by case (for example,
NODE1andnode1), which the pre-normalization model allowed. The surviving address, labels, and status depend on iteration order, andsave()then permanently removes the other record. Detect this collision and either reconcile it deterministically or stop the migration with an actionable error instead of overwriting it.
self._inventory[normalized_key] = v
src/pybind/mgr/cephadm/inventory.py:841
- This has the same collision problem for host-cache records: if both
host.NODE1andhost.node1exist, each is loaded into the same in-memory keys, and the migration may overwrite the canonical persisted entry with whichever snapshot is processed last. That can lose scheduled actions, daemon metadata, or device state. Handle duplicate normalized cache keys explicitly before rewriting/deleting records.
original_host = host
host = host.lower()
| f'Normalizing host_pattern for {spec.service_name()} ' | ||
| f'to lowercase: \'{stored_pattern}\' -> \'{normalized}\'' | ||
| ) | ||
| self.mgr.spec_store.save(spec, update_create=False) |
There was a problem hiding this comment.
Fixed in a later update. The migration now updates the persisted host_pattern directly using mgr.set_store() instead of spec_store.save().
1e942e9 to
e388e6c
Compare
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 7 out of 7 changed files in this pull request and generated no new comments.
Comments suppressed due to low confidence (4)
src/pybind/mgr/cephadm/inventory.py:144
- Making inventory membership case-insensitive also changes
AgentCache.load()at inventory.py:1902-1921: an existingagent.UPPERCASErecord now passes the membership check but is still loaded under the uppercase key. Agent callers indexagent_ports,agent_keys, counters, and config dependencies by normalized hostnames, so the persisted agent state remains invisible after this upgrade. Normalize and migrateagent.*records at load time as well.
host = host.lower()
return host in self._inventory or host in itertools.chain.from_iterable(self._all_known_names.values())
src/pybind/mgr/cephadm/inventory.py:1687
- This now accepts a persisted uppercase node-proxy key because inventory membership is case-insensitive, but line 1698 still stores the data under that uppercase key and
_resolve_hosts()performs exact lookups. After inventory normalization, querying the displayed lowercase hostname therefore returns “no node-proxy data,” while all-host reports retain the stale uppercase name. Normalize/migrate the node-proxy data key here, together with the correspondingoobandkeyringskeys.
if host not in self.mgr.inventory:
src/pybind/mgr/cephadm/inventory.py:104
- Lowercasing can collapse two persisted entries such as
HOST1andhost1; this assignment silently keeps whichever JSON entry appears last and thensave()permanently discards the other host's address, labels, and status. Since older versions treated these keys as distinct, detect this collision and either merge it deterministically or stop with an actionable migration error instead of losing inventory data.
self._inventory[normalized_key] = v
src/pybind/mgr/cephadm/inventory.py:894
- If both
host.HOST1andhost.host1exist, this migration can overwrite the normalized KV record with the uppercase record before the snapshot's lowercase entry is processed. Iteration order then determines which daemons, devices, scheduled actions, and timestamps survive, and persisted state can disagree with the final in-memory state. Detect the normalized-key collision and merge or select records explicitly before saving and deleting either key.
if original_host != host:
self.save_host(host)
self.mgr.set_store(k, None)
e388e6c to
5fad840
Compare
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 7 out of 7 changed files in this pull request and generated 1 comment.
Comments suppressed due to low confidence (3)
src/pybind/mgr/cephadm/inventory.py:104
- This assignment silently collapses inventory entries that differ only by case. That duplicate state can be produced during the affected upgrade: a normalized
HostSpecmay be added under the lowercase key while the pre-existing inventory entry is still uppercase. Whichever JSON entry is visited last then wins, potentially dropping the other entry's address, labels, status, or OOB data. Detect normalized-key collisions and reconcile them explicitly (or stop with a clear migration error) instead of overwriting one record.
self._inventory[normalized_key] = v
src/pybind/mgr/cephadm/inventory.py:897
- This migrates only
host.<name>records; persistedagent.<UPPERCASE>records are still loaded under uppercase keys byAgentCache.load()(lines 1902-1921). After inventory and HostCache keys become lowercase, agent lookups use those lowercase hostnames, so saved keyrings/ports are not found and existing agents may be rejected or unnecessarily redeployed. Apply the same key normalization and one-time persistence/deletion to AgentCache records.
if original_host != host:
self.save_host(host)
self.mgr.set_store(k, None)
for dk, _dv in self.mgr.get_store_prefix(
HOST_CACHE_PREFIX + original_host + '.devices.').items():
self.mgr.set_store(dk, None)
src/pybind/mgr/cephadm/inventory.py:1687
- With the new case-insensitive
Inventory.__contains__, an oldnode_proxy/data/UPPERCASErecord now passes this check and is retained inself.dataunder its uppercase key._resolve_hosts()later performs an exact lookup (line 1729), so requests using the normalized lowercase hostname report that no node-proxy data exists. Normalize and migrate the data key here, along with the matching OOB/keyring keys, rather than only accepting it as an inventory member.
if host not in self.mgr.inventory:
| original_host = host | ||
| host = host.lower() |
There was a problem hiding this comment.
the fix intentionally targets normalization of inventory and host-cache keys required for the reported regression. Normalizing persisted DaemonDescription.hostname would broaden the scope of this change
5fad840 to
09d21cd
Compare
|
Addressed the review by using normalize_hostname() consistently, adding deterministic collision handling for Inventory and HostCache to avoid data loss, and extending hostname canonicalization to AgentCache and NodeProxy persisted state. Collision merges emit warnings while preserving data |
09d21cd to
3435ac7
Compare
d21a277 to
fbf029d
Compare
| self.scheduled_daemon_actions[host] = j.get('scheduled_daemon_actions', {}) | ||
| self.metadata_up_to_date[host] = j.get('metadata_up_to_date', False) | ||
|
|
||
| if original_host != host: |
There was a problem hiding this comment.
This should be based on a flag like needs_save = False that gets set for the following cases:
if original_host != host:
needs_save = True # case migrate
if host_already_in_cache:
needs_save = True # merged into existing entry
This avoid the following scenario wrt ordering of the host load:
Order: HOST1 then host1
Load HOST1
original_host="HOST1", host="host1" -- save host1, delete HOST1
first-time load (not collision yet)
Load host1
original_host="host1", host="host1" -- no save
is_collision=True -- merges into memory
merged result not written
There was a problem hiding this comment.
Good catch , the merged result wasn't being persisted when original_host == host (e.g., loading host1 after HOST1 already normalized it). Fixed with a needs_save flag that covers both case-migration and collision-merge scenarios. Will push as a new commit (no force push).
| logger.warning( | ||
| f'Inventory: case-collision detected for hostname ' | ||
| f'{normalized_key!r}: found keys {original_keys}. ' | ||
| f'Merging labels and keeping richest record.' |
There was a problem hiding this comment.
Is the following precedence of merge intentional?
osdspec_previews - first wins;
scheduled_daemon_actions, metadata_up_to_date - last wins
There was a problem hiding this comment.
Yes, intentional. For osdspec_previews, we initialize it only on first load since merging preview dicts is complex and the first record (the one that was already saved under the normalized key) is the most authoritative. For scheduled_daemon_actions and metadata_up_to_date, last-wins is fine because they're simple scalars that get refreshed frequently anyway keeping the latest value is more useful than the first. The inconsistency only matters during a rare collision scenario and both records should have near-identical data in practice.
adk3798
left a comment
There was a problem hiding this comment.
I want to say this should all work as intended. A couple general points
I see a lot of places where we're changing the hostname to lowercase for specific commands e.g. host removal, updating a label, checking for presence (which is just a call to __contains__) etc. Since most (if not all, I didn't check) of these end up going through some Inventory or HostCache function to actually save the information at the end, is it possible to just have those classes handle the normalization of the hostname and leave the other functions as is? Doing it for individual functions makes it a lot easier to forget to do the normalization. If it's handled always by the classes we use to store information it would be easier to manage. The changes in ssh.py I wonder if we'd actually need generally if we've migrated all the hostnames when loading the host cache and inventory, but not 100% sure on that.
If we can't remove all those cases from the individual locations, is it possible to have all the cases where we change to lowercase go through that normalize_hostname function being used in inventory.py? Right now it's identical to just running lower on the string, but if we ever did anything else in terms of hostname normalization it would be nice to just have to change that function and not worry about modifying a bunch of other spots in the cephadm module.
Last point is we just need to make sure to squash the fixup commits before merging this, but I think you're leaving it as multiple commits right now for reviewers so it's fine until we think this is ready
Thanks Adam, those were good suggestions. I updated the implementation to centralize hostname normalization as much as possible. Inventory was already normalizing internally, and I've now updated HostCache to normalize hostnames at the entry points of its public APIs as well, so callers no longer need to remember to normalize before using it. I also replaced the remaining hostname .lower() call sites with normalize_hostname() for consistency. The only remaining .lower() calls are for non-hostname strings (for example status checks), where hostname normalization isn't applicable. I revisited the ssh.py changes as well. The remaining normalization there is only for interactions with plain data structures like offline_hosts, which don't perform normalization themselves. I'll squash the fixup commits before the PR is ready to merge. |
Normalize persisted hostnames when loading the inventory and host cache so existing clusters continue to work after hostname normalization changes. Centralize hostname normalization in the inventory/cache layer and replace ad-hoc lowercase conversions with normalize_hostname() where appropriate. This keeps hostname handling consistent while avoiding duplicate normalization in higher-level callers. Fixes: https://tracker.ceph.com/issues/78426 Signed-off-by: Shubha Jain <[email protected]>
42d890b to
51c9737
Compare
Retain the original hostname for CRUSH removal operations so the commands continue to match existing CRUSH bucket names after hostname normalization. Also normalize DaemonDescription.hostname when loading the persisted host cache to ensure scheduler hostname comparisons remain consistent with normalized inventory and HostCache entries. Fixes: https://tracker.ceph.com/issues/78426 Signed-off-by: Shubha Jain <[email protected]>
|
Could this be backported to umbrella? The umbrella branch carries the hostname normalization of #66820 (python-common/hostspec) but not this PR, so v21.2.0 and v21.3.0 only have half of it: On a fresh v21.2.0 cluster deployed with cephadm on hosts whose hostnames are uppercase (CI121, CI122, CI123), every daemon reports its uppercase host and the cluster never reaches HEALTH_OK: The tracker issue (https://tracker.ceph.com/issues/78426) was resolved without a Backport field, hence this comment. We deploy Ceph 21 with cephadm in SEAPATH (LF Energy), and some substations name their hosts in uppercase. |
Thanks for pointing this out. I'll update the tracker with the Umbrella backport and Pending Backport status, and follow up on the backport PR. |
|
Backport PR: #74499 |
Problem
PR #66820 introduced normalize_hostname() in HostSpec.init() which lowercases hostnames at the model layer. However, the persistent storage keys in Inventory._inventory and HostCache (daemons, networks, last_daemon_update, etc.) remain uppercase for clusters that were deployed with uppercase hostnames prior to the upgrade.
This creates a key mismatch: HostSpec.hostname returns "multi80-site1" but all cache dicts are keyed by "MULTI80-SITE1". As a result:
get_schedulable_hosts() returns an empty list (no hosts pass host_had_daemon_refresh())
All service placements fail: "Failed to apply 12 service(s)"
Host management commands fail: "host multi80-site3 does not exist"
Fixes: https://tracker.ceph.com/issues/78426
Signed-off-by: Shubha Jain [[email protected]]
Solution
This PR fixes hostname normalization regressions observed after upgrading clusters that originally used uppercase hostnames.
The changes:
Testing confirmed that ceph orch commands work correctly after upgrade, and redeploying an OSD continues to use the existing CRUSH host bucket. Remaining uppercase hostnames in commands such as ceph mon stat and ceph osd tree are cosmetic and do not affect service placement or CRUSH behavior.
Contribution Guidelines
To sign and title your commits, please refer to Submitting Patches to Ceph.
If you are submitting a fix for a stable branch (e.g. "quincy"), please refer to Submitting Patches to Ceph - Backports for the proper workflow.
When filling out the below checklist, you may click boxes directly in the GitHub web UI. When entering or editing the entire PR message in the GitHub web UI editor, you may also select a checklist item by adding an
xbetween the brackets:[x]. Spaces and capitalization matter when checking off items this way.Checklist
Show available Jenkins commands
jenkins test classic perfJenkins Job | Jenkins Job Definitionjenkins test crimson perfJenkins Job | Jenkins Job Definitionjenkins test signedJenkins Job | Jenkins Job Definitionjenkins test make checkJenkins Job | Jenkins Job Definitionjenkins test make check arm64Jenkins Job | Jenkins Job Definitionjenkins test submodulesJenkins Job | Jenkins Job Definitionjenkins test dashboardJenkins Job | Jenkins Job Definitionjenkins test dashboard cephadmJenkins Job | Jenkins Job Definitionjenkins test apiJenkins Job | Jenkins Job Definitionjenkins test docsReadTheDocs | Github Workflow Definitionjenkins test ceph-volume allJenkins Jobs | Jenkins Jobs Definitionjenkins test windowsJenkins Job | Jenkins Job Definitionjenkins test rook e2eJenkins Job | Jenkins Job DefinitionYou must only issue one Jenkins command per-comment. Jenkins does not understand
comments with more than one command.