git » kxd » commit 527095f

kxd: Log version on startup, and add --version flag

author Alberto Bertogli
2025-01-13 01:07:39 UTC
committer Alberto Bertogli
2025-01-13 01:30:43 UTC
parent 9c4db5cc5f8b117c3fa84a65cd1881f85910ae0e

kxd: Log version on startup, and add --version flag

Having an idea of the version can be useful for troubleshooting. This
patch makes kxd log the version on startup, and also introduces a
--version flag to print it to stdout and exit.

kxd/kxd.go +25 -0
tests/run_tests +7 -0

diff --git a/kxd/kxd.go b/kxd/kxd.go
index ac936bc..264963c 100644
--- a/kxd/kxd.go
+++ b/kxd/kxd.go
@@ -21,8 +21,10 @@ import (
 	"os"
 	"os/signal"
 	"path"
+	"runtime/debug"
 	"strings"
 	"syscall"
+	"time"
 )
 
 var port = flag.Int(
@@ -44,6 +46,8 @@ var logFile = flag.String(
 var hookPath = flag.String(
 	"hook", "/etc/kxd/hook",
 	"Hook to run before authorizing keys (skipped if it doesn't exist)")
+var versionFlag = flag.Bool(
+	"version", false, "Print version and exit")
 
 // Logger we will use to log entries.
 var logging *log.Logger
@@ -244,10 +248,31 @@ func signalHandler() {
 	}
 }
 
+func version() string {
+	info, _ := debug.ReadBuildInfo()
+	rev := info.Main.Version
+	ts := time.Time{}
+	for _, s := range info.Settings {
+		switch s.Key {
+		case "vcs.revision":
+			rev = s.Value
+		case "vcs.time":
+			ts, _ = time.Parse(time.RFC3339, s.Value)
+		}
+	}
+	return fmt.Sprintf("kxd version %s (%s)", rev, ts)
+}
+
 func main() {
 	flag.Parse()
 
+	if *versionFlag {
+		fmt.Println(version())
+		os.Exit(0)
+	}
+
 	initLog()
+	logging.Print(version())
 
 	go signalHandler()
 
diff --git a/tests/run_tests b/tests/run_tests
index 4d2fd34..5e0e3b2 100755
--- a/tests/run_tests
+++ b/tests/run_tests
@@ -809,5 +809,12 @@ class Emails(TestCase):
         self.assertEqual(self.emails, [])
 
 
+# Test kxd --version.
+class VersionFlag(TestCase):
+    def test_version(self):
+        output = subprocess.check_output([BINS + "/kxd", "--version"])
+        self.assertRegex(output.decode(), r"kxd version .+ (.+)")
+
+
 if __name__ == "__main__":
     unittest.main()