Return the machine when registering

This commit is contained in:
Juan Font Alonso 2021-05-08 13:27:53 +02:00
parent 33bee1df05
commit 4b3b48441f

23
cli.go
View File

@ -1,50 +1,45 @@
package headscale package headscale
import ( import (
"fmt" "errors"
"log" "log"
"tailscale.com/wgengine/wgcfg" "tailscale.com/wgengine/wgcfg"
) )
// RegisterMachine is executed from the CLI to register a new Machine using its MachineKey // RegisterMachine is executed from the CLI to register a new Machine using its MachineKey
func (h *Headscale) RegisterMachine(key string, namespace string) error { func (h *Headscale) RegisterMachine(key string, namespace string) (*Machine, error) {
ns, err := h.GetNamespace(namespace) ns, err := h.GetNamespace(namespace)
if err != nil { if err != nil {
return err return nil, err
} }
mKey, err := wgcfg.ParseHexKey(key) mKey, err := wgcfg.ParseHexKey(key)
if err != nil { if err != nil {
log.Printf("Cannot parse client key: %s", err) return nil, err
return err
} }
db, err := h.db() db, err := h.db()
if err != nil { if err != nil {
log.Printf("Cannot open DB: %s", err) log.Printf("Cannot open DB: %s", err)
return err return nil, err
} }
defer db.Close() defer db.Close()
m := Machine{} m := Machine{}
if db.First(&m, "machine_key = ?", mKey.HexString()).RecordNotFound() { if db.First(&m, "machine_key = ?", mKey.HexString()).RecordNotFound() {
log.Printf("Cannot find machine with machine key: %s", mKey.Base64()) return nil, errors.New("Machine not found")
return err
} }
if m.isAlreadyRegistered() { if m.isAlreadyRegistered() {
fmt.Println("This machine already registered") return nil, errors.New("Machine already registered")
return nil
} }
ip, err := h.getAvailableIP() ip, err := h.getAvailableIP()
if err != nil { if err != nil {
log.Println(err) return nil, err
return err
} }
m.IPAddress = ip.String() m.IPAddress = ip.String()
m.NamespaceID = ns.ID m.NamespaceID = ns.ID
m.Registered = true m.Registered = true
m.RegisterMethod = "cli" m.RegisterMethod = "cli"
db.Save(&m) db.Save(&m)
fmt.Println("Machine registered 🎉") return &m, nil
return nil
} }