Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/grpc/_observability.py: 54%
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1# Copyright 2023 The gRPC authors.
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
15from __future__ import annotations
17import abc
18import contextlib
19import logging
20import threading
21from typing import (
22 TYPE_CHECKING,
23 Any,
24 Generator,
25 Generic,
26 List,
27 Optional,
28 Tuple,
29 TypeVar,
30 Union,
31)
33from grpc._cython import cygrpc as _cygrpc
34from grpc._typing import ChannelArgumentType
36if TYPE_CHECKING:
37 from grpc._channel import _RPCState
39_LOGGER = logging.getLogger(__name__)
41ClientCallTracerCapsule = TypeVar("ClientCallTracerCapsule")
42ServerCallTracerFactoryCapsule = TypeVar("ServerCallTracerFactoryCapsule")
44_plugin_lock: threading.RLock = threading.RLock()
45_OBSERVABILITY_PLUGIN: Optional["ObservabilityPlugin"] = None
46_SERVICES_TO_EXCLUDE: List[bytes] = [
47 b"google.monitoring.v3.MetricService",
48 b"google.devtools.cloudtrace.v2.TraceService",
49]
52class ServerCallTracerFactory:
53 """An encapsulation of a ServerCallTracerFactory.
55 Instances of this class can be passed to a Channel as values for the
56 grpc.experimental.server_call_tracer_factory option
57 """
59 def __init__(self, address):
60 self._address = address
62 def __int__(self):
63 return self._address
66class ObservabilityPlugin(
67 Generic[ClientCallTracerCapsule, ServerCallTracerFactoryCapsule],
68 metaclass=abc.ABCMeta,
69):
70 """Abstract base class for observability plugin.
72 *This is a semi-private class that was intended for the exclusive use of
73 the gRPC team.*
75 The ClientCallTracerCapsule and ClientCallTracerCapsule created by this
76 plugin should be injected to gRPC core using observability_init at the
77 start of a program, before any channels/servers are built.
79 Any future methods added to this interface cannot have the
80 @abc.abstractmethod annotation.
82 Attributes:
83 _stats_enabled: A bool indicates whether tracing is enabled.
84 _tracing_enabled: A bool indicates whether stats(metrics) is enabled.
85 _registered_methods: A set which stores the registered method names in
86 bytes.
87 """
89 _tracing_enabled: bool = False
90 _stats_enabled: bool = False
92 @abc.abstractmethod
93 def create_client_call_tracer(
94 self, method_name: bytes, target: bytes
95 ) -> ClientCallTracerCapsule:
96 """Creates a ClientCallTracerCapsule.
98 After register the plugin, if tracing or stats is enabled, this method
99 will be called after a call was created, the ClientCallTracer created
100 by this method will be saved to call context.
102 The ClientCallTracer is an object which implements `grpc_core::ClientCallTracer`
103 interface and wrapped in a PyCapsule using `client_call_tracer` as name.
105 Args:
106 method_name: The method name of the call in byte format.
107 target: The channel target of the call in byte format.
108 registered_method: Whether this method is pre-registered.
110 Returns:
111 A PyCapsule which stores a ClientCallTracer object.
112 """
113 raise NotImplementedError()
115 @abc.abstractmethod
116 def save_trace_context(
117 self, trace_id: str, span_id: str, is_sampled: bool
118 ) -> None:
119 """Saves the trace_id and span_id related to the current span.
121 After register the plugin, if tracing is enabled, this method will be
122 called after the server finished sending response.
124 This method can be used to propagate census context.
126 Args:
127 trace_id: The identifier for the trace associated with the span as a
128 32-character hexadecimal encoded string,
129 e.g. 26ed0036f2eff2b7317bccce3e28d01f
130 span_id: The identifier for the span as a 16-character hexadecimal encoded
131 string. e.g. 113ec879e62583bc
132 is_sampled: A bool indicates whether the span is sampled.
133 """
134 raise NotImplementedError()
136 @abc.abstractmethod
137 def create_server_call_tracer_factory(
138 self,
139 *,
140 xds: bool = False,
141 ) -> Optional[ServerCallTracerFactoryCapsule]:
142 """Creates a ServerCallTracerFactoryCapsule.
144 This method will be called at server initialization time to create a
145 ServerCallTracerFactory, which will be registered to gRPC core.
147 The ServerCallTracerFactory is an object which implements
148 `grpc_core::ServerCallTracerFactory` interface and wrapped in a PyCapsule
149 using `server_call_tracer_factory` as name.
151 Args:
152 xds: Whether the server is xds server.
154 Returns:
155 A PyCapsule which stores a ServerCallTracerFactory object. Or None if
156 plugin decides not to create ServerCallTracerFactory.
157 """
158 raise NotImplementedError()
160 @abc.abstractmethod
161 def record_rpc_latency(
162 self, method: str, target: str, rpc_latency: float, status_code: Any
163 ) -> None:
164 """Record the latency of the RPC.
166 After register the plugin, if stats is enabled, this method will be
167 called at the end of each RPC.
169 Args:
170 method: The fully-qualified name of the RPC method being invoked.
171 target: The target name of the RPC method being invoked.
172 rpc_latency: The latency for the RPC in seconds, equals to the time between
173 when the client invokes the RPC and when the client receives the status.
174 status_code: An element of grpc.StatusCode in string format representing the
175 final status for the RPC.
176 """
177 raise NotImplementedError()
179 def set_tracing(self, enable: bool) -> None:
180 """Enable or disable tracing.
182 Args:
183 enable: A bool indicates whether tracing should be enabled.
184 """
185 self._tracing_enabled = enable
187 def set_stats(self, enable: bool) -> None:
188 """Enable or disable stats(metrics).
190 Args:
191 enable: A bool indicates whether stats should be enabled.
192 """
193 self._stats_enabled = enable
195 def save_registered_method(self, method_name: bytes) -> None:
196 """Saves the method name to registered_method list.
198 When exporting metrics, method name for unregistered methods will be replaced
199 with 'other' by default.
201 Args:
202 method_name: The method name in bytes.
203 """
204 raise NotImplementedError()
206 @property
207 def tracing_enabled(self) -> bool:
208 return self._tracing_enabled
210 @property
211 def stats_enabled(self) -> bool:
212 return self._stats_enabled
214 @property
215 def observability_enabled(self) -> bool:
216 return self.tracing_enabled or self.stats_enabled
219@contextlib.contextmanager
220def get_plugin() -> Generator[Optional[ObservabilityPlugin], None, None]:
221 """Get the ObservabilityPlugin in _observability module.
223 Returns:
224 The ObservabilityPlugin currently registered with the _observability
225 module. Or None if no plugin exists at the time of calling this method.
226 """
227 with _plugin_lock:
228 yield _OBSERVABILITY_PLUGIN
231def set_plugin(observability_plugin: Optional[ObservabilityPlugin]) -> None:
232 """Save ObservabilityPlugin to _observability module.
234 Args:
235 observability_plugin: The ObservabilityPlugin to save.
237 Raises:
238 ValueError: If an ObservabilityPlugin was already registered at the
239 time of calling this method.
240 """
241 global _OBSERVABILITY_PLUGIN # pylint: disable=global-statement # noqa: PLW0603
242 with _plugin_lock:
243 if observability_plugin and _OBSERVABILITY_PLUGIN:
244 error_msg = "observability_plugin was already set!"
245 raise ValueError(error_msg)
246 _OBSERVABILITY_PLUGIN = observability_plugin
249def observability_init(observability_plugin: ObservabilityPlugin) -> None:
250 """Initialize observability with provided ObservabilityPlugin.
252 This method have to be called at the start of a program, before any
253 channels/servers are built.
255 Args:
256 observability_plugin: The ObservabilityPlugin to use.
258 Raises:
259 ValueError: If an ObservabilityPlugin was already registered at the
260 time of calling this method.
261 """
262 set_plugin(observability_plugin)
265def observability_deinit() -> None:
266 """Clear the observability context, including ObservabilityPlugin and
267 ServerCallTracerFactory
269 This method have to be called after exit observability context so that
270 it's possible to re-initialize again.
271 """
272 set_plugin(None)
273 _cygrpc.clear_server_call_tracer_factory()
276def maybe_record_rpc_latency(state: "_RPCState") -> None:
277 """Record the latency of the RPC, if the plugin is registered and stats is enabled.
279 This method will be called at the end of each RPC.
281 Args:
282 state: a grpc._channel._RPCState object which contains the stats related to the
283 RPC.
284 """
285 # TODO(xuanwn): use channel args to exclude those metrics.
286 for exclude_prefix in _SERVICES_TO_EXCLUDE:
287 if exclude_prefix in state.method.encode("utf8"):
288 return
289 with get_plugin() as plugin:
290 if plugin and plugin.stats_enabled:
291 rpc_latency_s = state.rpc_end_time - state.rpc_start_time
292 rpc_latency_ms = rpc_latency_s * 1000
293 plugin.record_rpc_latency(
294 state.method, state.target, rpc_latency_ms, state.code
295 )
298def create_server_call_tracer_factory_option(
299 xds: bool,
300) -> Union[Tuple[ChannelArgumentType], Tuple[()]]:
301 with get_plugin() as plugin:
302 if plugin and plugin.stats_enabled:
303 server_call_tracer_factory_address = (
304 _cygrpc.get_server_call_tracer_factory_address(plugin, xds)
305 )
306 if server_call_tracer_factory_address:
307 return (
308 (
309 "grpc.experimental.server_call_tracer_factory",
310 ServerCallTracerFactory(
311 server_call_tracer_factory_address
312 ),
313 ),
314 )
315 return ()