Debian Codegraph @

cloudapi/machines.go

raw symbols SCIP
1 package cloudapi
2
3 import (
4 "encoding/json"
5 "fmt"
6 "net/http"
7
8 "strings"
9
10 "github.com/joyent/gocommon/client"
11 "github.com/joyent/gocommon/errors"
12 )
13
14 // Machine represent a provisioned virtual machines
15 type Machine struct {
16 Id string // Unique identifier for the image
17 Name string // Machine friendly name
18 Type string // Machine type, one of 'smartmachine' or 'virtualmachine'
19 State string // Current state of the machine
20 Dataset string // The dataset URN the machine was provisioned with. For new images/datasets this value will be the dataset id, i.e, same value than the image attribute
21 Memory int // The amount of memory the machine has (in Mb)
22 Disk int // The amount of disk the machine has (in Gb)
23 IPs []string // The IP addresses the machine has
24 Metadata map[string]string // Map of the machine metadata, e.g. authorized-keys
25 Tags map[string]string // Map of the machine tags
26 Created string // When the machine was created
27 Updated string // When the machine was updated
28 Package string // The name of the package used to create the machine
29 Image string // The image id the machine was provisioned with
30 PrimaryIP string // The primary (public) IP address for the machine
31 Networks []string // The network IDs for the machine
32 FirewallEnabled bool `json:"firewall_enabled"` // whether or not the firewall is enabled
33 DomainNames []string `json:"dns_names"` // The domain names of this machine
34 }
35
36 // Equals compares two machines. Ignores state and timestamps.
37 func (m Machine) Equals(other Machine) bool {
38 if m.Id == other.Id && m.Name == other.Name && m.Type == other.Type && m.Dataset == other.Dataset &&
39 m.Memory == other.Memory && m.Disk == other.Disk && m.Package == other.Package && m.Image == other.Image &&
40 m.compareIPs(other) && m.compareMetadata(other) {
41 return true
42 }
43 return false
44 }
45
46 // Helper method to compare two machines IPs
47 func (m Machine) compareIPs(other Machine) bool {
48 if len(m.IPs) != len(other.IPs) {
49 return false
50 }
51 for i, v := range m.IPs {
52 if v != other.IPs[i] {
53 return false
54 }
55 }
56 return true
57 }
58
59 // Helper method to compare two machines metadata
60 func (m Machine) compareMetadata(other Machine) bool {
61 if len(m.Metadata) != len(other.Metadata) {
62 return false
63 }
64 for k, v := range m.Metadata {
65 if v != other.Metadata[k] {
66 return false
67 }
68 }
69 return true
70 }
71
72 // CreateMachineOpts represent the option that can be specified
73 // when creating a new machine.
74 type CreateMachineOpts struct {
75 Name string `json:"name"` // Machine friendly name, default is a randomly generated name
76 Package string `json:"package"` // Name of the package to use on provisioning
77 Image string `json:"image"` // The image UUID
78 Networks []string `json:"networks"` // Desired networks IDs
79 Metadata map[string]string `json:"-"` // An arbitrary set of metadata key/value pairs can be set at provision time
80 Tags map[string]string `json:"-"` // An arbitrary set of tags can be set at provision time
81 FirewallEnabled bool `json:"firewall_enabled"` // Completely enable or disable firewall for this machine (new in API version 7.0)
82 }
83
84 // AuditAction represents an action/event accomplished by a machine.
85 type AuditAction struct {
86 Action string // Action name
87 Parameters map[string]interface{} // Original set of parameters sent when the action was requested
88 Time string // When the action finished
89 Success string // Either 'yes' or 'no', depending on the action successfulness
90 Caller Caller // Account requesting the action
91 }
92
93 // Caller represents an account requesting an action.
94 type Caller struct {
95 Type string // Authentication type for the action request. One of 'basic', 'operator', 'signature' or 'token'
96 User string // When the authentication type is 'basic', this member will be present and include user login
97 IP string // The IP addresses this from which the action was requested. Not present if type is 'operator'
98 KeyId string // When authentication type is either 'signature' or 'token', SSH key identifier
99 }
100
101 // appendJSON marshals the given attribute value and appends it as an encoded value to the given json data.
102 // The newly encode (attr, value) is inserted just before the closing "}" in the json data.
103 func appendJSON(data []byte, attr string, value interface{}) ([]byte, error) {
104 newData, err := json.Marshal(&value)
105 if err != nil {
106 return nil, err
107 }
108 strData := string(data)
109 result := fmt.Sprintf(`%s, "%s":%s}`, strData[:len(strData)-1], attr, string(newData))
110 return []byte(result), nil
111 }
112
113 type jsonOpts CreateMachineOpts
114
115 // MarshalJSON turns the given CreateMachineOpts into JSON
116 func (opts CreateMachineOpts) MarshalJSON() ([]byte, error) {
117 jo := jsonOpts(opts)
118 data, err := json.Marshal(&jo)
119 if err != nil {
120 return nil, err
121 }
122 for k, v := range opts.Tags {
123 if !strings.HasPrefix(k, "tag.") {
124 k = "tag." + k
125 }
126 data, err = appendJSON(data, k, v)
127 if err != nil {
128 return nil, err
129 }
130 }
131 for k, v := range opts.Metadata {
132 if !strings.HasPrefix(k, "metadata.") {
133 k = "metadata." + k
134 }
135 data, err = appendJSON(data, k, v)
136 if err != nil {
137 return nil, err
138 }
139 }
140 return data, nil
141 }
142
143 // ListMachines lists all machines on record for an account.
144 // You can paginate this API by passing in offset, and limit
145 // See API docs: http://apidocs.joyent.com/cloudapi/#ListMachines
146 func (c *Client) ListMachines(filter *Filter) ([]Machine, error) {
147 var resp []Machine
148 req := request{
149 method: client.GET,
150 url: apiMachines,
151 filter: filter,
152 resp: &resp,
153 }
154 if _, err := c.sendRequest(req); err != nil {
155 return nil, errors.Newf(err, "failed to get list of machines")
156 }
157 return resp, nil
158 }
159
160 // CountMachines returns the number of machines on record for an account.
161 // See API docs: http://apidocs.joyent.com/cloudapi/#ListMachines
162 func (c *Client) CountMachines() (int, error) {
163 var resp int
164 req := request{
165 method: client.HEAD,
166 url: apiMachines,
167 resp: &resp,
168 }
169 if _, err := c.sendRequest(req); err != nil {
170 return -1, errors.Newf(err, "failed to get count of machines")
171 }
172 return resp, nil
173 }
174
175 // GetMachine returns the machine specified by machineId.
176 // See API docs: http://apidocs.joyent.com/cloudapi/#GetMachine
177 func (c *Client) GetMachine(machineID string) (*Machine, error) {
178 var resp Machine
179 req := request{
180 method: client.GET,
181 url: makeURL(apiMachines, machineID),
182 resp: &resp,
183 }
184 if _, err := c.sendRequest(req); err != nil {
185 return nil, errors.Newf(err, "failed to get machine with id: %s", machineID)
186 }
187 return &resp, nil
188 }
189
190 // CreateMachine creates a new machine with the options specified.
191 // See API docs: http://apidocs.joyent.com/cloudapi/#CreateMachine
192 func (c *Client) CreateMachine(opts CreateMachineOpts) (*Machine, error) {
193 var resp Machine
194 req := request{
195 method: client.POST,
196 url: apiMachines,
197 reqValue: opts,
198 resp: &resp,
199 expectedStatus: http.StatusCreated,
200 }
201 if _, err := c.sendRequest(req); err != nil {
202 return nil, errors.Newf(err, "failed to create machine with name: %s", opts.Name)
203 }
204 return &resp, nil
205 }
206
207 // StopMachine stops a running machine.
208 // See API docs: http://apidocs.joyent.com/cloudapi/#StopMachine
209 func (c *Client) StopMachine(machineID string) error {
210 req := request{
211 method: client.POST,
212 url: fmt.Sprintf("%s/%s?action=%s", apiMachines, machineID, actionStop),
213 expectedStatus: http.StatusAccepted,
214 }
215 if _, err := c.sendRequest(req); err != nil {
216 return errors.Newf(err, "failed to stop machine with id: %s", machineID)
217 }
218 return nil
219 }
220
221 // StartMachine starts a stopped machine.
222 // See API docs: http://apidocs.joyent.com/cloudapi/#StartMachine
223 func (c *Client) StartMachine(machineID string) error {
224 req := request{
225 method: client.POST,
226 url: fmt.Sprintf("%s/%s?action=%s", apiMachines, machineID, actionStart),
227 expectedStatus: http.StatusAccepted,
228 }
229 if _, err := c.sendRequest(req); err != nil {
230 return errors.Newf(err, "failed to start machine with id: %s", machineID)
231 }
232 return nil
233 }
234
235 // RebootMachine reboots (stop followed by a start) a machine.
236 // See API docs: http://apidocs.joyent.com/cloudapi/#RebootMachine
237 func (c *Client) RebootMachine(machineID string) error {
238 req := request{
239 method: client.POST,
240 url: fmt.Sprintf("%s/%s?action=%s", apiMachines, machineID, actionReboot),
241 expectedStatus: http.StatusAccepted,
242 }
243 if _, err := c.sendRequest(req); err != nil {
244 return errors.Newf(err, "failed to reboot machine with id: %s", machineID)
245 }
246 return nil
247 }
248
249 // ResizeMachine allows you to resize a SmartMachine. Virtual machines can also
250 // be resized, but only resizing virtual machines to a higher capacity package
251 // is supported.
252 // See API docs: http://apidocs.joyent.com/cloudapi/#ResizeMachine
253 func (c *Client) ResizeMachine(machineID, packageName string) error {
254 req := request{
255 method: client.POST,
256 url: fmt.Sprintf("%s/%s?action=%s&package=%s", apiMachines, machineID, actionResize, packageName),
257 expectedStatus: http.StatusAccepted,
258 }
259 if _, err := c.sendRequest(req); err != nil {
260 return errors.Newf(err, "failed to resize machine with id: %s", machineID)
261 }
262 return nil
263 }
264
265 // RenameMachine renames an existing machine.
266 // See API docs: http://apidocs.joyent.com/cloudapi/#RenameMachine
267 func (c *Client) RenameMachine(machineID, machineName string) error {
268 req := request{
269 method: client.POST,
270 url: fmt.Sprintf("%s/%s?action=%s&name=%s", apiMachines, machineID, actionRename, machineName),
271 expectedStatus: http.StatusAccepted,
272 }
273 if _, err := c.sendRequest(req); err != nil {
274 return errors.Newf(err, "failed to rename machine with id: %s", machineID)
275 }
276 return nil
277 }
278
279 // DeleteMachine allows you to completely destroy a machine. Machine must be in the 'stopped' state.
280 // See API docs: http://apidocs.joyent.com/cloudapi/#DeleteMachine
281 func (c *Client) DeleteMachine(machineID string) error {
282 req := request{
283 method: client.DELETE,
284 url: makeURL(apiMachines, machineID),
285 expectedStatus: http.StatusNoContent,
286 }
287 if _, err := c.sendRequest(req); err != nil {
288 return errors.Newf(err, "failed to delete machine with id %s", machineID)
289 }
290 return nil
291 }
292
293 // MachineAudit provides a list of machine's accomplished actions, (sorted from
294 // latest to older one).
295 // See API docs: http://apidocs.joyent.com/cloudapi/#MachineAudit
296 func (c *Client) MachineAudit(machineID string) ([]AuditAction, error) {
297 var resp []AuditAction
298 req := request{
299 method: client.GET,
300 url: makeURL(apiMachines, machineID, apiAudit),
301 resp: &resp,
302 }
303 if _, err := c.sendRequest(req); err != nil {
304 return nil, errors.Newf(err, "failed to get actions for machine with id %s", machineID)
305 }
306 return resp, nil
307 }