Coverage Report

Created: 2026-05-13 01:09

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/util/timezone_utils.cpp
Line
Count
Source
1
// Licensed to the Apache Software Foundation (ASF) under one
2
// or more contributor license agreements.  See the NOTICE file
3
// distributed with this work for additional information
4
// regarding copyright ownership.  The ASF licenses this file
5
// to you under the Apache License, Version 2.0 (the
6
// "License"); you may not use this file except in compliance
7
// with the License.  You may obtain a copy of the License at
8
//
9
//   http://www.apache.org/licenses/LICENSE-2.0
10
//
11
// Unless required by applicable law or agreed to in writing,
12
// software distributed under the License is distributed on an
13
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
// KIND, either express or implied.  See the License for the
15
// specific language governing permissions and limitations
16
// under the License.
17
18
#include "util/timezone_utils.h"
19
20
#include <cctz/civil_time.h>
21
#include <cctz/time_zone.h>
22
#include <fcntl.h>
23
#include <glog/logging.h>
24
#include <re2/re2.h>
25
#include <re2/stringpiece.h>
26
#include <sys/mman.h>
27
#include <sys/stat.h>
28
#include <sys/types.h>
29
#include <unistd.h>
30
31
#include <algorithm>
32
#include <boost/algorithm/string.hpp>
33
#include <boost/algorithm/string/case_conv.hpp>
34
#include <cctype>
35
#include <chrono>
36
#include <cstdlib>
37
#include <filesystem>
38
#include <memory>
39
#include <string>
40
#include <string_view>
41
42
#include "common/exception.h"
43
#include "common/logging.h"
44
#include "common/status.h"
45
46
using boost::algorithm::to_lower_copy;
47
48
namespace fs = std::filesystem;
49
50
namespace doris {
51
52
using ZoneList = std::unordered_map<std::string, cctz::time_zone>;
53
54
RE2 time_zone_offset_format_reg(R"(^[+-]{1}\d{2}\:\d{2}$)"); // visiting is thread-safe
55
56
// for ut, make it never nullptr.
57
std::unique_ptr<ZoneList> lower_zone_cache_ = std::make_unique<ZoneList>();
58
59
const std::string TimezoneUtils::default_time_zone = "+08:00";
60
static const char* tzdir = "/usr/share/zoneinfo"; // default value, may change by TZDIR env var
61
62
6
void TimezoneUtils::clear_timezone_caches() {
63
6
    lower_zone_cache_->clear();
64
6
}
65
2
size_t TimezoneUtils::cache_size() {
66
2
    return lower_zone_cache_->size();
67
2
}
68
69
144k
static bool parse_save_name_tz(const std::string& tz_name) {
70
144k
    cctz::time_zone tz;
71
144k
    PROPAGATE_FALSE(cctz::load_time_zone(tz_name, &tz));
72
143k
    lower_zone_cache_->emplace(to_lower_copy(tz_name), tz);
73
143k
    return true;
74
144k
}
75
76
242
void TimezoneUtils::load_timezones_to_cache() {
77
242
    std::string base_str;
78
    // try get from system
79
242
    char* tzdir_env = std::getenv("TZDIR");
80
242
    if (tzdir_env && *tzdir_env) {
81
0
        tzdir = tzdir_env;
82
0
    }
83
84
242
    base_str = tzdir;
85
242
    base_str += '/';
86
87
242
    const auto root_path = fs::path {base_str};
88
242
    if (!exists(root_path)) {
89
0
        throw Exception(Status::FatalError("Cannot find system tzfile. Doris exiting!"));
90
0
    }
91
92
242
    std::set<std::string> ignore_paths = {"posix", "right"}; // duplications. ignore them.
93
94
150k
    for (fs::recursive_directory_iterator it {base_str}; it != end(it); it++) {
95
150k
        const auto& dir_entry = *it;
96
150k
        try {
97
150k
            if (dir_entry.is_regular_file() ||
98
150k
                (dir_entry.is_symlink() && is_regular_file(read_symlink(dir_entry)))) {
99
144k
                auto tz_name = dir_entry.path().string().substr(base_str.length());
100
144k
                if (!parse_save_name_tz(tz_name)) {
101
1.21k
                    LOG(WARNING) << "Meet illegal tzdata file: " << tz_name << ". skipped";
102
1.21k
                }
103
144k
            } else if (dir_entry.is_directory() &&
104
5.32k
                       ignore_paths.contains(dir_entry.path().filename())) {
105
484
                it.disable_recursion_pending();
106
484
            }
107
150k
        } catch (const fs::filesystem_error& e) {
108
            // maybe symlink loop or to nowhere...
109
0
            LOG(WARNING) << "filesystem error when loading timezone file from " << dir_entry.path()
110
0
                         << ": " << e.what();
111
0
        }
112
150k
    }
113
    // some special cases. Z = Zulu. CST = Asia/Shanghai
114
242
    if (auto it = lower_zone_cache_->find("zulu"); it != lower_zone_cache_->end()) {
115
242
        lower_zone_cache_->emplace("z", it->second);
116
242
    }
117
242
    if (auto it = lower_zone_cache_->find("asia/shanghai"); it != lower_zone_cache_->end()) {
118
242
        lower_zone_cache_->emplace("cst", it->second);
119
242
    }
120
121
242
    lower_zone_cache_->erase("lmt"); // local mean time for every timezone
122
123
242
    load_offsets_to_cache();
124
242
    LOG(INFO) << "Preloaded" << lower_zone_cache_->size() << " timezones.";
125
242
}
126
127
20.9k
static std::string to_hour_string(int arg) {
128
20.9k
    if (arg < 0 && arg > -10) { // -9 to -1
129
6.99k
        return std::string {"-0"} + std::to_string(std::abs(arg));
130
13.9k
    } else if (arg >= 0 && arg < 10) { //0 to 9
131
7.77k
        return std::string {"0"} + std::to_string(arg);
132
7.77k
    }
133
6.21k
    return std::to_string(arg);
134
20.9k
}
135
136
259
void TimezoneUtils::load_offsets_to_cache() {
137
259
    static constexpr int supported_minutes[] = {0, 30, 45};
138
7.25k
    for (int hour = -12; hour <= +14; hour++) {
139
20.9k
        for (int minute : supported_minutes) {
140
20.9k
            char min_str[3];
141
20.9k
            snprintf(min_str, sizeof(min_str), "%02d", minute);
142
20.9k
            std::string offset_str = (hour >= 0 ? "+" : "") + to_hour_string(hour) + ':' + min_str;
143
20.9k
            cctz::time_zone result;
144
20.9k
            parse_tz_offset_string(offset_str, result);
145
20.9k
            lower_zone_cache_->emplace(offset_str, result);
146
20.9k
        }
147
6.99k
    }
148
    // -00 for hour is also valid
149
259
    std::string offset_str = "-00:00";
150
259
    cctz::time_zone result;
151
259
    parse_tz_offset_string(offset_str, result);
152
259
    lower_zone_cache_->emplace(offset_str, result);
153
259
    offset_str = "-00:30";
154
259
    parse_tz_offset_string(offset_str, result);
155
259
    lower_zone_cache_->emplace(offset_str, result);
156
259
    offset_str = "-00:45";
157
259
    parse_tz_offset_string(offset_str, result);
158
259
    lower_zone_cache_->emplace(offset_str, result);
159
259
}
160
161
181k
bool TimezoneUtils::find_cctz_time_zone(const std::string& timezone, cctz::time_zone& ctz) {
162
181k
    if (auto it = lower_zone_cache_->find(to_lower_copy(timezone)); it != lower_zone_cache_->end())
163
132k
            [[likely]] {
164
132k
        ctz = it->second;
165
132k
        return true;
166
132k
    }
167
168
48.7k
    std::string normalized;
169
48.7k
    if (!normalize_timezone_name(timezone, &normalized)) {
170
45
        return false;
171
45
    }
172
48.7k
    if (auto it = lower_zone_cache_->find(to_lower_copy(normalized));
173
48.7k
        it != lower_zone_cache_->end()) [[likely]] {
174
4
        ctz = it->second;
175
4
        return true;
176
4
    }
177
48.7k
    return parse_tz_offset_string(normalized, ctz);
178
48.7k
}
179
180
bool TimezoneUtils::try_get_fixed_offset_seconds(const cctz::time_zone& timezone,
181
232
                                                 int32_t* offset_seconds) {
182
232
    const std::string& timezone_name = timezone.name();
183
232
    if (timezone_name == "UTC" || timezone_name == "Etc/UTC" || timezone_name == "Etc/GMT") {
184
62
        *offset_seconds = 0;
185
62
        return true;
186
62
    }
187
188
    // cctz names fixed_time_zone() instances with the "Fixed/" prefix. TZDB's Etc/GMT*
189
    // zones are fixed offsets too; cctz handles their POSIX-style reversed sign in lookup_offset().
190
    // If this naming convention changes, falling through to the generic path remains correct.
191
170
    static const auto epoch = std::chrono::time_point_cast<cctz::sys_seconds>(
192
170
            std::chrono::system_clock::from_time_t(0));
193
170
    if (timezone_name.compare(0, 6, "Fixed/") == 0 || timezone_name.compare(0, 7, "Etc/GMT") == 0) {
194
168
        *offset_seconds = timezone.lookup_offset(epoch).offset;
195
168
        return true;
196
168
    }
197
2
    return false;
198
170
}
199
200
static bool normalize_offset_string(const std::string& timezone, bool allow_hour_only,
201
118k
                                    std::string* normalized) {
202
118k
    if (timezone.size() < 2 || (timezone[0] != '+' && timezone[0] != '-')) {
203
0
        return false;
204
0
    }
205
206
118k
    const bool positive = timezone[0] == '+';
207
118k
    const std::string_view rest(timezone.data() + 1, timezone.size() - 1);
208
118k
    int hour = 0;
209
118k
    int minute = 0;
210
211
237k
    const auto parse_digit = [](char c) -> int { return c - '0'; };
212
118k
    const auto is_two_digits = [](std::string_view value) -> bool {
213
118k
        return value.size() == 2 && std::isdigit(static_cast<unsigned char>(value[0])) &&
214
118k
               std::isdigit(static_cast<unsigned char>(value[1]));
215
118k
    };
216
118k
    const auto is_one_or_two_digits = [](std::string_view value) -> bool {
217
118k
        return (value.size() == 1 || value.size() == 2) &&
218
118k
               std::all_of(value.begin(), value.end(),
219
237k
                           [](char c) { return std::isdigit(static_cast<unsigned char>(c)); });
220
118k
    };
221
222
118k
    auto colon_pos = rest.find(':');
223
118k
    if (colon_pos != std::string_view::npos) {
224
118k
        std::string_view hour_part = rest.substr(0, colon_pos);
225
118k
        std::string_view minute_part = rest.substr(colon_pos + 1);
226
118k
        if (!is_one_or_two_digits(hour_part) || !is_two_digits(minute_part)) {
227
0
            return false;
228
0
        }
229
118k
        hour = std::stoi(std::string(hour_part));
230
118k
        minute = parse_digit(minute_part[0]) * 10 + parse_digit(minute_part[1]);
231
118k
    } else {
232
5
        if (!allow_hour_only || !is_one_or_two_digits(rest)) {
233
2
            return false;
234
2
        }
235
3
        hour = std::stoi(std::string(rest));
236
3
        minute = 0;
237
3
    }
238
239
118k
    if ((!positive && hour > 12) || (positive && hour > 14) || minute >= 60) {
240
5
        return false;
241
5
    }
242
243
118k
    *normalized = std::string(1, positive ? '+' : '-') + (hour < 10 ? "0" : "") +
244
118k
                  std::to_string(hour) + ":" + (minute < 10 ? "0" : "") + std::to_string(minute);
245
118k
    return true;
246
118k
}
247
248
119k
bool TimezoneUtils::normalize_timezone_name(const std::string& timezone, std::string* normalized) {
249
119k
    const std::string lower = to_lower_copy(timezone);
250
119k
    if (lower == "utc" || lower == "etc/utc" || lower == "zulu") {
251
285
        *normalized = "UTC";
252
285
        return true;
253
285
    }
254
255
118k
    if (lower.rfind("utc", 0) == 0 || lower.rfind("gmt", 0) == 0) {
256
5
        if (timezone.size() <= 3) {
257
0
            return false;
258
0
        }
259
5
        return normalize_offset_string(timezone.substr(3), true, normalized);
260
5
    }
261
262
118k
    if (!timezone.empty() && (timezone[0] == '+' || timezone[0] == '-')) {
263
118k
        return normalize_offset_string(timezone, false, normalized);
264
118k
    }
265
266
43
    return false;
267
118k
}
268
269
70.4k
bool TimezoneUtils::parse_tz_offset_string(const std::string& timezone, cctz::time_zone& ctz) {
270
70.4k
    std::string normalized;
271
70.4k
    if (!normalize_timezone_name(timezone, &normalized)) {
272
5
        return false;
273
5
    }
274
70.4k
    if (normalized == "UTC") {
275
143
        ctz = cctz::utc_time_zone();
276
143
        return true;
277
143
    }
278
279
70.3k
    re2::StringPiece value;
280
70.3k
    if (time_zone_offset_format_reg.Match(normalized, 0, normalized.size(), RE2::UNANCHORED, &value,
281
70.3k
                                          1)) [[likely]] {
282
70.3k
        const bool positive = value[0] != '-';
283
70.3k
        const int hour = std::stoi(value.substr(1, 2).as_string());
284
70.3k
        const int minute = std::stoi(value.substr(4, 2).as_string());
285
70.3k
        int offset = hour * 60 * 60 + minute * 60;
286
70.3k
        offset *= positive ? 1 : -1;
287
70.3k
        ctz = cctz::fixed_time_zone(cctz::seconds(offset));
288
70.3k
        return true;
289
70.3k
    }
290
0
    return false;
291
70.3k
}
292
293
} // namespace doris