File: python-persist.c

package info (click to toggle)
syslog-ng 4.8.1-6
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 20,456 kB
  • sloc: ansic: 177,631; python: 13,035; cpp: 11,611; makefile: 7,012; sh: 5,147; java: 3,651; xml: 3,344; yacc: 1,377; lex: 599; perl: 193; awk: 190; objc: 162
file content (551 lines) | stat: -rw-r--r-- 15,301 bytes parent folder | download | duplicates (2)
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
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
/*
 * Copyright (c) 2019 Balabit
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 as published
 * by the Free Software Foundation, 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, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * As an additional exemption you are allowed to compile & link against the
 * OpenSSL libraries as published by the OpenSSL project. See the file
 * COPYING for details.
 *
 */

#include "python-persist.h"
#include "persistable-state-header.h"
#include "python-helpers.h"
#include "python-types.h"
#include "python-main.h"
#include "syslog-ng.h"
#include "driver.h"
#include "mainloop.h"
#include "compat/compat-python.h"

#include <structmember.h>

#define SUBKEY_DELIMITER "##"
#define MASTER_ENTRY_VERSION 1

typedef PersistableStateHeader PythonPersistMasterEntry;

typedef enum
{
  ENTRY_TYPE_STRING,
  ENTRY_TYPE_LONG,
  ENTRY_TYPE_BYTES,
  ENTRY_TYPE_MAX
} EntryType;

typedef struct
{
  guint8 type;
  gchar data[0];
} Entry;

/* Ensure there is no padding between type and data */
G_STATIC_ASSERT(offsetof(Entry, data) == sizeof(guint8) + offsetof(Entry, type));

static PyObject *
entry_to_pyobject(guint8 type, gchar *value)
{
  switch (type)
    {
    case ENTRY_TYPE_STRING:
      return py_string_from_string(value, -1);
    case ENTRY_TYPE_LONG:
      return PyLong_FromString(value, NULL, 10);
    case ENTRY_TYPE_BYTES:
      return PyBytes_FromString(value);
    default:
      g_assert_not_reached();
    }
}

static PyObject *
_call_generate_persist_name_method(PythonPersistMembers *options)
{
  PyObject *py_options = options->options ? python_options_create_py_dict(options->options) : NULL;
  PyObject *ret = _py_invoke_function(options->generate_persist_name_method, py_options,
                                      options->class, options->id);
  Py_XDECREF(py_options);
  return ret;
}

static void
format_default_stats_instance(gchar *buffer, gsize size, const gchar *module, const gchar *name)
{
  g_snprintf(buffer, size, "%s,%s", module, name);
}

static void
copy_stats_instance(const LogPipe *self, const gchar *module, PythonPersistMembers *options,
                    gchar *buffer, gsize size)
{
  PyGILState_STATE gstate;
  gstate = PyGILState_Ensure();

  PyObject *ret = _call_generate_persist_name_method(options);
  if (ret)
    {
      const gchar *ret_as_c_str;
      py_bytes_or_string_to_string(ret, &ret_as_c_str);
      g_snprintf(buffer, size, "%s,%s", module, ret_as_c_str);
    }
  else
    {
      format_default_stats_instance(buffer, size, module, options->class);
      msg_error("Failed while generating persist name, using default",
                evt_tag_str("default_persist_name", buffer),
                evt_tag_str("driver", options->id),
                evt_tag_str("class", options->class));
    }
  Py_XDECREF(ret);

  PyGILState_Release(gstate);
}

static void
copy_instance_name(const LogPipe *self, const gchar *module, PythonPersistMembers *options,
                   gchar *buffer, gsize size)
{
  PyGILState_STATE gstate;
  gstate = PyGILState_Ensure();

  PyObject *ret = _call_generate_persist_name_method(options);
  if (ret)
    {
      const gchar *ret_as_c_str;
      py_bytes_or_string_to_string(ret, &ret_as_c_str);
      g_snprintf(buffer, size, "%s", ret_as_c_str);
    }
  else
    {
      g_strlcpy(buffer, "", size);
    }
  Py_XDECREF(ret);

  PyGILState_Release(gstate);
}

