File: numeric-funcs.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 (531 lines) | stat: -rw-r--r-- 14,251 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
/*
 * Copyright (c) 2002-2014 Balabit
 * Copyright (c) 1998-2012 Balázs Scheidler
 *
 * 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 "generic-number.h"
#include <math.h>

typedef gboolean (*AggregateFunc)(gpointer, gint64);

void
format_number(GString *result, LogMessageValueType *type, const GenericNumber *n)
{
  if (n->type == GN_INT64)
    {
      *type = LM_VT_INTEGER;
      format_int64_padded(result, 0, ' ', 10, gn_as_int64(n));
      return;
    }

  *type = LM_VT_DOUBLE;
  g_string_append_printf(result, "%.*f", n->precision, gn_as_double(n));
}

void
format_nan(GString *result, LogMessageValueType *type)
{
  g_string_append_len(result, "NaN", 3);
  *type = LM_VT_DOUBLE;
}

static gboolean
tf_num_parse(gint argc, GString *argv[],
             const gchar *func_name, GenericNumber *n, GenericNumber *m)
{
  if (argc != 2)
    {
      msg_debug("Template function requires two arguments.",
                evt_tag_str("function", func_name));
      return FALSE;
    }

  if (!parse_generic_number(argv[0]->str, n))
    {
      msg_debug("Parsing failed, template function's first argument is not a number",
                evt_tag_str("function", func_name),
                evt_tag_str("arg1", argv[0]->str));
      return FALSE;
    }

  if (!parse_generic_number(argv[1]->str, m))
    {
      msg_debug("Parsing failed, template function's second argument is not a number",
                evt_tag_str("function", func_name),
                evt_tag_str("arg2", argv[1]->str));
      return FALSE;
    }

  return TRUE;
}

static void
tf_num_plus(LogMessage *msg, gint argc, GString *argv[], GString *result, LogMessageValueType *type)
{
  GenericNumber n, m, res;

  if (!tf_num_parse(argc, argv, "+", &n, &m))
    {
      format_nan(result, type);
      return;
    }

  if (n.type == GN_INT64 && m.type == GN_INT64)
    {
      gn_set_int64(&res, gn_as_int64(&n) + gn_as_int64(&m));
    }
  else
    {
      gn_set_double(&res, gn_as_double(&n) + gn_as_double(&m), -1);
    }

  format_number(result, type, &res);
}

TEMPLATE_FUNCTION_SIMPLE(tf_num_plus);

static void
tf_num_minus(LogMessage *msg, gint argc, GString *argv[], GString *result, LogMessageValueType *type)
{
  GenericNumber n, m, res;

  if (!tf_num_parse(argc, argv, "-", &n, &m))
    {
      format_nan(result, type);
      return;
    }

  if (n.type == GN_INT64 && m.type == GN_INT64)
    {
      gn_set_int64(&res, gn_as_int64(&n) - gn_as_int64(&m));
    }
  else
    {
      gn_set_double(&res, gn_as_double(&n) - gn_as_double(&m), -1);
    }

  format_number(result, type, &res);
}

TEMPLATE_FUNCTION_SIMPLE(tf_num_minus);

static void
tf_num_multi(LogMessage *msg, gint argc, GString *argv[], GString *result, LogMessageValueType *type)
{
  GenericNumber n, m, res;

  if (!tf_num_parse(argc, argv, "*", &n, &m))
    {
      format_nan(result, type);
      return;
    }

  if (n.type == GN_INT64 && m.type == GN_INT64)
    {
      gn_set_int64(&res, gn_as_int64(&n) * gn_as_int64(&m));
    }
  else
    {
      gn_set_double(&res, gn_as_double(&n) * gn_as_double(&m), -1);
    }

  format_number(result, type, &res);
}

TEMPLATE_FUNCTION_SIMPLE(tf_num_multi);

static void
tf_num_div(LogMessage *msg, gint argc, GString *argv[], GString *result, LogMessageValueType *type)
{
  GenericNumber n, m, res;

  if (!tf_num_parse(argc, argv, "/", &n, &m) || gn_is_zero(&m))
    {
      format_nan(result, type);
      return;
    }

  if (n.type == GN_INT64 && m.type == GN_INT64)
    {
      gn_set_int64(&res, gn_as_int64(&n) / gn_as_int64(&m));
    }
  else
    {
      gn_set_double(&res, gn_as_double(&n) / gn_as_double(&m), -1);
    }

  format_number(result, type, &res);
}

TEMPLATE_FUNCTION_SIMPLE(tf_num_div);

static void
tf_num_mod(LogMessage *msg, gint argc, GString *argv[], GString *result, LogMessageValueType *type)
{
  GenericNumber n, m, res;

  if (!tf_num_parse(argc, argv, "%", &n, &m) || gn_is_zero(&m))
    {
      format_nan(result, type);
      return;
    }

  if (n.type == GN_INT64 && m.type == GN_INT64)
    {
      gn_set_int64(&res, gn_as_int64(&n) % gn_as_int64(&m));
    }
  else
    {
      gn_set_double(&res, fmod(gn_as_double(&n), gn_as_double(&m)), -1);
    }

  format_number(result, type, &res);
}

TEMPLATE_FUNCTION_SIMPLE(tf_num_mod);

static void
tf_num_round(LogMessage *msg, gint argc, GString *argv[], GString *result, LogMessageValueType *type)
{
  GenericNumber n;
  gint64 precision = 0;

  if (argc < 1 || argc > 2)
    {
      msg_debug("Template function requires exactly one or two arguments.",
                evt_tag_str("function", "round"));
      format_nan(result, type);
      return;
    }

  if (!parse_generic_number(argv[0]->str, &n))
    {
      msg_debug("Parsing failed, template function's first argument is not a number",
                evt_tag_str("function", "round"),
                evt_tag_str("arg1", argv[0]->str));
      format_nan(result, type);
      return;
    }

  if (argc > 1)
    {
      if (!parse_int64(argv[1]->str, &precision))
        {
          msg_debug("Parsing failed, template function's second argument is not a number",
                    evt_tag_str("function", "round"),
                    evt_tag_str("arg2", argv[1]->str));
          format_nan(result, type);
          return;
        }

      if (precision < 0 || precision > 20)
        {
          msg_debug("Parsing failed, precision is not in the supported range (0..20)",
                    evt_tag_str("function", "round"),
                    evt_tag_str("arg2", argv[1]->str));
          format_nan(result, type);
          return;
        }
    }

  double multiplier = pow(10, precision);
  double res = round(gn_as_double(&n) * multiplier) / multiplier;
  gn_set_double(&n, res, -1);

  /*
   * gn_set_double() resets the precision, so assign it now.
   */
  n.precision = precision;

  format_number(result, type, &n);
}

