Repository navigation
Add DRBD helpers #11
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Wescoeur
wants to merge
3
commits into
ran-json-rpc-server
Choose a base branch
from
ran-rpc-module-drbd
base: ran-json-rpc-server
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Add DRBD helpers #11
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Empty file.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,234 @@ | ||
| # Copyright (C) 2026 Vates SAS | ||
| # | ||
| # This program is free software: you can redistribute it and/or modify | ||
| # it under the terms of the GNU General Public License as published by | ||
| # the Free Software Foundation, either version 3 of the License, or | ||
| # (at your option) any later version. | ||
| # This program is distributed in the hope that it will be useful, | ||
| # but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
| # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
| # GNU General Public License for more details. | ||
| # | ||
| # You should have received a copy of the GNU General Public License | ||
| # along with this program. If not, see <https://www.gnu.org/licenses/>. | ||
|
|
||
| import contextlib | ||
| from dataclasses import dataclass | ||
| import json | ||
| from pathlib import Path | ||
| import re | ||
|
|
||
| import xcp_storage.log as log | ||
| from xcp_storage.utils.process import ( | ||
| get_process_cmdline, | ||
| run_command, | ||
| ) | ||
|
|
||
| from xcp_storage.typing import ( | ||
| Any, | ||
| Dict, | ||
| Final, | ||
| Iterator, | ||
| List, | ||
| ) | ||
|
|
||
| # ============================================================================== | ||
|
|
||
| logger = log.get_logger() # Use default logger. | ||
|
|
||
| # ------------------------------------------------------------------------------ | ||
|
|
||
| DRBD_BY_RES_PATH: Final = "/dev/drbd/by-res/" | ||
|
|
||
| DRBD_PORT_RANGE: Final = (7000, 8000) | ||
|
|
||
| # ------------------------------------------------------------------------------ | ||
|
|
||
| _EXEC_PATH_DRBDSETUP: Final = "/usr/sbin/drbdsetup" | ||
|
|
||
| _REGEX_DRBD_OPENER_LINE: Final = re.compile(r"(.*)\s+(\d+)\s+(\d+)") | ||
|
|
||
| # Characters allowed in a resource name: ASCII only, and neither a path separator nor a leading `-` or `.`. | ||
| _REGEX_DRBD_RESOURCE_NAME: Final = re.compile(r"\w[\w.-]*", re.ASCII) | ||
|
|
||
| # ------------------------------------------------------------------------------ | ||
|
|
||
| # Because this module can be used by external layers and RPC, we must have checkers | ||
| # to prevent code injection. | ||
|
|
||
| def _check_drbd_resource_name(resource_name: str) -> None: | ||
| if not isinstance(resource_name, str): | ||
| raise ValueError(f"Not a DRBD resource name: `{resource_name}`.") | ||
| if not _REGEX_DRBD_RESOURCE_NAME.fullmatch(resource_name): | ||
| raise ValueError(f"Invalid DRBD resource name: `{resource_name}`.") | ||
|
|
||
| def _check_drbd_volume_number(volume_number: int) -> None: | ||
| if not isinstance(volume_number, int) or isinstance(volume_number, bool): | ||
| raise ValueError(f"Not a DRBD volume number: `{volume_number}`.") | ||
| if volume_number < 0: | ||
| raise ValueError(f"Invalid DRBD volume number: `{volume_number}`.") | ||
|
|
||
| # ------------------------------------------------------------------------------ | ||
|
|
||
| @contextlib.contextmanager | ||
| def _handle_drbd_json_error() -> Iterator[None]: | ||
| """ | ||
| Log instead of raising an error while reading the JSON status of DRBD. | ||
|
|
||
| The log message suggests that the JSON format may have changed BUT it's also logged for valid states that | ||
| don't have the expected keys or items, like a resource without connection or even a connection without path. | ||
| """ | ||
| try: | ||
| yield | ||
| except KeyError as e: | ||
| logger.exception( | ||
| "The key `%s` could not be found in the DRBD configuration. The JSON format may have changed.", e | ||
| ) | ||
| except Exception as e: | ||
| logger.exception("Failed to parse DRBD configuration: `%s`. The JSON format may have changed.", e) | ||
|
|
||
| def _get_drbd_status(resource_name: str) -> Dict[str, Any]: | ||
| try: | ||
| stdout, stderr, ret_code = run_command([ | ||
| _EXEC_PATH_DRBDSETUP, "status", resource_name, "--json" | ||
| ], simple=False) | ||
| if ret_code != 0: | ||
| logger.warning( | ||
| "Failed to get DRBD status of resource `%s`: `%s` (exit code %d).", | ||
| resource_name, stderr.strip(), ret_code | ||
| ) | ||
| return {} | ||
| except Exception as e: | ||
| logger.error("Failed to get DRBD status of resource `%s`: `%s`.", resource_name, e) | ||
| return {} | ||
|
|
||
| try: | ||
| status = json.loads(stdout) | ||
| except Exception as e: | ||
| logger.error("Failed to read DRBD status of resource `%s` as JSON: `%s`.", resource_name, e) | ||
| return {} | ||
|
|
||
| with _handle_drbd_json_error(): | ||
| return status[0] | ||
| return {} | ||
|
|
||
| # ------------------------------------------------------------------------------ | ||
|
|
||
| @dataclass(frozen=True) | ||
| class DrbdOpener: | ||
| pid: int | ||
| process_name: str | ||
| cmdline: List[str] | ||
| # The duration is expressed in milliseconds. | ||
| open_duration: int | ||
|
|
||
| # ------------------------------------------------------------------------------ | ||
|
|
||
| class Drbd: | ||
| @staticmethod | ||
| def build_path(resource_name: str, volume_number: int) -> str: | ||
| _check_drbd_resource_name(resource_name) | ||
| _check_drbd_volume_number(volume_number) | ||
| return f"{DRBD_BY_RES_PATH}{resource_name}/{volume_number}" | ||
|
|
||
| @staticmethod | ||
| def get_name_from_path(path: str) -> str: | ||
| # Assume that we have a path like this: | ||
| # - "/dev/drbd/by-res/<NAME>/0" | ||
| # - "../<NAME>/0" | ||
| if path.startswith(DRBD_BY_RES_PATH): | ||
| prefix_len = len(DRBD_BY_RES_PATH) | ||
| elif path.startswith("../"): | ||
| prefix_len = 3 | ||
| else: | ||
| return "" | ||
|
|
||
| res_name_end = path.find("/", prefix_len) | ||
| if res_name_end == -1: | ||
| return "" | ||
|
|
||
| resource_name = path[prefix_len:res_name_end] | ||
| if _REGEX_DRBD_RESOURCE_NAME.fullmatch(resource_name) and path[res_name_end + 1:].isdecimal(): | ||
| return resource_name | ||
| return "" | ||
|
|
||
| @staticmethod | ||
| def get_connection_address(resource_name: str, node_name: str) -> str: | ||
| _check_drbd_resource_name(resource_name) | ||
| status = _get_drbd_status(resource_name) | ||
| if not status: | ||
| return "" | ||
|
|
||
| with _handle_drbd_json_error(): | ||
| for connection in status["connections"]: | ||
| if connection["name"] == node_name: | ||
| return connection["paths"][0]["remote_host"]["address"] | ||
| return "" | ||
|
|
||
| @staticmethod | ||
| def get_primary_address(resource_name: str) -> str: | ||
| _check_drbd_resource_name(resource_name) | ||
| status = _get_drbd_status(resource_name) | ||
| if not status: | ||
| return "" | ||
|
|
||
| with _handle_drbd_json_error(): | ||
| if status["role"] == "Primary": | ||
| return status["connections"][0]["paths"][0]["this_host"]["address"] | ||
|
|
||
| for connection in status["connections"]: | ||
| if connection["peer-role"] == "Primary": | ||
| return connection["paths"][0]["remote_host"]["address"] | ||
|
|
||
| return "" | ||
|
|
||
| @staticmethod | ||
| def get_local_openers(resource_name: str, volume_number: int) -> List[DrbdOpener]: | ||
| _check_drbd_resource_name(resource_name) | ||
| _check_drbd_volume_number(volume_number) | ||
|
|
||
| path = Path(f"/sys/kernel/debug/drbd/resources/{resource_name}/volumes/{volume_number}/openers") | ||
| try: | ||
| lines = path.read_text().splitlines() | ||
| except Exception as e: | ||
| # The resource is probably available not on this node. | ||
| logger.info("Unable to get DRBD openers of volume `%s/%d`: `%s`.", resource_name, volume_number, e) | ||
| return [] | ||
|
|
||
| drbd_openers = [] | ||
| for line in lines: | ||
| match = _REGEX_DRBD_OPENER_LINE.fullmatch(line) | ||
| if not match: | ||
| logger.warning( | ||
| "Unable to parse DRBD opener line of volume `%s/%d` with: `%s`.", | ||
| resource_name, | ||
| volume_number, | ||
| line | ||
| ) | ||
| continue | ||
|
|
||
| groups = match.groups() | ||
| pid = int(groups[1]) | ||
| drbd_openers.append(DrbdOpener( | ||
| pid=pid, | ||
| process_name=groups[0], | ||
| # Note: `cmdline` is empty for `mount` calls. That's correct because `mount` process is dead. | ||
| cmdline=get_process_cmdline(pid), | ||
| open_duration=int(groups[2]) | ||
| )) | ||
|
|
||
| return drbd_openers | ||
|
|
||
| @staticmethod | ||
| def demote(resource_name: str) -> bool: | ||
| _check_drbd_resource_name(resource_name) | ||
| error_message = "" | ||
| try: | ||
| _stdout, stderr, ret_code = run_command([_EXEC_PATH_DRBDSETUP, "secondary", resource_name], simple=False) | ||
| if not ret_code: | ||
| return True | ||
| error_message = stderr | ||
| except Exception as e: | ||
| error_message = str(e) | ||
| logger.error("Failed to demote DRBD resource `%s`: `%s`.", resource_name, error_message) | ||
| return False | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,40 @@ | ||
| # Copyright (C) 2026 Vates SAS | ||
| # | ||
| # This program is free software: you can redistribute it and/or modify | ||
| # it under the terms of the GNU General Public License as published by | ||
| # the Free Software Foundation, either version 3 of the License, or | ||
| # (at your option) any later version. | ||
| # This program is distributed in the hope that it will be useful, | ||
| # but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
| # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
| # GNU General Public License for more details. | ||
| # | ||
| # You should have received a copy of the GNU General Public License | ||
| # along with this program. If not, see <https://www.gnu.org/licenses/>. | ||
|
|
||
| from dataclasses import asdict | ||
|
|
||
| from xcp_storage.backends.drbd import Drbd | ||
| from xcp_storage.rpc.dispatcher import ApiDispatcher | ||
| from xcp_storage.utils.json import JsonDict | ||
|
|
||
| from xcp_storage.typing import ( | ||
| assert_type, | ||
| cast, | ||
| Dict, | ||
| List, | ||
| MYPY, | ||
| PYREFLY, | ||
| Union, | ||
| ) | ||
|
|
||
| # ============================================================================== | ||
|
|
||
| @ApiDispatcher.method | ||
| def get_openers(resource_name: str, volume_number: int) -> List[JsonDict]: | ||
| openers = [asdict(opener) for opener in Drbd.get_local_openers(resource_name, volume_number)] | ||
| # Some linters, such as pyrefly, may struggle to convert a type to a recursive type. | ||
| # We therefore perform a static check (so that it's validated by linters) and we cast it explicitly. | ||
| if PYREFLY and not MYPY: | ||
| assert_type(openers, List[Dict[str, Union[int, str, List[str]]]]) | ||
| return cast(List[JsonDict], openers) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Process names from the
openersfile may also be prefixed with a "+" in certain cases (see https://github.com/LINBIT/drbd/blob/6c10a1e648883ef457f831c6b7be39a7e39cb50f/drbd/drbd_debugfs.c#L1179-L1203).For example:
In this case, this function returns the following:
[ { "pid": 3629671, "process_name": "tapdisk", "cmdline": [ "tapdisk" ], "open_duration": 75149683 }, { "pid": 3629671, "process_name": "+tapdisk", "cmdline": [ "tapdisk" ], "open_duration": 75149683 } ]Is this expected behavior?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yes, this behavior has been known for a long time and can prove useful for debugging. :)
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
In this case, since this "+" isn't really a part of the process name, does it make more sense to remove it and add a boolean property which would represent it?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I'm not sure about that. As long as we aren't doing detailed parsing, we don't need to do that. Overall, the use case for this API is really just to retrieve the content from the DEBUG path and dump it, and perhaps send that raw data to XO6 sometime in the future.
Ideally, we shouldn't use data specific to this helper (or add more parsing) to trigger actions on the driver side.
@Millefeuille42 For additional comments.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
If we want to exploit the data at SMAPI level why not implement its parsing, but if the idea is to send it to XO, since it's already JSON I don't see a point in parsing it beforehand.