File: object-datetime.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 (388 lines) | stat: -rw-r--r-- 11,386 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
/*
 * Copyright (c) 2023 Balazs Scheidler <balazs.scheidler@axoflow.com>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; 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 "object-datetime.h"
#include "scratch-buffers.h"
#include "str-format.h"
#include "str-utils.h"
#include "timeutils/wallclocktime.h"
#include "timeutils/conv.h"
#include "timeutils/misc.h"
#include "timeutils/format.h"
#include "filterx/object-string.h"
#include "filterx/object-primitive.h"
#include "filterx/object-message-value.h"
#include "filterx/object-null.h"
#include "filterx/expr-literal.h"
#include "generic-number.h"
#include "filterx/filterx-eval.h"
#include "filterx-globals.h"
#include "compat/json.h"

#define FILTERX_FUNC_STRPTIME_USAGE "Usage: strptime(time_str, format_str_1, ..., format_str_N)"

typedef struct _FilterXDateTime
{
  FilterXObject super;
  UnixTime ut;
} FilterXDateTime;

static gboolean
_truthy(FilterXObject *s)
{
  return TRUE;
}

/* FIXME: delegate formatting and parsing to UnixTime */
static void
_convert_unix_time_to_string(const UnixTime *ut, GString *result)
{

  format_int64_padded(result, -1, ' ', 10, ut->ut_sec);
  g_string_append_c(result, '.');
  format_uint64_padded(result, 6, '0', 10, ut->ut_usec);
  if (ut->ut_gmtoff != -1)
    {
      if (ut->ut_gmtoff >= 0)
        g_string_append_c(result, '+');
      else
        g_string_append_c(result, '-');

      format_int64_padded(result, 2, '0', 10, ut->ut_gmtoff / 3600);
      g_string_append_c(result, ':');
      format_int64_padded(result, 2, '0', 10, (ut->ut_gmtoff % 3600) / 60);
    }
}

static gboolean
_marshal(FilterXObject *s, GString *repr, LogMessageValueType *t)
{
  FilterXDateTime *self = (FilterXDateTime *) s;

  *t = LM_VT_DATETIME;
  _convert_unix_time_to_string(&self->ut, repr);
  return TRUE;
}

static gboolean
_map_to_json(FilterXObject *s, struct json_object **object, FilterXObject **assoc_object)
{
  FilterXDateTime *self = (FilterXDateTime *) s;
  GString *time_stamp = scratch_buffers_alloc();

  _convert_unix_time_to_string(&self->ut, time_stamp);

  *object = json_object_new_string_len(time_stamp->str, time_stamp->len);
  return TRUE;
}

FilterXObject *
filterx_datetime_new(const UnixTime *ut)
{
  FilterXDateTime *self = g_new0(FilterXDateTime, 1);

  filterx_object_init_instance(&self->super, &FILTERX_TYPE_NAME(datetime));
  self->ut = *ut;
  return &self->super;
}

UnixTime
filterx_datetime_get_value(FilterXObject *s)
{
  FilterXDateTime *self = (FilterXDateTime *) s;

  return self->ut;
}


FilterXObject *
filterx_typecast_datetime(GPtrArray *args)
{
  FilterXObject *object = filterx_typecast_get_arg(args,
                                                   "FilterX: Failed to create datetime object: invalid number of arguments. "
                                                   "Usage: datetime($isodate_str), datetime($unix_int_ms) or datetime($unix_float_s)");
  if (!object)
    return NULL;

  if (filterx_object_is_type(object, &FILTERX_TYPE_NAME(datetime)))
    {
      filterx_object_ref(object);
      return object;
    }
  else if (filterx_object_is_type(object, &FILTERX_TYPE_NAME(integer)))
    {
      GenericNumber gn = filterx_primitive_get_value(object);
      int64_t val = gn_as_int64(&gn);
      UnixTime ut = unix_time_from_unix_epoch(val);
      return filterx_datetime_new(&ut);
    }
  else if (filterx_object_is_type(object, &FILTERX_TYPE_NAME(double)))
    {
      GenericNumber gn = filterx_primitive_get_value(object);
      double val = gn_as_double(&gn);
      UnixTime ut = unix_time_from_unix_epoch((gint64)(val * USEC_PER_SEC));
      return filterx_datetime_new(&ut);
    }
  else if (filterx_object_is_type(object, &FILTERX_TYPE_NAME(string)))
    {
      return filterx_typecast_datetime_isodate(args);
    }
  msg_error("filterx: invalid typecast",
            evt_tag_str("from", object->type->name),
            evt_tag_str("to", "datetime"));
  return NULL;
}

