File: pyutils.cpp

package info (click to toggle)
pytango 10.0.2-3
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 10,216 kB
  • sloc: python: 28,206; cpp: 16,380; sql: 255; sh: 82; makefile: 43
file content (451 lines) | stat: -rw-r--r-- 13,577 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
/*
 * SPDX-FileCopyrightText: All Contributors to the PyTango project
 *
 * SPDX-License-Identifier: LGPL-3.0-or-later
 */

#include "precompiled_header.hpp"
#include "defs.h"
#include "pyutils.h"

bopy::object from_char_to_boost_str(const std::string &in,
                                    const char *encoding /*=NULL defaults to latin-1 */,
                                    const char *errors /*="strict" */)
{
    return from_char_to_boost_str(in.c_str(), in.size(), encoding, errors);
}

bopy::object from_char_to_boost_str(const char *in,
                                    Py_ssize_t size /* =-1 */,
                                    const char *encoding /*=NULL defaults to latin-1 */,
                                    const char *errors /*="strict" */)
{
    return bopy::object(bopy::handle<>(from_char_to_python_str(in, size, encoding, errors)));
}

PyObject *from_char_to_python_str(const std::string &in,
                                  const char *encoding /*=NULL defaults to latin-1 */,
                                  const char *errors /*="strict" */)
{
    return from_char_to_python_str(in.c_str(), in.size(), encoding, errors);
}

PyObject *from_char_to_python_str(const char *in,
                                  Py_ssize_t size /* =-1 */,
                                  const char *encoding /*=NULL defaults to latin-1 */,
                                  const char *errors /*="strict" */)
{
    if(size < 0)
    {
        size = strlen(in);
    }
    if(!encoding)
    {
        return PyUnicode_DecodeLatin1(in, size, errors);
    }
    else
    {
        return PyUnicode_Decode(in, size, encoding, errors);
    }
}

void throw_bad_type(const char *type, const char *source)
{
    TangoSys_OMemStream description;
    description << "Incompatible argument type, expected type is : Tango::" << type << std::ends;

    TangoSys_OMemStream origin;
    origin << source << std::ends;

    Tango::Except::throw_exception("API_IncompatibleCmdArgumentType", description.str(), origin.str());
}

char *__copy_bytes_to_char(PyObject *in, Py_ssize_t *size)
{
    Py_buffer view;

    if(PyObject_GetBuffer(in, &view, PyBUF_FULL_RO) < 0)
    {
        raise_(PyExc_TypeError, "Can't translate python object to C char* - PyObject_GetBuffer failed");
    }

    *size = view.len;
    char *out = new char[*size + 1];
    out[*size] = '\0';
    memcpy(out, (char *) view.buf, *size);

    PyBuffer_Release(&view);

    return out;
}

char *from_str_to_char(const bopy::object &in)
{
    Py_ssize_t size;
    return from_str_to_char(in.ptr(), &size);
}

char *from_str_to_char(PyObject *in)
{
    Py_ssize_t size;
    return from_str_to_char(in, &size);
}

char *from_str_to_char(const bopy::object &in, Py_ssize_t *size_out, const bool utf_encoding)
{
    return from_str_to_char(in.ptr(), size_out, utf_encoding);
}

// The result is a newly allocated buffer. It is the responsibility
// of the caller to manage the memory returned by this function
char *from_str_to_char(PyObject *in, Py_ssize_t *size_out, const bool utf_encoding)
{
    char *out = NULL;
    if(PyUnicode_Check(in))
    {
        PyObject *bytes_in;
        if(utf_encoding)
        {
            bytes_in = PyUnicode_AsUTF8String(in);
        }
        else
        {
            bytes_in = EncodeAsLatin1(in);
        }
        out = __copy_bytes_to_char(bytes_in, size_out);
        Py_DECREF(bytes_in);
    }
    else if(PyBytes_Check(in) || PyByteArray_Check(in))
    {
        out = __copy_bytes_to_char(in, size_out);
    }
    else
    {
        raise_(PyExc_TypeError, "can't translate python object to C char*");
    }
    return out;
}