TEMPLATE_FUNCTION_SIMPLE(tf_num_round);

static void
tf_num_ceil(LogMessage *msg, gint argc, GString *argv[], GString *result, LogMessageValueType *type)
{
  GenericNumber n;

  if (argc != 1)
    {
      msg_debug("Template function requires one argument.",
                evt_tag_str("function", "ceil"));
      format_nan(result, type);
      return;
    }

  if (!parse_generic_number(argv[0]->str, &n))
    {
      msg_debug("Parsing failed, template function's first argument is not a number",
                evt_tag_str("function", "ceil"),
                evt_tag_str("arg1", argv[0]->str));
      format_nan(result, type);
      return;
    }

  *type = LM_VT_INTEGER;

  gdouble number = ceil(gn_as_double(&n));
  gn_set_int64(&n, (gint64) number);
  format_number(result, type, &n);
}

TEMPLATE_FUNCTION_SIMPLE(tf_num_ceil);

static void
tf_num_floor(LogMessage *msg, gint argc, GString *argv[], GString *result, LogMessageValueType *type)
{
  GenericNumber n;

  if (argc != 1)
    {
      msg_debug("Template function requires one argument.",
                evt_tag_str("function", "floor"));
      format_nan(result, type);
      return;
    }

  if (!parse_generic_number(argv[0]->str, &n))
    {
      msg_debug("Parsing failed, template function's first argument is not a number",
                evt_tag_str("function", "floor"),
                evt_tag_str("arg1", argv[0]->str));
      format_nan(result, type);
      return;
    }

  *type = LM_VT_INTEGER;

  gdouble number = floor(gn_as_double(&n));
  gn_set_int64(&n, (gint64) number);
  format_number(result, type, &n);
}

TEMPLATE_FUNCTION_SIMPLE(tf_num_floor);

static gboolean
_tf_num_parse_arg_with_message(const TFSimpleFuncState *state,
                               LogMessage *message,
                               const LogTemplateInvokeArgs *args,
                               gint64 *number)
{
  GString *formatted_template = scratch_buffers_alloc();
  gint on_error = args->options->opts->on_error;

  log_template_format(state->argv_templates[0], message, args->options, formatted_template);

  if (!parse_int64(formatted_template->str, number))
    {
      if (!(on_error & ON_ERROR_SILENT))
        msg_error("Parsing failed, template function's argument is not a number",
                  evt_tag_str("arg", formatted_template->str));
      return FALSE;
    }

  return TRUE;
}

static gboolean
tf_num_prepare(LogTemplateFunction *self, gpointer s, LogTemplate *parent,
               gint argc, gchar *argv[], GError **error)
{
  g_return_val_if_fail(error == NULL || *error == NULL, FALSE);

  if (argc != 2)
    {
      g_set_error(error, LOG_TEMPLATE_ERROR, LOG_TEMPLATE_ERROR_COMPILE,
                  "$(%s) requires only one argument", argv[0]);
      return FALSE;
    }

  return tf_simple_func_prepare(self, s, parent, argc, argv, error);
}

