Skip to content

Commit

Permalink
parser: Support system timezone in Time_Offset
Browse files Browse the repository at this point in the history
Add the 'System' option to Time_Offset that uses the system timezone
to compute the UTC offset during startup.

As proposed in #593

Signed-off-by: Sijmen Huizenga <sijmenhuizenga@gmail.com>
  • Loading branch information
SijmenHuizenga committed Sep 30, 2023
1 parent b7ee1e8 commit 8a0860a
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
10 changes: 10 additions & 0 deletions src/flb_parser.c
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@
#include <sys/stat.h>
#include <limits.h>
#include <string.h>
#include <time.h>

static inline uint32_t digits10(uint64_t v) {
if (v < 10) return 1;
Expand Down Expand Up @@ -1009,6 +1010,15 @@ int flb_parser_tzone_offset(const char *str, int len, int *tmdiff)
return 0;
}

/* Check system timezones */
if (*p == 'S') {
time_t currentTime = time(NULL);
struct tm localTime = {0};
localtime_r(&currentTime, &localTime);
*tmdiff = localTime.tm_gmtoff;
return 0;
}

/* Unexpected timezone string */
if (*p != '+' && *p != '-') {
*tmdiff = 0;
Expand Down
36 changes: 36 additions & 0 deletions tests/internal/parser.c
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@ struct tz_check tz_entries_ok[] = {
{"-0600", -21600},
{"-06:00", -21600},
{"Z", 0},
// System is mocked to timezone "HST" is -10 hours
{"System", -36000},
};

struct tz_check tz_entries_error[] = {
Expand Down Expand Up @@ -126,6 +128,35 @@ int flb_parser_regex_do(struct flb_parser *parser,
void **out_buf, size_t *out_size,
struct flb_time *out_time);

static char* mock_timezone(char *tz)
{
char *original_tz = getenv("TZ");
if (original_tz) {
original_tz = strdup(original_tz);
if (!original_tz) {
perror("Failed to allocate memory for original_tz");
exit(EXIT_FAILURE);
}
}

setenv("TZ", tz, 1);
tzset();

return original_tz;
}

static void undo_mock_timezone(char *original_tz)
{
if (original_tz) {
setenv("TZ", original_tz, 1);
} else {
unsetenv("TZ");
}
tzset();
free(original_tz);
}


/* Parse timezone string and get the offset */
void test_parser_tzone_offset()
{
Expand All @@ -135,6 +166,9 @@ void test_parser_tzone_offset()
int diff;
struct tz_check *t;

/* Hawaii Standard Time chosen for not having daylight saving time */
char *original_timezone = mock_timezone("HST");

/* Valid offsets */
for (i = 0; i < sizeof(tz_entries_ok) / sizeof(struct tz_check); i++) {
t = &tz_entries_ok[i];
Expand All @@ -154,6 +188,8 @@ void test_parser_tzone_offset()
ret = flb_parser_tzone_offset(t->val, len, &diff);
TEST_CHECK(ret != 0);
}

undo_mock_timezone(original_timezone);
}

static void load_json_parsers(struct flb_config *config)
Expand Down

0 comments on commit 8a0860a

Please sign in to comment.