// The out_array will be updated with a pointer to existing memory (e.g., Python's internal memory for
// a byte array). The caller gets a "view" of the memory and must not modify the memory.
void view_pybytes_as_char_array(const bopy::object &py_value, Tango::DevVarCharArray &out_array)
{
    CORBA::ULong nb;
    PyObject *data_ptr = py_value.ptr();

    if(PyUnicode_Check(data_ptr))
    {
        Py_ssize_t size;
        CORBA::Octet *encoded_data = (CORBA::Octet *) PyUnicode_AsUTF8AndSize(data_ptr, &size);
        nb = static_cast<CORBA::ULong>(size);
        out_array.replace(nb, nb, encoded_data, false);
    }

    else if(PyBytes_Check(data_ptr))
    {
        nb = static_cast<CORBA::ULong>(bopy::len(py_value));
        CORBA::Octet *encoded_data = (CORBA::Octet *) PyBytes_AsString(data_ptr);
        out_array.replace(nb, nb, encoded_data, false);
    }
    else if(PyByteArray_Check(data_ptr))
    {
        nb = static_cast<CORBA::ULong>(bopy::len(py_value));
        CORBA::Octet *encoded_data = (CORBA::Octet *) PyByteArray_AsString(data_ptr);
        out_array.replace(nb, nb, encoded_data, false);
    }
    else
    {
        throw_bad_type(Tango::CmdArgTypeName[Tango::DEV_ENCODED], TANGO_EXCEPTION_ORIGIN);
    }
}

bool is_method_defined(bopy::object &obj, const std::string &method_name)
{
    return is_method_defined(obj.ptr(), method_name);
}

bool is_method_defined(PyObject *obj, const std::string &method_name)
{
    bool exists, is_method;
    is_method_defined(obj, method_name, exists, is_method);
    return exists && is_method;
}

void is_method_defined(bopy::object &obj, const std::string &method_name, bool &exists, bool &is_method)
{
    is_method_defined(obj.ptr(), method_name, exists, is_method);
}

void is_method_defined(PyObject *obj, const std::string &method_name, bool &exists, bool &is_method)
{
    exists = is_method = false;

    PyObject *meth = PyObject_GetAttrString_(obj, method_name.c_str());

    exists = NULL != meth;

    if(!exists)
    {
        PyErr_Clear();
        return;
    }

    is_method = (1 == PyCallable_Check(meth));
    Py_DECREF(meth);
}

#ifdef PYCAPSULE_OLD

int PyCapsule_SetName(PyObject *capsule, const char *unused)
{
    unused = unused;
    PyErr_SetString(PyExc_NotImplementedError, "can't use PyCapsule_SetName with CObjects");
    return 1;
}

void *PyCapsule_Import(const char *name, int no_block)
{
    PyObject *object = NULL;
    void *return_value = NULL;
    char *trace;
    size_t name_length = (strlen(name) + 1) * sizeof(char);
    char *name_dup = (char *) PyMem_MALLOC(name_length);

    if(!name_dup)
    {
        return NULL;
    }

    memcpy(name_dup, name, name_length);

    trace = name_dup;
    while(trace)
    {
        char *dot = strchr(trace, '.');
        if(dot)
        {
            *dot++ = '\0';
        }

        if(object == NULL)
        {
            if(no_block)
            {
                object = PyImport_ImportModuleNoBlock(trace);
            }
            else
            {
                object = PyImport_ImportModule(trace);
                if(!object)
                {
                    PyErr_Format(PyExc_ImportError,
                                 "PyCapsule_Import could not "
                                 "import module \"%s\"",
                                 trace);
                }
            }
        }
        else
        {
            PyObject *object2 = PyObject_GetAttrString(object, trace);
            Py_DECREF(object);
            object = object2;
        }
        if(!object)
        {
            goto EXIT;
        }

        trace = dot;
    }

    if(PyCObject_Check(object))
    {
        PyCObject *cobject = (PyCObject *) object;
        return_value = cobject->cobject;
    }
    else
    {
        PyErr_Format(PyExc_AttributeError, "PyCapsule_Import \"%s\" is not valid", name);
    }

EXIT:
    Py_XDECREF(object);
    if(name_dup)
    {
        PyMem_FREE(name_dup);
    }
    return return_value;
}

#endif

bool hasattr(bopy::object &obj, const std::string &name)
{
    return PyObject_HasAttrString(obj.ptr(), name.c_str());
}

void export_ensure_omni_thread()
{
    bopy::class_<EnsureOmniThread, boost::noncopyable>("EnsureOmniThread", bopy::init<>())
        .def("_acquire", &EnsureOmniThread::acquire)
        .def("_release", &EnsureOmniThread::release);
    bopy::def("is_omni_thread", is_omni_thread);
}

#if defined(TANGO_USE_TELEMETRY)
// I.e., cppTango is compiled with telemetry support.

Tango::telemetry::InterfacePtr telemetry_interface{nullptr};
Tango::telemetry::ScopePtr telemetry_set_context_scope{nullptr};

