-
Notifications
You must be signed in to change notification settings - Fork 4
/
client.go
115 lines (90 loc) · 2.33 KB
/
client.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
package fossil
import (
"encoding/json"
)
//***** Requests *****//
// GetServer fetches the server with the given ID if it exists
func (c *ClientCredentials) GetServer(id string) (sv *ClientServer, err error) {
bytes, err := c.query("servers/"+id+"?include=allocations", "GET", nil)
if err != nil {
return
}
var wrapper struct {
Server jsonServer `json:"attributes"`
}
err = json.Unmarshal(bytes, &wrapper)
if err != nil {
return
}
return wrapper.Server.asClientServer(), nil
}
// GetServers fetches all the servers of the client
func (c *ClientCredentials) GetServers() (svs []*ClientServer, err error) {
bytes, err := c.query("?include=allocations", "GET", nil)
if err != nil {
return
}
// Get the initial page
var page jsonServerPage
err = json.Unmarshal(bytes, &page)
if err != nil {
return
}
// Search for the remaining pages if present
pages, err := page.getAll(c.Token)
if err != nil {
return
}
for _, page := range pages {
svs = append(svs, page.asClientServers()...)
}
return
}
// GetServerStatus fetches the server's status and usage
func (c *ClientCredentials) GetServerStatus(id string) (ss *ServerStatus, err error) {
bytes, err := c.query("servers/"+id+"/utilization", "GET", nil)
if err != nil {
return
}
var wrapper struct {
Utilization *ServerStatus `json:"attributes"`
}
err = json.Unmarshal(bytes, &wrapper)
if err != nil {
return
}
return wrapper.Utilization, nil
}
// ExecuteCommand allows the execution of a console command on the specified server
func (c *ClientCredentials) ExecuteCommand(id string, cmd string) (err error) {
type wrapper struct {
Command string `json:"command"`
}
cmdWrapper := wrapper{Command: cmd}
rq, err := json.Marshal(cmdWrapper)
if err != nil {
return
}
_, err = c.query("servers/"+id+"/command", "POST", rq)
if err != nil {
return
}
return nil
}
// SetPowerState changes the power state of a server. Will result in error if the server is already in that state
// or is unable to change state.
func (c *ClientCredentials) SetPowerState(id string, state string) (err error) {
type wrapper struct {
Signal string `json:"signal"`
}
signalWrapper := wrapper{Signal: state}
rq, err := json.Marshal(signalWrapper)
if err != nil {
return
}
_, err = c.query("servers/"+id+"/power", "POST", rq)
if err != nil {
return
}
return nil
}