• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Copyright 2023 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.
14import codecs
15from typing import Optional
16
17from libcpp.cast cimport static_cast
18
19from grpc import _observability
20
21
22cdef const char* CLIENT_CALL_TRACER = "client_call_tracer"
23cdef const char* SERVER_CALL_TRACER_FACTORY = "server_call_tracer_factory"
24
25
26def get_server_call_tracer_factory_address(object observability_plugin, bint xds) -> Optional[int]:
27  capsule = observability_plugin.create_server_call_tracer_factory(xds=xds)
28  if capsule:
29    capsule_ptr = cpython.PyCapsule_GetPointer(capsule, SERVER_CALL_TRACER_FACTORY)
30    return int(<uintptr_t>capsule_ptr)
31  else:
32    return None
33
34def clear_server_call_tracer_factory() -> None:
35  _register_server_call_tracer_factory(NULL)
36
37
38def maybe_save_server_trace_context(RequestCallEvent event) -> None:
39  cdef ServerCallTracer* server_call_tracer
40  with _observability.get_plugin() as plugin:
41    if not (plugin and plugin.tracing_enabled):
42      return
43    server_call_tracer = static_cast['ServerCallTracer*'](_get_call_tracer(event.call.c_call))
44    # TraceId and SpanId is hex string, need to convert to str
45    trace_id = _decode(codecs.decode(server_call_tracer.TraceId(), 'hex_codec'))
46    span_id = _decode(codecs.decode(server_call_tracer.SpanId(), 'hex_codec'))
47    is_sampled = server_call_tracer.IsSampled()
48    plugin.save_trace_context(trace_id, span_id, is_sampled)
49
50
51cdef void _set_call_tracer(grpc_call* call, void* capsule_ptr):
52  cdef ClientCallTracer* call_tracer = <ClientCallTracer*>capsule_ptr
53  grpc_call_tracer_set_and_manage(call, call_tracer)
54
55
56cdef void* _get_call_tracer(grpc_call* call):
57  cdef void* call_tracer = grpc_call_tracer_get(call)
58  return call_tracer
59
60
61cdef void _register_server_call_tracer_factory(void* capsule_ptr):
62  cdef ServerCallTracerFactory* call_tracer_factory = <ServerCallTracerFactory*>capsule_ptr
63  ServerCallTracerFactory.RegisterGlobal(call_tracer_factory)
64