From 06c928bc525e3a79d985030658bf6dd17767151a Mon Sep 17 00:00:00 2001 From: Kristoffer Dalby Date: Sun, 24 Apr 2022 20:56:42 +0100 Subject: [PATCH] Migrate name and nickname fields --- db.go | 42 ++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 40 insertions(+), 2 deletions(-) diff --git a/db.go b/db.go index 9130d90..6eb0683 100644 --- a/db.go +++ b/db.go @@ -39,6 +39,44 @@ func (h *Headscale) initDB() error { } _ = db.Migrator().RenameColumn(&Machine{}, "ip_address", "ip_addresses") + _ = db.Migrator().RenameColumn(&Machine{}, "name", "hostname") + + // GivenName is used as the primary source of DNS names, make sure + // the field is populated and normalized if it was not when the + // machine was registered. + _ = db.Migrator().RenameColumn(&Machine{}, "nickname", "given_name") + if db.Migrator().HasColumn(&Machine{}, "given_name") { + machines := Machines{} + if err := h.db.Find(&machines).Error; err != nil { + log.Error().Err(err).Msg("Error accessing db") + } + + for _, machine := range machines { + if machine.GivenName == "" { + normalizedHostname, err := NormalizeToFQDNRules( + machine.Hostname, + h.cfg.OIDC.StripEmaildomain, + ) + if err != nil { + log.Error(). + Caller(). + Str("hostname", machine.Hostname). + Err(err). + Msg("Failed to normalize machine hostname in DB migration") + } + + err = h.RenameMachine(&machine, normalizedHostname) + if err != nil { + log.Error(). + Caller(). + Str("hostname", machine.Hostname). + Err(err). + Msg("Failed to save normalized machine name in DB migration") + } + + } + } + } // If the Machine table has a column for registered, // find all occourences of "false" and drop them. Then @@ -54,13 +92,13 @@ func (h *Headscale) initDB() error { for _, machine := range machines { log.Info(). - Str("machine", machine.Name). + Str("machine", machine.Hostname). Str("machine_key", machine.MachineKey). Msg("Deleting unregistered machine") if err := h.db.Delete(&Machine{}, machine.ID).Error; err != nil { log.Error(). Err(err). - Str("machine", machine.Name). + Str("machine", machine.Hostname). Str("machine_key", machine.MachineKey). Msg("Error deleting unregistered machine") }