From 71d99118d22f99db5ff7ecde1ce45ba4e0779bd9 Mon Sep 17 00:00:00 2001 From: John Mulligan Date: Sat, 9 Apr 2022 14:46:50 -0400 Subject: [PATCH] pybind/mgr: add a ReturnValueAdapter type to object_format.py The ReturnValueAdapter type fulfills a similar role to the ObjectFormatAdapter but instead of serializing data for the body of a mgr response, extracts an return value (error code) to reply with. Most of the time it is totally unnecessary to provide an explicit return value because if you have are returning a valid object (as opposed to raising an exception) the return value will be zero (success). However, in the off chance an type need to directly communicate a return value for the mgr response it can provide the `mgr_return_value` method and the adapater will discover and use it. Signed-off-by: John Mulligan (cherry picked from commit 27787a9905d4d2e1062f7f4977377530d7aa8c23) --- src/pybind/mgr/object_format.py | 35 +++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/src/pybind/mgr/object_format.py b/src/pybind/mgr/object_format.py index 045d17461d85..2dc0ecdabac6 100644 --- a/src/pybind/mgr/object_format.py +++ b/src/pybind/mgr/object_format.py @@ -80,6 +80,15 @@ class YAMLFormatter(Protocol): ... # pragma: no cover +class ReturnValueProvider(Protocol): + def mgr_return_value(self) -> int: + """Return an integer value to provide the Ceph MGR with a error code + for the MGR's response tuple. Zero means success. Return an negative + errno otherwise. + """ + ... # pragma: no cover + + # The _is_name_of_protocol_type functions below are here because the production # builds of the ceph manager are lower than python 3.8 and do not have # typing_extensions available in the resulting images. This means that @@ -106,6 +115,11 @@ def _is_yaml_data_provider(obj: YAMLDataProvider) -> bool: return callable(getattr(obj, 'to_yaml', None)) +def _is_return_value_provider(obj: ReturnValueProvider) -> bool: + """Return true if obj is usable as a YAMLDataProvider.""" + return callable(getattr(obj, 'mgr_return_value', None)) + + class ObjectFormatAdapter: """A format adapater for a single object. Given an input object, this type will adapt the object, or a simplified @@ -167,3 +181,24 @@ class ObjectFormatAdapter: def format_yaml(self) -> str: """Return a YAML formatted string representing the input object.""" return yaml.safe_dump(self._fetch_yaml_data()) + + +class ReturnValueAdapter: + """A return-value adapter for an object. + Given an input object, this type will attempt to get a mgr return value + from the object if provides a `mgr_return_value` function. + If not it returns a default return value, typically 0. + """ + + def __init__( + self, + obj: Any, + default: int = 0, + ) -> None: + self.obj = obj + self.default_return_value = default + + def mgr_return_value(self) -> int: + if _is_return_value_provider(self.obj): + return int(self.obj.mgr_return_value()) + return self.default_return_value -- 2.47.3