void ensure_default_telemetry_interface_initialized()
{
    if(!telemetry_interface)
    {
        std::string client_name;
        if(Tango::ApiUtil::get_env_var("PYTANGO_TELEMETRY_CLIENT_SERVICE_NAME", client_name) != 0)
        {
            client_name = "pytango.client";
        }
        std::string name_space{"tango"};
        auto details = Tango::telemetry::Configuration::Client{client_name};
        Tango::telemetry::Configuration cfg{client_name, name_space, details};
        telemetry_interface = Tango::telemetry::InterfaceFactory::create(cfg);
    }
    // else: we already made our custom interface singleton.

    auto span = Tango::telemetry::Interface::get_current();
    if(span->is_default())
    {
        // Make our client interface active (applies to current thread only, as cppTango uses a thread_local variable)
        Tango::telemetry::Interface::set_current(telemetry_interface);
    }
    // else: a non-default interface is either from a device, or we already set our client interface for this thread.
}

/*
 * Get the current trace context (from cppTango, to be used in PyTango).
 *
 * This function is used to propagate the trace context, fetching it from the cppTango kernel context,
 * The trace context is obtained in its W3C format as a dict of strings, with keys: "traceparent" and "tracestate".
 *
 * For details of the W3C format see: https://www.w3.org/TR/trace-context/
 */
bopy::dict get_trace_context()
{
    ensure_default_telemetry_interface_initialized();

    std::string trace_parent;
    std::string trace_state;
    Tango::telemetry::Interface::get_trace_context(trace_parent, trace_state);

    bopy::dict carrier;
    carrier["traceparent"] = trace_parent;
    carrier["tracestate"] = trace_state;
    return carrier;
}

/*
 * Set the trace context (from PyTango to cppTango)
 *
 * This class is used to propagate trace context, writing the Python context into cppTango's telemetry context using
 * the two strings passed as constructor arguments (trace_parent & trace_state) in W3C format. A new span, with
 * the name specified by the "new_span_name" argument will be created when then acquire() method is called.
 * We have an acquire() method and a release() method so that this class can be used with a Python context handler.
 * Entering the context handler must call acquire(), which activates the scope in cppTango.  Exiting the context
 * handler must call release(), thus ending the scope (and associated span), and returning cppTango's context to
 * whatever it was before.  The restoration of the scope happens automatically when the scope pointer is released,
 * and the underlying cppTango object destroyed.
 *
 * For details of the W3C format see: https://www.w3.org/TR/trace-context/
 */
class TraceContextScope
{
    Tango::telemetry::ScopePtr scope;
    const std::string new_span_name;
    std::string trace_parent;
    std::string trace_state;

  public:
    TraceContextScope(const std::string &new_span_name_,
                      const std::string &trace_parent_,
                      const std::string &trace_state_) :
        new_span_name{new_span_name_},
        trace_parent{trace_parent_},
        trace_state{trace_state_}
    {
    }

    void acquire()
    {
        if(scope == nullptr)
        {
            ensure_default_telemetry_interface_initialized();
            scope = Tango::telemetry::Interface::set_trace_context(
                new_span_name, trace_parent, trace_state, Tango::telemetry::Span::Kind::kClient);
        }
    }

    void release()
    {
        scope = nullptr;
    }

    ~TraceContextScope()
    {
        release();
    }
};

#else
// cppTango is *not* compiled with telemetry support.
// We use no-op handlers, so the Python code can run without errors but does nothing.

bopy::dict no_op_get_trace_context()
{
    bopy::dict carrier;
    carrier["traceparent"] = "";
    carrier["tracestate"] = "";
    return carrier;
}

class NoOpTraceContextScope
{
  public:
    NoOpTraceContextScope(const std::string &new_span_name_,
                          const std::string &trace_parent_,
                          const std::string &trace_state_)
    {
    }

    void acquire() { }

    void release() { }

    ~NoOpTraceContextScope() { }
};

#endif

void export_telemetry_helpers()
{
    bopy::object telemetry_module(bopy::handle<>(bopy::borrowed(PyImport_AddModule("tango._telemetry"))));
    bopy::scope().attr("_telemetry") = telemetry_module;
    bopy::scope telemetry_scope = telemetry_module;

#if defined(TANGO_USE_TELEMETRY)
    telemetry_scope.attr("TELEMETRY_ENABLED") = true;
    bopy::def("get_trace_context", get_trace_context);
    bopy::class_<TraceContextScope, boost::noncopyable>(
        "TraceContextScope", bopy::init<const std::string &, const std::string &, const std::string &>())
        .def("_acquire", &TraceContextScope::acquire)
        .def("_release", &TraceContextScope::release);
#else
    bopy::def("get_trace_context", no_op_get_trace_context);
    bopy::class_<NoOpTraceContextScope, boost::noncopyable>(
        "TraceContextScope", bopy::init<const std::string &, const std::string &, const std::string &>())
        .def("_acquire", &NoOpTraceContextScope::acquire)
        .def("_release", &NoOpTraceContextScope::release);
#endif
}