const gchar *
python_format_stats_key(LogPipe *p, StatsClusterKeyBuilder *kb, const gchar *module, PythonPersistMembers *options)
{
  static gchar persist_name[1024];

  stats_cluster_key_builder_add_legacy_label(kb, stats_cluster_label("driver", module));
  stats_cluster_key_builder_add_legacy_label(kb, stats_cluster_label("class", options->class));

  if (options->generate_persist_name_method)
    {
      copy_instance_name(p, module, options, persist_name, sizeof(persist_name));
      stats_cluster_key_builder_add_legacy_label(kb, stats_cluster_label("instance", persist_name));
    }


  if (p->persist_name)
    format_default_stats_instance(persist_name, sizeof(persist_name), module, p->persist_name);
  else if (options->generate_persist_name_method)
    copy_stats_instance(p, module, options, persist_name, sizeof(persist_name));
  else
    format_default_stats_instance(persist_name, sizeof(persist_name), module, options->class);

  return persist_name;
}

static void
format_default_persist_name_with_persist_name(gchar *buffer, gsize size, const gchar *module, const gchar *persist_name)
{
  g_snprintf(buffer, size, "%s.%s", module, persist_name);
}

static void
format_default_persist_name_with_class(gchar *buffer, gsize size, const gchar *module, const gchar *class)
{
  g_snprintf(buffer, size, "%s(%s)", module, class);
}

static void
copy_persist_name(const LogPipe *self, const gchar *module, PythonPersistMembers *options,
                  gchar *buffer, gsize size)
{
  PyGILState_STATE gstate;
  gstate = PyGILState_Ensure();

  PyObject *ret =_call_generate_persist_name_method(options);
  if (ret)
    {
      const gchar *ret_as_c_str;
      py_bytes_or_string_to_string(ret, &ret_as_c_str);
      g_snprintf(buffer, size, "%s.%s", module, ret_as_c_str);
    }
  else
    {
      format_default_persist_name_with_class(buffer, size, module, options->class);
      msg_error("Failed while generating persist name, using default",
                evt_tag_str("default_persist_name", buffer),
                evt_tag_str("driver", options->id),
                evt_tag_str("class", options->class));
    }
  Py_XDECREF(ret);

  PyGILState_Release(gstate);
}

const gchar *
python_format_persist_name(const LogPipe *p, const gchar *module, PythonPersistMembers *options)
{
  static gchar persist_name[1024];

  if (p->persist_name)
    format_default_persist_name_with_persist_name(persist_name, sizeof(persist_name), module, p->persist_name);
  else if (options->generate_persist_name_method)
    copy_persist_name(p, module, options, persist_name, sizeof(persist_name));
  else
    format_default_persist_name_with_class(persist_name, sizeof(persist_name), module, options->class);

  return persist_name;
}

static gboolean
load_persist_entry(PersistState *persist_state, PersistEntryHandle handle)
{
  PythonPersistMasterEntry *entry = persist_state_map_entry(persist_state, handle);
  guint8 version = entry->version;
  persist_state_unmap_entry(persist_state, handle);

  if (version != MASTER_ENTRY_VERSION)
    {
      PyErr_Format(PyExc_RuntimeError, "Invalid persist version: %d\nPossible persist file corruption", (gint)version);
      return FALSE;
    }

  return TRUE;
}

static gboolean
allocate_persist_entry(PersistState *persist_state, const gchar *persist_name)
{
  PersistEntryHandle handle = persist_state_alloc_entry(persist_state, persist_name, sizeof(PythonPersistMasterEntry));
  if (!handle)
    {
      PyErr_Format(PyExc_RuntimeError, "Could not allocate persist entry");
      return FALSE;
    }

  PythonPersistMasterEntry *entry = persist_state_map_entry(persist_state, handle);
  entry->version = MASTER_ENTRY_VERSION;
  persist_state_unmap_entry(persist_state, handle);

  return TRUE;
}

static gboolean
prepare_master_entry(PersistState *persist_state, const gchar *persist_name)
{
  gsize size;
  guint8 version;
  PersistEntryHandle handle = persist_state_lookup_entry(persist_state, persist_name, &size, &version);
  if (handle)
    return load_persist_entry(persist_state, handle);
  else
    return allocate_persist_entry(persist_state, persist_name);
}

