From ec1509de4ebbccbade51115c434996cd1fd9be7e Mon Sep 17 00:00:00 2001
From: Ekaterina Lebedeva <ekaterina.lebedeva@yadro.com>
Date: Thu, 15 Aug 2024 17:12:38 +0300
Subject: [PATCH] [#1262] sdnotify: Send system monotonic time on reload

The synchronized service reload protocol added in systemd version 253
requires that the service provides a MONOTONIC_USEC field alongside the
RELOADING=1 notification message for synchronization purposes. The value
carried in this field must be the system CLOCK_MONOTONIC timestamp at
the time the notification message was generated as systemd compares it
to other CLOCK_MONOTONIC timestamps taken by pid1.

Signed-off-by: Ekaterina Lebedeva <ekaterina.lebedeva@yadro.com>
---
 pkg/util/sdnotify/clock.go    | 10 ----------
 pkg/util/sdnotify/clock.s     |  2 --
 pkg/util/sdnotify/sdnotify.go |  9 ++++++++-
 3 files changed, 8 insertions(+), 13 deletions(-)
 delete mode 100644 pkg/util/sdnotify/clock.go
 delete mode 100644 pkg/util/sdnotify/clock.s

diff --git a/pkg/util/sdnotify/clock.go b/pkg/util/sdnotify/clock.go
deleted file mode 100644
index f5419d027..000000000
--- a/pkg/util/sdnotify/clock.go
+++ /dev/null
@@ -1,10 +0,0 @@
-package sdnotify
-
-import (
-	// For go:linkname to work.
-	_ "unsafe"
-)
-
-//go:noescape
-//go:linkname nanotime runtime.nanotime
-func nanotime() int64
diff --git a/pkg/util/sdnotify/clock.s b/pkg/util/sdnotify/clock.s
deleted file mode 100644
index ad033ff4f..000000000
--- a/pkg/util/sdnotify/clock.s
+++ /dev/null
@@ -1,2 +0,0 @@
-// The file is intentionally empty.
-// It is a workaround for https://github.com/golang/go/issues/15006
diff --git a/pkg/util/sdnotify/sdnotify.go b/pkg/util/sdnotify/sdnotify.go
index 16a3f11c1..5235315cc 100644
--- a/pkg/util/sdnotify/sdnotify.go
+++ b/pkg/util/sdnotify/sdnotify.go
@@ -5,7 +5,10 @@ import (
 	"fmt"
 	"net"
 	"os"
+	"strconv"
 	"strings"
+
+	"golang.org/x/sys/unix"
 )
 
 const (
@@ -51,7 +54,11 @@ func FlagAndStatus(status string) error {
 		//    must be sent, containing "READY=1".
 		//
 		// For MONOTONIC_USEC format refer to https://www.man7.org/linux/man-pages/man3/sd_notify.3.html
-		status += fmt.Sprintf("\nMONOTONIC_USEC=%d", uint64(nanotime())/1e3 /* microseconds in nanoseconds */)
+		var ts unix.Timespec
+		if err := unix.ClockGettime(unix.CLOCK_MONOTONIC, &ts); err != nil {
+			return fmt.Errorf("clock_gettime: %w", err)
+		}
+		status += "\nMONOTONIC_USEC=" + strconv.FormatInt(ts.Nano()/1000, 10)
 	}
 	status += "\nSTATUS=" + strings.TrimSuffix(status, "=1")
 	return Send(status)