FilterXObject *
filterx_typecast_datetime_isodate(GPtrArray *args)
{
  FilterXObject *object = filterx_typecast_get_arg(args,
                                                   "FilterX: Failed to create datetime object: invalid number of arguments. "
                                                   "Usage: datetime($isodate_str), datetime($unix_int_ms) or datetime($unix_float_s)");
  if (!object)
    return NULL;

  if (!filterx_object_is_type(object, &FILTERX_TYPE_NAME(string)))
    return NULL;

  UnixTime ut = UNIX_TIME_INIT;
  WallClockTime wct = WALL_CLOCK_TIME_INIT;

  gsize len;
  const gchar *timestr = filterx_string_get_value(object, &len);
  if (len == 0)
    {
      msg_error("filterx: empty time string",
                evt_tag_str("from", object->type->name),
                evt_tag_str("to", "datetime"),
                evt_tag_str("format", "isodate"));
      return NULL;
    }

  gchar *end = wall_clock_time_strptime(&wct, datefmt_isodate, timestr);
  if (end && *end != 0)
    {
      msg_error("filterx: unable to parse time",
                evt_tag_str("from", object->type->name),
                evt_tag_str("to", "datetime"),
                evt_tag_str("format", "isodate"),
                evt_tag_str("time_string", timestr),
                evt_tag_str("end", end));
      return NULL;
    }

  convert_wall_clock_time_to_unix_time(&wct, &ut);
  return filterx_datetime_new(&ut);
}

gboolean
datetime_repr(const UnixTime *ut, GString *repr)
{
  WallClockTime wct = WALL_CLOCK_TIME_INIT;
  convert_unix_time_to_wall_clock_time(ut, &wct);
  append_format_wall_clock_time(&wct, repr, TS_FMT_ISO, 3);
  return TRUE;
}

static gboolean
_repr(FilterXObject *s, GString *repr)
{
  UnixTime ut = filterx_datetime_get_value(s);
  return datetime_repr(&ut, repr);
}

const gchar *
_strptime_get_time_str_from_object(FilterXObject *obj, gsize *len)
{
  if (filterx_object_is_type(obj, &FILTERX_TYPE_NAME(string)))
    return filterx_string_get_value(obj, len);

  if (filterx_object_is_type(obj, &FILTERX_TYPE_NAME(message_value)))
    {
      if (filterx_message_value_get_type(obj) == LM_VT_STRING)
        return filterx_message_value_get_value(obj, len);
    }

  return NULL;
}


typedef struct FilterXFunctionStrptime_
{
  FilterXFunction super;
  FilterXExpr *time_str_expr;
  GPtrArray *formats;
} FilterXFunctionStrptime;

static FilterXObject *
_strptime_eval(FilterXExpr *s)
{
  FilterXFunctionStrptime *self = (FilterXFunctionStrptime *) s;

  FilterXObject *result = NULL;

  gsize time_str_len;
  FilterXObject *time_str_obj = filterx_expr_eval(self->time_str_expr);
  if (!time_str_obj)
    {
      filterx_eval_push_error("Failed to evaluate first argument. " FILTERX_FUNC_STRPTIME_USAGE, s, NULL);
      return NULL;
    }

  const gchar *time_str = _strptime_get_time_str_from_object(time_str_obj, &time_str_len);
  filterx_object_unref(time_str_obj);

  if (!time_str)
    {
      filterx_eval_push_error("First argument must be string typed. " FILTERX_FUNC_STRPTIME_USAGE, s, NULL);
      return NULL;
    }

  WallClockTime wct = WALL_CLOCK_TIME_INIT;
  UnixTime ut = UNIX_TIME_INIT;
  gchar *end = NULL;

  for (guint i = 0; i < self->formats->len; i++)
    {
      const gchar *format = g_ptr_array_index(self->formats, i);
      end = wall_clock_time_strptime(&wct, format, time_str);
      if (!end)
        {
          msg_debug("filterx: unable to parse time",
                    evt_tag_str("time_string", time_str),
                    evt_tag_str("format", format));
        }
      else
        break;
    }

  if (end)
    {
      convert_wall_clock_time_to_unix_time(&wct, &ut);
      result = filterx_datetime_new(&ut);
    }
  else
    result = filterx_null_new();

  return result;
}

