feat: update functions to use set command

This commit is contained in:
Adrien Raffin-Caboisse 2022-04-25 21:16:14 +02:00
parent cc9eeda889
commit ea9aaa6022
2 changed files with 18 additions and 35 deletions

View File

@ -3,8 +3,6 @@ package headscale
import ( import (
"context" "context"
"fmt"
"strconv"
"time" "time"
v1 "github.com/juanfont/headscale/gen/go/headscale/v1" v1 "github.com/juanfont/headscale/gen/go/headscale/v1"
@ -184,35 +182,23 @@ func (api headscaleV1APIServer) GetMachine(
return &v1.GetMachineResponse{Machine: machine.toProto()}, nil return &v1.GetMachineResponse{Machine: machine.toProto()}, nil
} }
func (api headscaleV1APIServer) UpdateMachine( func (api headscaleV1APIServer) SetTags(
ctx context.Context, ctx context.Context,
request *v1.UpdateMachineRequest, request *v1.SetTagsRequest,
) (*v1.UpdateMachineResponse, error) { ) (*v1.SetTagsResponse, error) {
rMachine := request.GetMachine() machine, err := api.h.GetMachineByID(request.GetMachineId())
machine, err := api.h.GetMachineByID(rMachine.Id)
if err != nil { if err != nil {
return nil, err return nil, err
} }
machine.ForcedTags = rMachine.ForcedTags api.h.SetTags(machine, request.GetTags())
machine.Name = rMachine.Name
id, err := strconv.Atoi(rMachine.Namespace.Id)
if err != nil {
return nil, fmt.Errorf("failed to convert namespace id to integer: %w", err)
}
machine.NamespaceID = uint(id)
err = api.h.UpdateDBMachine(*machine) log.Trace().
if err != nil { Str("machine", machine.Name).
return nil, err Strs("tags", request.GetTags()).
} Msg("Changing tags of machine")
machine, err = api.h.GetMachineByID(rMachine.Id) return &v1.SetTagsResponse{Machine: machine.toProto()}, nil
if err != nil {
return nil, err
}
return &v1.UpdateMachineResponse{Machine: machine.toProto()}, nil
} }
func (api headscaleV1APIServer) DeleteMachine( func (api headscaleV1APIServer) DeleteMachine(

View File

@ -360,18 +360,15 @@ func (h *Headscale) UpdateMachine(machine *Machine) error {
return nil return nil
} }
// UpdateDBMachine takes a Machine struct pointer (typically already loaded from database // SetTags takes a Machine struct pointer and update the forced tags.
// search for the same machine in the database and update the latter. func (h *Headscale) SetTags(machine *Machine, tags []string) error {
func (h *Headscale) UpdateDBMachine(machine Machine) error { machine.ForcedTags = tags
destMachine := Machine{} err := h.UpdateACLRules()
if result := h.db.Where("id = ?", machine.ID).Find(&destMachine); result.Error != nil { if err != nil {
return result.Error return err
} }
destMachine.Name = machine.Name h.setLastStateChangeToNow(machine.Namespace.Name)
destMachine.NamespaceID = machine.NamespaceID h.db.Save(machine)
destMachine.ForcedTags = machine.ForcedTags
h.db.Save(destMachine)
return nil return nil
} }