static int
_persist_type_init(PyObject *s, PyObject *args, PyObject *kwds)
{
  PyPersist *self = (PyPersist *) s;
  const gchar *persist_name = NULL;
  GlobalConfig *cfg = _py_get_config_from_main_module()->cfg;

  static char *kwlist[] = {"persist_name", NULL};

  if (! PyArg_ParseTupleAndKeywords(args, kwds, "s", kwlist, &persist_name))
    return -1;

  self->persist_state = cfg->state;
  if (!self->persist_state)
    {
      msg_error("Attempting to use persist_state while the configuration is not yet initialized, please use Persist() in or after the init() method",
                evt_tag_str("name", persist_name));
      _py_finish_exception_handling();
      PyErr_SetString(PyExc_RuntimeError, "persist_state is not yet available");
      return -1;
    }


  if (g_strstr_len(persist_name, -1, SUBKEY_DELIMITER))
    {
      // Internally, we will store subkeys as persist_name##subkey
      PyErr_Format(PyExc_ValueError, "persist name cannot contain " SUBKEY_DELIMITER);
      return -1;
    }

  if (!prepare_master_entry(self->persist_state, persist_name))
    return -1;

  if (!self->persist_name)
    self->persist_name = g_strdup(persist_name);

  return 0;
}

static void
py_persist_dealloc(PyObject *s)
{
  PyPersist *self =(PyPersist *)s;

  g_free(self->persist_name);
  self->persist_name = NULL;

  py_slng_generic_dealloc(s);
}

static PyMemberDef
py_persist_type_members[] =
{
  {"persist_name", T_STRING, offsetof(PyPersist, persist_name), READONLY},
  {NULL}
};

static gchar *
_build_key(PyPersist *self, const gchar *key)
{
  return g_strdup_printf("%s" SUBKEY_DELIMITER "%s", self->persist_name, key);
}

static gchar *
_lookup_entry(PyPersist *self, const gchar *key, guint8 *type)
{
  gchar *query_key = _build_key(self, key);

  gsize size;
  guint8 version;
  PersistEntryHandle handle = persist_state_lookup_entry(self->persist_state, query_key, &size, &version);
  if (!handle)
    {
      PyErr_Format(PyExc_KeyError, "Persist has no such key: %s", key);
      g_free(query_key);
      return NULL;
    }

  Entry *entry = persist_state_map_entry(self->persist_state, handle);
  *type = entry->type;
  gchar *copy = g_strdup(entry->data);
  persist_state_unmap_entry(self->persist_state, handle);

  g_free(query_key);

  return copy;
};

static PersistEntryHandle
_allocate_persist_entry(PersistState *persist_state, const gchar *key, const gchar *value, gsize value_len)
{
  gsize size;
  guint8 version;
  PersistEntryHandle handle = persist_state_lookup_entry(persist_state, key, &size, &version);
  if (handle && size >= value_len)
    return handle;

  return persist_state_alloc_entry(persist_state, key, value_len);
}

static gchar *
_serialize(guint8 type, PyObject *v)
{
  switch (type)
    {
    case ENTRY_TYPE_STRING:
    {
      const gchar *str;
      py_bytes_or_string_to_string(v, &str);
      return g_strdup(str);
    }
    case ENTRY_TYPE_LONG:
    {
      PyObject *as_str = PyObject_Str(v);
      g_assert(as_str);
      const gchar *as_c_str;
      py_bytes_or_string_to_string(as_str, &as_c_str);
      gchar *result = g_strdup(as_c_str);
      Py_DECREF(as_str);
      return result;
    }
    case ENTRY_TYPE_BYTES:
      return g_strdup(PyBytes_AsString(v));
    default:
      g_assert_not_reached();
    }
}

static gboolean
_store_entry(PyPersist *self, const gchar *key, guint8 type, PyObject *v)
{
  gchar *query_key = _build_key(self, key);
  gchar *value = _serialize(type, v);
  gsize value_len = strlen(value) + 1 + sizeof(type);

  PersistEntryHandle handle = _allocate_persist_entry(self->persist_state, query_key, value, value_len);
  if (!handle)
    {
      g_free(value);
      g_free(query_key);
      return FALSE;
    }

  Entry *entry = persist_state_map_entry(self->persist_state, handle);
  entry->type = type;
  strcpy(entry->data, value);
  persist_state_unmap_entry(self->persist_state, handle);

  g_free(value);
  g_free(query_key);

  return TRUE;
}

