112 lines
2.3 KiB
Go
112 lines
2.3 KiB
Go
// Copyright (C) 2020 Marius Schellenberger
|
|
|
|
package pve
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
)
|
|
|
|
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")
|
|
)
|
|
|
|
type NodeStatus string
|
|
|
|
const (
|
|
NodeStatusOnline NodeStatus = "online"
|
|
NodeStatusOffline NodeStatus = "offline"
|
|
NodeStatusUnknown NodeStatus = "unknown"
|
|
)
|
|
|
|
type Node struct {
|
|
Name string `json:"node"`
|
|
Status NodeStatus `json:"status"`
|
|
}
|
|
|
|
type NodeList []*Node
|
|
|
|
type NodeClient struct {
|
|
client *Client
|
|
}
|
|
|
|
func (c *NodeClient) List(ctx context.Context) (nl NodeList, err error) {
|
|
req, err := c.client.NewRequest(ctx, "GET", "/nodes", nil)
|
|
if err != nil {
|
|
return
|
|
}
|
|
_, err = c.client.Do(req, &nl)
|
|
return
|
|
}
|
|
|
|
func (c *NodeClient) ListServers(ctx context.Context, n *Node) (sl ServerList, err error) {
|
|
req, err := c.client.NewRequest(ctx, "GET", fmt.Sprintf("/nodes/%s/qemu", n.Name), nil)
|
|
if err != nil {
|
|
return
|
|
}
|
|
_, err = c.client.Do(req, &sl)
|
|
if err == nil {
|
|
for i := range sl {
|
|
sl[i].Node = n.Name
|
|
}
|
|
}
|
|
return
|
|
}
|
|
|
|
func (c *NodeClient) FindServer(ctx context.Context, name, id string) (s *Server, err error) {
|
|
nl, err := c.List(ctx)
|
|
if err != nil {
|
|
return
|
|
}
|
|
nodeOffline := false
|
|
nodeNotSearched := false
|
|
for _, node := range nl {
|
|
if node.Status != NodeStatusOnline {
|
|
nodeOffline = true
|
|
continue
|
|
}
|
|
sl, err := c.ListServers(ctx, node)
|
|
if err != nil {
|
|
nodeNotSearched = true
|
|
continue
|
|
}
|
|
for _, s := range sl {
|
|
if id != "" && s.ID == id {
|
|
return s, nil
|
|
}
|
|
if name != "" && s.Name == name {
|
|
return s, nil
|
|
}
|
|
}
|
|
}
|
|
if nodeOffline {
|
|
return nil, ErrNodesOffline
|
|
}
|
|
if nodeNotSearched {
|
|
return nil, ErrNodesNotSearched
|
|
}
|
|
return nil, ErrServerNotFound
|
|
}
|
|
|
|
func (c *NodeClient) FindServerByName(ctx context.Context, name string) (s *Server, err error) {
|
|
return c.FindServer(ctx, name, "")
|
|
}
|
|
|
|
func (c *NodeClient) FindServerByID(ctx context.Context, id string) (s *Server, err error) {
|
|
if id == "" {
|
|
err = ErrEmptyID
|
|
return
|
|
}
|
|
return c.FindServer(ctx, "", id)
|
|
}
|
|
|
|
func (c *NodeClient) FindServerByURL(ctx context.Context, url string) (s *Server, err error) {
|
|
_, _, id, err := ParseURL(url)
|
|
if err != nil {
|
|
return
|
|
}
|
|
return c.FindServerByID(ctx, id)
|
|
}
|