/
instance.go
393 lines (344 loc) · 10.5 KB
/
instance.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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
// -*- Mode: Go; indent-tabs-mode: t -*-
/*
* This file is part of AMS SDK
* Copyright 2021 Canonical Ltd.
*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the Lesser GNU General Public License version 3, as published
* by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranties of MERCHANTABILITY, SATISFACTORY
* QUALITY, or FITNESS FOR A PARTICULAR PURPOSE. See the Lesser GNU General Public
* License for more details.
*
* You should have received a copy of the Lesser GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package client
import (
"bytes"
"encoding/json"
"io"
"net/http"
"strconv"
api "github.com/anbox-cloud/ams-sdk/api/ams"
"github.com/anbox-cloud/ams-sdk/internal/ams/shared"
errs "github.com/anbox-cloud/ams-sdk/internal/ams/shared/errors"
"github.com/anbox-cloud/ams-sdk/internal/ams/shared/rest/client"
"github.com/gorilla/websocket"
)
// The InstanceExecArgs struct is used to pass additional options during a
// instance shell session
type InstanceExecArgs struct {
Stdin io.ReadCloser
Stdout io.WriteCloser
Stderr io.WriteCloser
Control func(conn *websocket.Conn)
DataDone chan bool
}
// ListInstancesWithFilters lists all available instances the AMS service currently manages
func (c *clientImpl) ListInstancesWithFilters(filters []string) ([]api.Instance, error) {
instances := []api.Instance{}
if !c.hasInstanceSupport {
containers, err := c.ListContainersWithFilters(filters)
if err != nil {
return nil, err
}
for _, c := range containers {
inst, err := api.MapContainerToInstance(&c)
if err != nil {
return nil, err
}
instances = append(instances, inst)
}
} else {
params, err := convertFiltersToParams(filters)
if err != nil {
return nil, err
}
params["recursion"] = "1"
_, err = c.QueryStruct("GET", client.APIPath("instances"), params, nil, nil, "", &instances)
if err != nil {
return nil, err
}
}
return instances, nil
}
// ListInstances lists all available instances the AMS service currently manages
func (c *clientImpl) ListInstances() ([]api.Instance, error) {
instances := []api.Instance{}
if !c.hasInstanceSupport {
containers, err := c.ListContainers()
if err != nil {
return nil, err
}
for _, c := range containers {
inst, err := api.MapContainerToInstance(&c)
if err != nil {
return nil, err
}
instances = append(instances, inst)
}
} else {
params := client.QueryParams{
"recursion": "1",
}
_, err := c.QueryStruct("GET", client.APIPath("instances"), params, nil, nil, "", &instances)
if err != nil {
return nil, err
}
}
return instances, nil
}
// LaunchInstance launches a single new instance on the AMS endpoint
func (c *clientImpl) LaunchInstance(details *api.InstancesPost, noWait bool) (client.Operation, error) {
if !c.hasInstanceSupport {
d := api.ContainersPost{
ApplicationID: details.ApplicationID,
ApplicationVersion: details.ApplicationVersion,
ImageID: details.ImageID,
ImageVersion: details.ImageVersion,
Node: details.Node,
Userdata: details.Userdata,
Addons: details.Addons,
Services: details.Services,
CPUs: details.Resources.CPUs,
DiskSize: details.Resources.DiskSize,
Memory: details.Resources.Memory,
GPUSlots: details.Resources.GPUSlots,
VPUSlots: details.Resources.VPUSlots,
Tags: details.Tags,
}
d.Config.Platform = details.Config.Platform
d.Config.BootPackage = details.Config.BootPackage
d.Config.BootActivity = details.Config.BootActivity
d.Config.MetricsServer = details.Config.MetricsServer
d.Config.DisableWatchdog = details.Config.DisableWatchdog
d.Config.Features = details.Config.Features
d.Config.DevMode = details.Config.DevMode
d.NoStart = details.NoStart
if len(d.ImageID) > 0 && (d.CPUs == nil || d.Memory == nil || d.DiskSize == nil) {
return nil, errs.NewInvalidArgument("resources")
}
return c.LaunchContainer(&d, noWait)
}
if details.Type == api.InstanceTypeVM && !c.HasExtension("vm_support") {
return nil, errs.NewErrNotSupported("VM")
}
b, err := json.Marshal(details)
if err != nil {
return nil, err
}
params := client.QueryParams{"no_wait": strconv.FormatBool(noWait)}
op, _, err := c.QueryOperation("POST", client.APIPath("instances"), params, nil, bytes.NewReader(b), "")
return op, err
}
// RetrieveInstanceByID retrieves a single instance by its ID
func (c *clientImpl) RetrieveInstanceByID(id string) (*api.Instance, string, error) {
if len(id) == 0 {
return nil, "", errs.NewInvalidArgument("id")
}
if !c.hasInstanceSupport {
container, etag, err := c.RetrieveContainerByID(id)
if err != nil {
return nil, "", err
}
instance, err := api.MapContainerToInstance(container)
if err != nil {
return nil, "", err
}
return &instance, etag, err
}
instance := &api.Instance{}
etag, err := c.QueryStruct("GET", client.APIPath("instances", id), nil, nil, nil, "", instance)
return instance, etag, err
}
// UpdateInstanceByID updates an existing instance specified by its id
func (c *clientImpl) UpdateInstanceByID(id string, details *api.InstancePatch, noWait bool) (client.Operation, error) {
if len(id) == 0 {
return nil, errs.NewInvalidArgument("id")
}
if !c.hasInstanceSupport {
return c.UpdateContainerByID(id, &api.ContainerPatch{
DesiredStatus: details.DesiredStatus,
}, noWait)
}
b, err := json.Marshal(details)
if err != nil {
return nil, err
}
params := client.QueryParams{"no_wait": strconv.FormatBool(noWait)}
op, _, err := c.QueryOperation("PATCH", client.APIPath("instances", id), params, nil, bytes.NewReader(b), "")
return op, err
}
// DeleteInstanceByID deletes a single instance specified by its id
func (c *clientImpl) DeleteInstanceByID(id string, force bool) (client.Operation, error) {
if len(id) == 0 {
return nil, errs.NewInvalidArgument("id")
}
if !c.hasInstanceSupport {
return c.DeleteContainerByID(id, force)
}
details := api.InstanceDelete{
Force: force,
}
b, err := json.Marshal(details)
if err != nil {
return nil, err
}
op, _, err := c.QueryOperation("DELETE", client.APIPath("instances", id), nil, nil, bytes.NewReader(b), "")
return op, err
}
// DeleteInstances deletes multiple instances in a bulk operation
func (c *clientImpl) DeleteInstances(ids []string, force bool) (client.Operation, error) {
if len(ids) == 0 {
return nil, errs.NewInvalidArgument("ids")
}
if !c.hasInstanceSupport {
return c.DeleteContainers(ids, force)
}
details := api.InstancesDelete{
IDs: ids,
Force: force,
}
b, err := json.Marshal(details)
if err != nil {
return nil, err
}
op, _, err := c.QueryOperation("DELETE", client.APIPath("instances"), nil, nil, bytes.NewReader(b), "")
return op, err
}
// RetrieveInstanceLog retrieves a specific log file of an instance
func (c *clientImpl) RetrieveInstanceLog(id, name string, downloader func(header *http.Header, body io.ReadCloser) error) error {
if len(id) == 0 {
return errs.NewInvalidArgument("id")
}
if len(name) == 0 {
return errs.NewInvalidArgument("name")
}
if !c.hasInstanceSupport {
return c.RetrieveContainerLog(id, name, downloader)
}
return c.download(client.APIPath("instances", id, "logs", name), nil, nil, downloader)
}
// ExecuteInstance requests that AMS opens a shell inside an instance
func (c *clientImpl) ExecuteInstance(id string, details *api.InstanceExecPost, args *InstanceExecArgs) (client.Operation, error) {
if len(id) == 0 {
return nil, errs.NewInvalidArgument("id")
}
if !c.hasInstanceSupport {
return c.ExecuteContainer(id, &api.ContainerExecPost{
Command: details.Command,
Environment: details.Environment,
Interactive: details.Interactive,
Width: details.Width,
Height: details.Height,
}, &ContainerExecArgs{
Stdin: args.Stdin,
Stdout: args.Stdout,
Stderr: args.Stderr,
Control: args.Control,
DataDone: args.DataDone,
})
}
b, err := json.Marshal(details)
if err != nil {
return nil, err
}
op, _, err := c.QueryOperation("POST", client.APIPath("instances", id, "exec"), nil, nil, bytes.NewReader(b), "")
if err != nil {
return nil, err
}
if args != nil {
opAPI := op.Get()
fds := map[string]string{}
value, ok := opAPI.Metadata["fds"]
if ok {
values := value.(map[string]interface{})
for k, v := range values {
fds[k] = v.(string)
}
}
if args.Control != nil && fds["control"] != "" {
conn, err := c.getOperationWebsocket(opAPI.ID, fds["control"])
if err != nil {
return nil, err
}
go args.Control(conn)
}
if details.Interactive {
// Handle interactive sections
if args.Stdin != nil && args.Stdout != nil {
// Connect to the websocket
conn, err := c.getOperationWebsocket(opAPI.ID, fds["0"])
if err != nil {
return nil, err
}
// And attach stdin and stdout to it
go func() {
shared.WebsocketSendStream(conn, args.Stdin, -1)
<-shared.WebsocketRecvStream(args.Stdout, conn)
conn.Close()
if args.DataDone != nil {
close(args.DataDone)
}
}()
} else {
if args.DataDone != nil {
close(args.DataDone)
}
}
} else {
dones := map[int]chan bool{}
conns := []*websocket.Conn{}
// Handle stdin
if fds["0"] != "" {
conn, err := c.getOperationWebsocket(opAPI.ID, fds["0"])
if err != nil {
return nil, err
}
conns = append(conns, conn)
dones[0] = shared.WebsocketSendStream(conn, args.Stdin, -1)
}
// Handle stdout
if fds["1"] != "" {
conn, err := c.getOperationWebsocket(opAPI.ID, fds["1"])
if err != nil {
return nil, err
}
conns = append(conns, conn)
dones[1] = shared.WebsocketRecvStream(args.Stdout, conn)
}
// Handle stderr
if fds["2"] != "" {
conn, err := c.getOperationWebsocket(opAPI.ID, fds["2"])
if err != nil {
return nil, err
}
conns = append(conns, conn)
dones[2] = shared.WebsocketRecvStream(args.Stderr, conn)
}
// Wait for everything to be done
go func() {
for i, chDone := range dones {
// Skip stdin, dealing with it separately below
if i == 0 {
continue
}
<-chDone
}
if fds["0"] != "" {
args.Stdin.Close()
}
for _, conn := range conns {
conn.Close()
}
if args.DataDone != nil {
close(args.DataDone)
}
}()
}
}
return op, nil
}