static void
_strptime_free(FilterXExpr *s)
{
  FilterXFunctionStrptime *self = (FilterXFunctionStrptime *) s;

  filterx_expr_unref(self->time_str_expr);
  g_ptr_array_free(self->formats, TRUE);
  filterx_function_free_method(&self->super);
}

static GPtrArray *
_extract_strptime_formats(FilterXFunctionArgs *args, GError **error)
{
  guint64 num_formats = filterx_function_args_len(args) - 1;
  GPtrArray *formats = g_ptr_array_new_full(num_formats, g_free);

  for (guint64 i = 0; i < num_formats; i++)
    {
      const gchar *format = filterx_function_args_get_literal_string(args, i+1, NULL);
      if (!format)
        {
          g_set_error(error, FILTERX_FUNCTION_ERROR, FILTERX_FUNCTION_ERROR_CTOR_FAIL,
                      "format_str_%" G_GUINT64_FORMAT " argument must be string literal. " FILTERX_FUNC_STRPTIME_USAGE,
                      i+1);
          goto error;
        }

      g_ptr_array_add(formats, g_strdup(format));
    }

  return formats;

error:
  g_ptr_array_free(formats, TRUE);
  return NULL;
}

static FilterXExpr *
_extract_time_str_expr(FilterXFunctionArgs *args, GError **error)
{
  FilterXExpr *time_str_expr = filterx_function_args_get_expr(args, 0);
  if (!time_str_expr)
    {
      g_set_error(error, FILTERX_FUNCTION_ERROR, FILTERX_FUNCTION_ERROR_CTOR_FAIL,
                  "argument must be set: time_str. " FILTERX_FUNC_STRPTIME_USAGE);
      return NULL;
    }

  return time_str_expr;
}

static gboolean
_extract_args(FilterXFunctionStrptime *self, FilterXFunctionArgs *args, GError **error)
{
  gsize len = filterx_function_args_len(args);
  if (len < 2)
    {
      g_set_error(error, FILTERX_FUNCTION_ERROR, FILTERX_FUNCTION_ERROR_CTOR_FAIL,
                  "invalid number of arguments. " FILTERX_FUNC_STRPTIME_USAGE);
      return FALSE;
    }

  self->time_str_expr = _extract_time_str_expr(args, error);
  if (!self->time_str_expr)
    return FALSE;

  self->formats = _extract_strptime_formats(args, error);
  if (!self->formats)
    return FALSE;

  return TRUE;
}

/* Takes reference of args */
FilterXFunction *
filterx_function_strptime_new(const gchar *function_name, FilterXFunctionArgs *args, GError **error)
{
  FilterXFunctionStrptime *self = g_new0(FilterXFunctionStrptime, 1);
  filterx_function_init_instance(&self->super, function_name);
  self->super.super.eval = _strptime_eval;
  self->super.super.free_fn = _strptime_free;

  if (!_extract_args(self, args, error))
    goto error;

  filterx_function_args_free(args);
  return &self->super;

error:
  filterx_function_args_free(args);
  filterx_expr_unref(&self->super.super);
  return NULL;
}

FILTERX_DEFINE_TYPE(datetime, FILTERX_TYPE_NAME(object),
                    .truthy = _truthy,
                    .map_to_json = _map_to_json,
                    .marshal = _marshal,
                    .repr = _repr,
                   );