mirror of
https://github.com/caddyserver/caddy.git
synced 2025-05-24 11:41:19 +08:00
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.
This commit is contained in:
21
caddy.go
21
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
|
||||
|
Reference in New Issue
Block a user