From aac1ccf12d0076ce7ae2b67ed9cbdf55dc99e14e Mon Sep 17 00:00:00 2001 From: Matthew Holt Date: Tue, 30 Mar 2021 14:15:20 -0600 Subject: caddy: Add InstanceID() method Caddy can now generate and persist its own instance ID, a UUID that is stored in the data directory. This makes it possible to differentiate it from other instances in a cluster. --- caddy.go | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) (limited to 'caddy.go') diff --git a/caddy.go b/caddy.go index fccfeef..dcbcb2d 100644 --- a/caddy.go +++ b/caddy.go @@ -33,6 +33,7 @@ import ( "time" "github.com/caddyserver/certmagic" + "github.com/google/uuid" "go.uber.org/zap" ) @@ -662,6 +663,26 @@ func ParseDuration(s string) (time.Duration, error) { return time.ParseDuration(s) } +// InstanceID returns the UUID for this instance, and generates one if it +// does not already exist. The UUID is stored in the local data directory, +// regardless of storage configuration, since each instance is intended to +// have its own unique ID. +func InstanceID() (uuid.UUID, error) { + uuidFilePath := filepath.Join(AppDataDir(), "instance.uuid") + uuidFileBytes, err := os.ReadFile(uuidFilePath) + if os.IsNotExist(err) { + uuid, err := uuid.NewRandom() + if err != nil { + return uuid, err + } + err = ioutil.WriteFile(uuidFilePath, []byte(uuid.String()), 0644) + return uuid, err + } else if err != nil { + return [16]byte{}, err + } + return uuid.ParseBytes(uuidFileBytes) +} + // GoModule returns the build info of this Caddy // build from debug.BuildInfo (requires Go modules). // If no version information is available, a non-nil -- cgit v1.2.3