static gint
_tf_num_filter_iterate(const TFSimpleFuncState *state,
                       const LogTemplateInvokeArgs *args,
                       gint message_index,
                       AggregateFunc aggregate,
                       gpointer accumulator)
{
  for (; message_index < args->num_messages; message_index++)
    {
      LogMessage *message = args->messages[message_index];
      gint64 number;
      if ((_tf_num_parse_arg_with_message(state, message, args, &number) &&
           (!aggregate(accumulator, number))))
        return message_index;
    }

  return -1;
}

static gboolean
_tf_num_filter(const TFSimpleFuncState *state,
               const LogTemplateInvokeArgs *args,
               AggregateFunc start,
               AggregateFunc aggregate,
               gpointer accumulator)
{
  gint first = _tf_num_filter_iterate(state, args, 0, start, accumulator);
  if (first < 0)
    return FALSE;

  _tf_num_filter_iterate(state, args, first + 1, aggregate, accumulator);
  return TRUE;
}

static gboolean
_tf_num_store_first(gpointer accumulator, gint64 element)
{
  gint64 *acc = (gint64 *)accumulator;
  *acc = element;
  return FALSE;
}

static void
_tf_num_aggregation(TFSimpleFuncState *state, const LogTemplateInvokeArgs *args,
                    AggregateFunc aggregate, GString *result, LogMessageValueType *type)
{
  gint64 accumulator;

  if (!_tf_num_filter(state, args, _tf_num_store_first, aggregate, &accumulator))
    {
      /* invalid arguments, empty string */
      *type = LM_VT_NULL;
      return;
    }

  *type = LM_VT_INTEGER;
  format_int64_padded(result, 0, ' ', 10, accumulator);
}

static gboolean
_tf_num_sum(gpointer accumulator, gint64 element)
{
  gint64 *acc = (gint64 *)accumulator;
  *acc += element;
  return TRUE;
}

static void
tf_num_sum_call(LogTemplateFunction *self, gpointer s,
                const LogTemplateInvokeArgs *args, GString *result, LogMessageValueType *type)
{
  _tf_num_aggregation((TFSimpleFuncState *) s, args, _tf_num_sum, result, type);
}

TEMPLATE_FUNCTION(TFSimpleFuncState, tf_num_sum,
                  tf_num_prepare, NULL, tf_num_sum_call,
                  tf_simple_func_free_state, NULL);

static gboolean
_tf_num_minimum(gpointer accumulator, gint64 element)
{
  gint64 *acc = (gint64 *)accumulator;
  if (element < *acc)
    *acc = element;

  return TRUE;
}

static void
tf_num_min_call(LogTemplateFunction *self, gpointer s,
                const LogTemplateInvokeArgs *args, GString *result, LogMessageValueType *type)
{
  _tf_num_aggregation((TFSimpleFuncState *) s, args, _tf_num_minimum, result, type);
}

TEMPLATE_FUNCTION(TFSimpleFuncState, tf_num_min,
                  tf_num_prepare, NULL, tf_num_min_call,
                  tf_simple_func_free_state, NULL);

static gboolean
_tf_num_maximum(gpointer accumulator, gint64 element)
{
  gint64 *acc = (gint64 *)accumulator;
  if (element > *acc)
    *acc = element;

  return TRUE;
}

static void
tf_num_max_call(LogTemplateFunction *self, gpointer s,
                const LogTemplateInvokeArgs *args, GString *result, LogMessageValueType *type)
{
  _tf_num_aggregation((TFSimpleFuncState *) s, args, _tf_num_maximum, result, type);
}

TEMPLATE_FUNCTION(TFSimpleFuncState, tf_num_max,
                  tf_num_prepare, NULL, tf_num_max_call,
                  tf_simple_func_free_state, NULL);

typedef struct _AverageState
{
  gint count;
  gint64 sum;
} AverageState;

static gboolean
_tf_num_store_average_first(gpointer accumulator, gint64 element)
{
  AverageState *state = (AverageState *) accumulator;
  state->count = 1;
  state->sum = element;
  return FALSE;
}

static gboolean
_tf_num_average(gpointer accumulator, gint64 element)
{
  AverageState *state = (AverageState *) accumulator;
  ++state->count;
  state->sum += element;
  return TRUE;
}

static void
tf_num_average_call(LogTemplateFunction *self, gpointer s,
                    const LogTemplateInvokeArgs *args, GString *result, LogMessageValueType *type)
{
  TFSimpleFuncState *state = (TFSimpleFuncState *)s;
  AverageState accumulator = {0, 0};

  if (!_tf_num_filter(state, args, _tf_num_store_average_first, _tf_num_average, &accumulator))
    {
      *type = LM_VT_NULL;
      return;
    }

  /* _tf_num_filter() would return FALSE if there are no elements, so
   * handling this case with assert is fine */

  g_assert(accumulator.count > 0);
  *type = LM_VT_INTEGER;
  gint64 mean = accumulator.sum / accumulator.count;
  format_int64_padded(result, 0, ' ', 10, mean);
}

TEMPLATE_FUNCTION(TFSimpleFuncState, tf_num_average,
                  tf_num_prepare, NULL, tf_num_average_call,
                  tf_simple_func_free_state, NULL);