added better id handling

This commit is contained in:
ston1th 2021-12-10 20:33:20 +01:00
commit 78b40626e6
4 changed files with 77 additions and 33 deletions

35
node.go
View file

@ -10,10 +10,10 @@ import (
)
var (
ErrNodesOffline = errors.New("one or more nodes are offline")
ErrNodesNotSearched = errors.New("one or more nodes could not be searched")
ErrEmptyID = errors.New("id is empty")
ErrUnschedulable = errors.New("no schedulable node found")
ErrNodesOffline = errors.New("one or more nodes are offline")
ErrNodesNotSearched = errors.New("one or more nodes could not be searched")
ErrUnschedulable = errors.New("no schedulable node found")
ErrTooManyServersFound = errors.New("too many servers found with the same name")
)
type NodeStatus string
@ -205,13 +205,16 @@ func (c *NodeClient) ListServers(ctx context.Context, n *Node) (sl ServerRefList
return
}
func (c *NodeClient) FindServer(ctx context.Context, name string, id int) (s *ServerRef, err error) {
func (c *NodeClient) FindServer(ctx context.Context, name string, id int) (ref *ServerRef, err error) {
valid := ValidateID(id) == nil
nl, err := c.List(ctx)
if err != nil {
return
}
nodeOffline := false
nodeNotSearched := false
var (
nodeOffline bool
nodeNotSearched bool
)
for _, node := range nl {
if node.Status != NodeStatusOnline {
nodeOffline = true
@ -223,11 +226,14 @@ func (c *NodeClient) FindServer(ctx context.Context, name string, id int) (s *Se
continue
}
for _, s := range sl {
if id != -1 && s.ID == id {
if valid && s.ID == id {
return s, nil
}
if name != "" && s.Name == name {
return s, nil
if ref != nil {
return nil, ErrTooManyServersFound
}
ref = s
}
}
}
@ -237,16 +243,19 @@ func (c *NodeClient) FindServer(ctx context.Context, name string, id int) (s *Se
if nodeNotSearched {
return nil, ErrNodesNotSearched
}
return nil, ErrServerNotFound
if ref == nil {
err = ErrServerNotFound
}
return
}
func (c *NodeClient) FindServerByName(ctx context.Context, name string) (s *ServerRef, err error) {
return c.FindServer(ctx, name, -1)
return c.FindServer(ctx, name, InvalidID)
}
func (c *NodeClient) FindServerByID(ctx context.Context, id int) (s *ServerRef, err error) {
if id == -1 {
err = ErrEmptyID
err = ValidateID(id)
if err != nil {
return
}
return c.FindServer(ctx, "", id)