static PyObject *
_py_persist_type_get(PyObject *o, PyObject *key)
{
  PyPersist *self = (PyPersist *)o;

  const gchar *name;
  if (!py_bytes_or_string_to_string(key, &name))
    {
      PyErr_SetString(PyExc_TypeError, "key is not a string object");
      return NULL;
    }

  guint8 type;
  gchar *value = _lookup_entry(self, name, &type);

  if (!value)
    {
      PyErr_Format(PyExc_KeyError, "No such name-value pair %s", name);
      return NULL;
    }

  if (type >= ENTRY_TYPE_MAX)
    {
      PyErr_Format(PyExc_RuntimeError, "Unknown data type: %d", (gint)type);
      g_free(value);
      return NULL;
    }

  PyObject *py_value = entry_to_pyobject(type, value);
  g_free(value);
  return py_value;
}

static int
_py_persist_type_set(PyObject *o, PyObject *k, PyObject *v)
{
  PyPersist *self = (PyPersist *)o;
  guint8 type;

  const gchar *key;
  if (!py_bytes_or_string_to_string(k, &key))
    {
      PyErr_SetString(PyExc_TypeError, "key is not a string object");
      return -1;
    }

  if (PyBytes_Check(v))
    type = ENTRY_TYPE_BYTES;
  else if (is_py_obj_bytes_or_string_type(v))
    type = ENTRY_TYPE_STRING;
  else if (PyLong_Check(v))
    type = ENTRY_TYPE_LONG;
  else
    {
      PyErr_SetString(PyExc_TypeError, "Value must be either string, integer or bytes");
      return -1;
    }

  if (!_store_entry(self, key, type, v))
    {
      PyErr_SetString(PyExc_IOError, "value could not be stored");
      return -1;
    }

  return 0;
}

static PyMappingMethods py_persist_type_mapping =
{
  .mp_length = NULL,
  .mp_subscript = (binaryfunc) _py_persist_type_get,
  .mp_ass_subscript = (objobjargproc) _py_persist_type_set
};

static void
_insert_to_dict(gchar *key, gint entry_size, Entry *entry, gpointer *user_data)
{
  const gchar *persist_name = user_data[0];
  PyObject *entries = user_data[1];

  if (!g_str_has_prefix(key, persist_name))
    return;

  gchar *start = g_strstr_len(key, -1, SUBKEY_DELIMITER);
  if (!start)
    return;

  if (entry->type >= ENTRY_TYPE_MAX)
    return;

  PyObject *key_object = py_string_from_string(start + strlen(SUBKEY_DELIMITER), -1);
  PyObject *value_object = entry_to_pyobject(entry->type, entry->data);
  PyDict_SetItem(entries, key_object, value_object);
  Py_XDECREF(key_object);
  Py_XDECREF(value_object);
}

PyObject *py_persist_type_iter(PyObject *o)
{
  PyPersist *self = (PyPersist *)o;

  PyObject *entries = PyDict_New();
  persist_state_foreach_entry(self->persist_state, (PersistStateForeachFunc)_insert_to_dict,
                              (gpointer [])
  {
    self->persist_name, entries
  });

  PyObject *iter = PyObject_GetIter(entries);
  Py_DECREF(entries);
  return iter;
}

PyTypeObject py_persist_type =
{
  PyVarObject_HEAD_INIT(&PyType_Type, 0)
  .tp_name = "Persist",
  .tp_basicsize = sizeof(PyPersist),
  .tp_dealloc = py_persist_dealloc,
  .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
  .tp_doc = "Persist class encapsulates persist handling",
  .tp_new = PyType_GenericNew,
  .tp_init = _persist_type_init,
  .tp_members = py_persist_type_members,
  .tp_as_mapping = &py_persist_type_mapping,
  .tp_iter = &py_persist_type_iter,
  0,
};

void
py_persist_global_init(void)
{
  PyType_Ready(&py_persist_type);
  PyModule_AddObject(PyImport_AddModule("_syslogng"), "Persist", (PyObject *) &py_persist_type);
}