clogger.git  about / heads / tags
configurable request logging for Rack
   commit 0a6b4a2c54784c90ec1b762cb6880ebc745658e9 (patch)
   parent 461c3d4 use _POSIX_C_SOURCE=200809L
     tree 025adccf5797753079673dc7dd7b463c046e8bfb
   author Eric Wong <bofh@yhbt.net>  2023-03-19 20:24:29 +0000
committer Eric Wong <bofh@yhbt.net>  2023-05-11 21:27:08 +0000

workaround for time(2) being non-monotonic

Apparently, time(2) may go backwards in the first 1 - 2.5ms of
every second since Linux + glibc 2.31+ (and some proprietary
OSes).  Use clock_gettime(2) with CLOCK_REALTIME to workaround
the problem at the cost of a slight performance hit(*).  While git
will likely use gettimeofday(2) for compatibility with
proprietary OSes, gettimeofday(2) was declared obsolete in
POSIX.1-2008 and we don't support proprietary OSes.

(*) https://inbox.sourceware.org/libc-alpha/87ttywq0je.fsf@oldenburg.str.redhat.com/
Link: https://lore.kernel.org/git/20230319064353.686226-3-eggert@cs.ucla.edu/T/
---
 ext/clogger_ext/clogger.c | 18 +++++++++++++++---
 1 file changed, 15 insertions(+), 3 deletions(-)

diff --git a/ext/clogger_ext/clogger.c b/ext/clogger_ext/clogger.c
index 7989472..23aea39 100644
--- a/ext/clogger_ext/clogger.c
+++ b/ext/clogger_ext/clogger.c
@@ -475,9 +475,21 @@ static void append_request_length(struct clogger *c)
 	}
 }
 
+/*
+ * time(2) may slip backwards, so use CLOCK_REALTIME for accuracy
+ * https://lore.kernel.org/git/20230319064353.686226-3-eggert@cs.ucla.edu/T/
+ */
+static time_t cur_time(void)
+{
+	struct timespec now;
+
+	(void)clock_gettime(CLOCK_REALTIME, &now);
+	return now.tv_sec;
+}
+
 static long local_gmtoffset(struct tm *tm)
 {
-	time_t t = time(NULL);
+	time_t t = cur_time();
 
 	tzset();
 	localtime_r(&t, tm);
@@ -537,7 +549,7 @@ static void append_time_utc(struct clogger *c)
 	char buf[sizeof("01/Jan/1970:00:00:00 +0000")];
 	struct tm tm;
 	int nr;
-	time_t t = time(NULL);
+	time_t t = cur_time();
 
 	gmtime_r(&t, &tm);
 	nr = snprintf(buf, sizeof(buf),
@@ -556,7 +568,7 @@ append_time(struct clogger *c, enum clogger_opcode op, VALUE fmt, VALUE buf)
 	size_t buf_size = RSTRING_LEN(buf) + 1; /* "\0" */
 	size_t nr;
 	struct tm tmp;
-	time_t t = time(NULL);
+	time_t t = cur_time();
 
 	if (op == CL_OP_TIME_LOCAL)
 		localtime_r(&t, &tmp);


glossary
--------
Commit objects reference one tree, and zero or more parents.

Single parent commits can typically generate a patch in
unified diff format via `git format-patch'.

Multiple parents means the commit is a merge.

Root commits have no ancestor.  Note that it is
possible to have multiple root commits when merging independent histories.

Every commit references one top-level tree object.

git clone http://yhbt.net/clogger.git