Merged
fix(dfx): keep log time initialization dependency out of error header #6560
fix(dfx): keep log time initialization dependency out of error header #6560
Merged
W4termyAdd on Sep 21
Total: 6 files changed+276-50
@@ -21,6 +21,7 @@
21#include <algorithm>21#include <algorithm>
22 22 
23#include "error.h"23#include "error.h"
24+#include "utils/host_log/log_time.h"
24#include "interface/utils/string_utils.h"25#include "interface/utils/string_utils.h"
25#include "tilefwk/pypto_fwk_log.h"26#include "tilefwk/pypto_fwk_log.h"
26 27 
@@ -126,5 +127,32 @@ const char* Error::what() const noexcept
126 .c_str();127 .c_str();
127}128}
128 129 
130+TerminateHandler::TerminateHandler()
131+{
132+ InitializeLogTime();
133+ struct sigaction sa;
134+ sa.sa_handler = TerminateHandler::SigAction;
135+ sigemptyset(&sa.sa_mask);
136+ sa.sa_flags = SA_RESTART;
137+ 
138+ sigaction(SIGSEGV, &sa, &ori[0]);
139+ sigaction(SIGFPE, &sa, &ori[1]);
140+ 
141+ std::set_terminate([] {
142+ try {
143+ auto eptr = std::current_exception();
144+ if (eptr) {
145+ std::rethrow_exception(eptr);
146+ }
147+ } catch (const std::exception& e) {
148+ PYPTO_LOGE_FULL("Caught exception: %s", e.what());
149+ ErrorManager::Instance().OutputErrorMessage();
150+ std::cerr << "Caught exception: '" << e.what() << "'\n";
151+ }
152+ (void)fflush(nullptr);
153+ _Exit(1);
154+ });
155+}
156+ 
129static struct TerminateHandler terminateHandler;157static struct TerminateHandler terminateHandler;
130} // namespace npu::tile_fwk158} // namespace npu::tile_fwk
@@ -23,31 +23,7 @@
23 23 
24namespace npu::tile_fwk {24namespace npu::tile_fwk {
25struct TerminateHandler {25struct TerminateHandler {
26- TerminateHandler()26+ TerminateHandler();
27- {
28- struct sigaction sa;
29- sa.sa_handler = TerminateHandler::SigAction;
30- sigemptyset(&sa.sa_mask);
31- sa.sa_flags = SA_RESTART;
32- 
33- sigaction(SIGSEGV, &sa, &ori[0]);
34- sigaction(SIGFPE, &sa, &ori[1]);
35- 
36- std::set_terminate([] {
37- try {
38- auto eptr = std::current_exception();
39- if (eptr) {
40- std::rethrow_exception(eptr);
41- }
42- } catch (const std::exception& e) {
43- PYPTO_LOGE_FULL("Caught exception: %s", e.what());
44- ErrorManager::Instance().OutputErrorMessage();
45- std::cerr << "Caught exception: '" << e.what() << "'\n";
46- }
47- (void)fflush(nullptr);
48- _Exit(1);
49- });
50- }
51 27 
52 static void SigAction(int signo)28 static void SigAction(int signo)
53 {29 {
@@ -21,11 +21,12 @@
21#include <sys/syscall.h>21#include <sys/syscall.h>
22#include <array>22#include <array>
23#include <cstring>23#include <cstring>
24-#include <iomanip>
25#include <iostream>24#include <iostream>
25+#include <sstream>
26#include <stdexcept>26#include <stdexcept>
27#include "securec.h"27#include "securec.h"
28#include "file_utils.h"28#include "file_utils.h"
29+#include "host_log/log_time.h"
29 30 
30namespace npu::tile_fwk {31namespace npu::tile_fwk {
31namespace {32namespace {
@@ -77,30 +78,6 @@ bool GetEnvStr(const char* envName, std::string& envValue)
77 return true;78 return true;
78}79}
79 80 
80-std::string GetCurrentTime()
81-{
82- auto now = std::chrono::system_clock::now();
83- auto nowTime = std::chrono::system_clock::to_time_t(now);
84- std::tm* nowTm = std::localtime(&nowTime);
85- std::stringstream ss;
86- ss << std::put_time(nowTm, "%Y-%m-%d %H:%M:%S");
87- auto milliseconds = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()) % 1000;
88- ss << "." << std::setfill('0') << std::setw(3) << milliseconds.count();
89- return ss.str();
90-}
91- 
92-std::string GetCurrentTimeStr()
93-{
94- auto now = std::chrono::system_clock::now();
95- auto nowTime = std::chrono::system_clock::to_time_t(now);
96- std::tm* nowTm = std::localtime(&nowTime);
97- std::stringstream ss;
98- ss << std::put_time(nowTm, "%Y%m%d%H%M%S");
99- auto milliseconds = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()) % 1000;
100- ss << std::setfill('0') << std::setw(3) << milliseconds.count();
101- return ss.str();
102-}
103- 
104int ParseStrToInt(const std::string& str)81int ParseStrToInt(const std::string& str)
105{82{
106 try {83 try {
@@ -0,0 +1,139 @@
1+/**
2+ * Copyright (c) 2025-2026 Huawei Technologies Co., Ltd.
3+ * This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4+ * CANN Open Software License Agreement Version 2.0 (the "License").
5+ * Please refer to the License for details. You may not use this file except in compliance with the License.
6+ * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7+ * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8+ * See LICENSE in the root of the software repository for the full text of the License.
9+ */
10+ 
11+#include "host_log/log_time.h"
12+ 
13+#include <algorithm>
14+#include <cstdint>
15+#include <ctime>
16+#include <mutex>
17+#include <sys/time.h>
18+#include "securec.h"
19+ 
20+namespace npu::tile_fwk {
21+namespace {
22+// Constant-initialized so explicit startup is safe across translation units.
23+std::once_flag g_logTimeInit;
24+time_t g_timeZone = 0;
25+int32_t g_timeDst = 0;
26+ 
27+int32_t IsLeapYear(const int32_t year)
28+{
29+ // years can be divisible by 4, but not by 100, or years can be divisible by 400
30+ return ((((year % 4) == 0) && ((year % 100) != 0)) || ((year % 400) == 0)) ? 1 : 0;
31+}
32+ 
33+/**
34+ * @brief CalLocalTime: calculate local time
35+ * @param [in/out]timeInfo: local time struct
36+ * @param [in]sec: seconds from 1970/1/1
37+ * @param [in]tzone: current time zone
38+ * @param [in]dst: daylight time
39+ * @return: void
40+ */
41+void CalLocalTime(struct tm* timeInfo, const time_t sec, const time_t tzone, const int32_t dst)
42+{
43+ const time_t oneMin = 60; // 1m: 60s
44+ const time_t oneHour = 3600; // 1h: 3600s
45+ const time_t oneDay = 86400; // 24h: 86400s
46+ const time_t oneYear = 365; // 365 days
47+ 
48+ time_t realSec = sec - tzone; // Adjust for timezone
49+ realSec += oneHour * dst; // Adjust for daylight time
50+ time_t days = realSec / oneDay; // Days passed since epoch
51+ time_t seconds = realSec % oneDay; // Remaining seconds
52+ 
53+ timeInfo->tm_isdst = dst;
54+ timeInfo->tm_hour = (int32_t)(seconds / oneHour);
55+ timeInfo->tm_min = (int32_t)((seconds % oneHour) / oneMin);
56+ timeInfo->tm_sec = (int32_t)((seconds % oneHour) % oneMin);
57+ 
58+ // 1/1/1970 was a Thursday, that is, day 4 from the POV of the tm structure * where sunday = 0,
59+ // so to calculate the day of the week we have to add 4 * and take the modulo by 7.
60+ timeInfo->tm_wday = (int32_t)((days + 4) % 7); // start from Thursday
61+ // Calculate the current year
62+ timeInfo->tm_year = 1970; // start from 1970
63+ while (1) {
64+ // Leap years have one day more
65+ time_t yearDays = oneYear + (time_t)IsLeapYear(timeInfo->tm_year);
66+ if (yearDays > days) {
67+ break;
68+ }
69+ days -= yearDays;
70+ timeInfo->tm_year++;
71+ }
72+ timeInfo->tm_yday = (int32_t)days; // Number of day of the current year
73+ 
74+ int32_t mDays[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; // days of month: 31, 30, 28/29
75+ mDays[1] += IsLeapYear(timeInfo->tm_year); // leap year
76+ 
77+ timeInfo->tm_mon = 0;
78+ while (days >= mDays[timeInfo->tm_mon]) {
79+ days -= mDays[timeInfo->tm_mon];
80+ timeInfo->tm_mon++;
81+ }
82+ 
83+ timeInfo->tm_mon++; // Add 1 since our 'month' is zero-based
84+ timeInfo->tm_mday = (int32_t)days + 1; // Add 1 since our 'days' is zero-based
85+}
86+ 
87+void InitializeTimeZone()
88+{
89+ tzset();
90+ timeval now{};
91+ std::tm localTime{};
92+ if (gettimeofday(&now, nullptr) == 0 && localtime_r(&now.tv_sec, &localTime) != nullptr) {
93+ g_timeZone = timezone;
94+ g_timeDst = localTime.tm_isdst > 0 ? 1 : 0;
95+ }
96+ // Keep the zero-initialized UTC fallback on failure; do not log recursively.
97+}
98+ 
99+bool IsTimeSeparator(const char ch) { return ch == '-' || ch == ' ' || ch == ':' || ch == '.'; }
100+} // namespace
101+ 
102+void InitializeLogTime()
103+{
104+ // The once guard is used only by startup, never by timestamp generation.
105+ std::call_once(g_logTimeInit, InitializeTimeZone);
106+}
107+ 
108+namespace {
109+struct LogTimeInitializer {
110+ LogTimeInitializer() { InitializeLogTime(); }
111+};
112+ 
113+// Initialize log time when the utils library is loaded, even if no
114+// TerminateHandler is constructed.
115+LogTimeInitializer g_logTimeInitializer;
116+} // namespace
117+ 
118+std::string GetCurrentTime()
119+{
120+ timeval now{};
121+ if (gettimeofday(&now, nullptr) != 0) {
122+ return {};
123+ }
124+ std::tm localTime{};
125+ CalLocalTime(&localTime, now.tv_sec, g_timeZone, g_timeDst);
126+ char timeStr[24]{};
127+ const int ret = snprintf_s(timeStr, sizeof(timeStr), sizeof(timeStr) - 1, "%04d-%02d-%02d %02d:%02d:%02d.%03ld",
128+ localTime.tm_year, localTime.tm_mon, localTime.tm_mday, localTime.tm_hour,
129+ localTime.tm_min, localTime.tm_sec, static_cast<long>(now.tv_usec / 1000));
130+ return ret < 0 ? std::string{} : std::string(timeStr);
131+}
132+ 
133+std::string GetCurrentTimeStr()
134+{
135+ std::string timeStr = GetCurrentTime();
136+ timeStr.erase(std::remove_if(timeStr.begin(), timeStr.end(), IsTimeSeparator), timeStr.end());
137+ return timeStr;
138+}
139+} // namespace npu::tile_fwk
@@ -0,0 +1,20 @@
1+/**
2+ * Copyright (c) 2025-2026 Huawei Technologies Co., Ltd.
3+ * This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4+ * CANN Open Software License Agreement Version 2.0 (the "License").
5+ * Please refer to the License for details. You may not use this file except in compliance with the License.
6+ * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7+ * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8+ * See LICENSE in the root of the software repository for the full text of the License.
9+ */
10+ 
11+#pragma once
12+ 
13+#include <string>
14+ 
15+namespace npu::tile_fwk {
16+// Startup only: call before installing handlers that can log. Never call from a log callback.
17+void InitializeLogTime();
18+std::string GetCurrentTime();
19+std::string GetCurrentTimeStr();
20+} // namespace npu::tile_fwk
@@ -0,0 +1,86 @@
1+/**
2+ * Copyright (c) 2025-2026 Huawei Technologies Co., Ltd.
3+ * This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4+ * CANN Open Software License Agreement Version 2.0 (the "License").
5+ * Please refer to the License for details. You may not use this file except in compliance with the License.
6+ * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7+ * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8+ * See LICENSE in the root of the software repository for the full text of the License.
9+ */
10+ 
11+#include <gtest/gtest.h>
12+#include <atomic>
13+#include <ctime>
14+#include <regex>
15+#include <thread>
16+#include <vector>
17+#include "utils/host_log/log_time.h"
18+ 
19+namespace npu::tile_fwk {
20+namespace {
21+std::string FormatReferenceTime(const time_t seconds)
22+{
23+ std::tm localTime{};
24+ if (localtime_r(&seconds, &localTime) == nullptr) {
25+ return {};
26+ }
27+ char buffer[32]{};
28+ std::strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", &localTime);
29+ return buffer;
30+}
31+std::string FormatReferenceFilenameTime(const time_t seconds)
32+{
33+ std::tm localTime{};
34+ if (localtime_r(&seconds, &localTime) == nullptr) {
35+ return {};
36+ }
37+ char buffer[32]{};
38+ std::strftime(buffer, sizeof(buffer), "%Y%m%d%H%M%S", &localTime);
39+ return buffer;
40+}
41+void CheckConcurrentTimestamps(std::atomic<bool>* valid)
42+{
43+ for (int j = 0; j < 1000; ++j) {
44+ const std::string normal = GetCurrentTime();
45+ const std::string compact = GetCurrentTimeStr();
46+ if (normal.size() != 23 || compact.size() != 17 ||
47+ compact.find_first_not_of("0123456789") != std::string::npos) {
48+ *valid = false;
49+ }
50+ }
51+}
52+} // namespace
53+ 
54+TEST(LogTimeTest, PreservesLocalTimestampFormat)
55+{
56+ const time_t before = std::time(nullptr);
57+ const std::string actual = GetCurrentTime();
58+ const time_t after = std::time(nullptr);
59+ ASSERT_TRUE(std::regex_match(actual, std::regex(R"(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d{3})")));
60+ const std::string date = actual.substr(0, 19);
61+ EXPECT_TRUE(date == FormatReferenceTime(before) || date == FormatReferenceTime(after));
62+}
63+ 
64+TEST(LogTimeTest, PreservesFilenameTimestampFormat)
65+{
66+ const time_t before = std::time(nullptr);
67+ const std::string actual = GetCurrentTimeStr();
68+ const time_t after = std::time(nullptr);
69+ ASSERT_TRUE(std::regex_match(actual, std::regex(R"(\d{17})")));
70+ const std::string date = actual.substr(0, 14);
71+ EXPECT_TRUE(date == FormatReferenceFilenameTime(before) || date == FormatReferenceFilenameTime(after));
72+}
73+ 
74+TEST(LogTimeTest, ConcurrentTimestampGeneration)
75+{
76+ std::atomic<bool> valid{true};
77+ std::vector<std::thread> threads;
78+ for (int i = 0; i < 8; ++i) {
79+ threads.emplace_back(CheckConcurrentTimestamps, &valid);
80+ }
81+ for (auto& thread : threads) {
82+ thread.join();
83+ }
84+ EXPECT_TRUE(valid.load());
85+}
86+} // namespace npu::tile_fwk