forked from juju/juju
/
client_instance.go
368 lines (311 loc) · 9.69 KB
/
client_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
// Copyright 2015 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
// +build go1.3
package lxdclient
import (
"bytes"
"fmt"
"io"
"os"
"strings"
"github.com/juju/errors"
"github.com/lxc/lxd/shared"
"github.com/lxc/lxd/shared/api"
"github.com/juju/juju/container"
"github.com/juju/juju/network"
)
type Device map[string]string
type Devices map[string]Device
type DiskDevice struct {
Path string
Source string
Pool string
ReadOnly bool
}
type File struct {
Content []byte
Path string
GID int
UID int
Mode os.FileMode
}
type Files []File
// TODO(ericsnow) We probably need to address some of the things that
// get handled in container/lxc/clonetemplate.go.
type rawInstanceClient interface {
ListContainers() ([]api.Container, error)
ContainerInfo(name string) (*api.Container, error)
Init(name string, imgremote string, image string, profiles *[]string, config map[string]string, devices map[string]map[string]string, ephem bool) (*api.Response, error)
Action(name string, action shared.ContainerAction, timeout int, force bool, stateful bool) (*api.Response, error)
Delete(name string) (*api.Response, error)
WaitForSuccess(waitURL string) error
ContainerState(name string) (*api.ContainerState, error)
ContainerDeviceAdd(container, devname, devtype string, props []string) (*api.Response, error)
ContainerDeviceDelete(container, devname string) (*api.Response, error)
PushFile(container, path string, gid int, uid int, mode string, buf io.ReadSeeker) error
}
type instanceClient struct {
raw rawInstanceClient
remote string
}
func deviceProperties(device Device) []string {
var props []string
for k, v := range device {
props = append(props, fmt.Sprintf("%s=%s", k, v))
}
return props
}
func (client *instanceClient) addInstance(spec InstanceSpec) error {
imageRemote := spec.ImageRemote
if imageRemote == "" {
imageRemote = client.remote
}
imageAlias := spec.Image
var profiles *[]string
if len(spec.Profiles) > 0 {
profiles = &spec.Profiles
}
// TODO(ericsnow) Copy the image first?
lxdDevices := make(map[string]map[string]string, len(spec.Devices))
for name, device := range spec.Devices {
lxdDevice := make(Device, len(device))
for key, value := range device {
lxdDevice[key] = value
}
lxdDevices[name] = lxdDevice
}
config := spec.config()
resp, err := client.raw.Init(spec.Name, imageRemote, imageAlias, profiles, config, lxdDevices, spec.Ephemeral)
if err != nil {
return errors.Trace(err)
}
// Init is an async operation, since the tar -xvf (or whatever) might
// take a while; the result is an LXD operation id, which we can just
// wait on until it is finished.
if err := client.raw.WaitForSuccess(resp.Operation); err != nil {
// TODO(ericsnow) Handle different failures (from the async
// operation) differently?
return errors.Trace(err)
}
for _, file := range spec.Files {
logger.Infof("pushing file %q to container %q", file.Path, spec.Name)
err := client.raw.PushFile(spec.Name, file.Path, file.GID, file.UID, file.Mode.String(), bytes.NewReader(file.Content))
if err != nil {
return errors.Trace(err)
}
}
return nil
}
func (client *instanceClient) startInstance(spec InstanceSpec) error {
timeout := -1
force := false
stateful := false
resp, err := client.raw.Action(spec.Name, shared.Start, timeout, force, stateful)
if err != nil {
return errors.Trace(err)
}
if err := client.raw.WaitForSuccess(resp.Operation); err != nil {
// TODO(ericsnow) Handle different failures (from the async
// operation) differently?
return errors.Trace(err)
}
return nil
}
// AddInstance creates a new instance based on the spec's data and
// returns it. The instance will be created using the client.
func (client *instanceClient) AddInstance(spec InstanceSpec) (*Instance, error) {
if err := client.addInstance(spec); err != nil {
return nil, errors.Trace(err)
}
if err := client.startInstance(spec); err != nil {
if err := client.removeInstance(spec.Name); err != nil {
logger.Errorf("could not remove container %q after starting it failed", spec.Name)
}
return nil, errors.Trace(err)
}
inst, err := client.Instance(spec.Name)
if err != nil {
return nil, errors.Trace(err)
}
inst.spec = &spec
return inst, nil
}
// Instance gets the up-to-date info about the given instance
// and returns it.
func (client *instanceClient) Instance(name string) (*Instance, error) {
info, err := client.raw.ContainerInfo(name)
if err != nil {
return nil, errors.Trace(err)
}
inst := newInstance(info, nil)
return inst, nil
}
func (client *instanceClient) Status(name string) (string, error) {
info, err := client.raw.ContainerInfo(name)
if err != nil {
return "", errors.Trace(err)
}
return info.Status, nil
}
// Instances sends a request to the API for a list of all instances
// (in the Client's namespace) for which the name starts with the
// provided prefix. The result is also limited to those instances with
// one of the specified statuses (if any).
func (client *instanceClient) Instances(prefix string, statuses ...string) ([]Instance, error) {
infos, err := client.raw.ListContainers()
if err != nil {
return nil, errors.Trace(err)
}
var insts []Instance
for _, info := range infos {
name := info.Name
if prefix != "" && !strings.HasPrefix(name, prefix) {
continue
}
if len(statuses) > 0 && !checkStatus(info, statuses) {
continue
}
inst := newInstance(&info, nil)
insts = append(insts, *inst)
}
return insts, nil
}
func checkStatus(info api.Container, statuses []string) bool {
for _, status := range statuses {
statusCode := allStatuses[status]
if info.StatusCode == statusCode {
return true
}
}
return false
}
// removeInstance sends a request to the API to remove the instance
// with the provided ID. The call blocks until the instance is removed
// (or the request fails).
func (client *instanceClient) removeInstance(name string) error {
info, err := client.raw.ContainerInfo(name)
if err != nil {
return errors.Trace(err)
}
//if info.Status.StatusCode != 0 && info.Status.StatusCode != shared.Stopped {
if info.StatusCode != api.Stopped {
timeout := -1
force := true
stateful := false
resp, err := client.raw.Action(name, shared.Stop, timeout, force, stateful)
if err != nil {
return errors.Trace(err)
}
if err := client.raw.WaitForSuccess(resp.Operation); err != nil {
// TODO(ericsnow) Handle different failures (from the async
// operation) differently?
return errors.Trace(err)
}
}
resp, err := client.raw.Delete(name)
if err != nil {
return errors.Trace(err)
}
if err := client.raw.WaitForSuccess(resp.Operation); err != nil {
// TODO(ericsnow) Handle different failures (from the async
// operation) differently?
return errors.Trace(err)
}
return nil
}
// RemoveInstances sends a request to the API to terminate all
// instances (in the Client's namespace) that match one of the
// provided IDs. If a prefix is provided, only IDs that start with the
// prefix will be considered. The call blocks until all the instances
// are removed or the request fails.
func (client *instanceClient) RemoveInstances(prefix string, names ...string) error {
if len(names) == 0 {
return nil
}
instances, err := client.Instances(prefix)
if err != nil {
return errors.Annotatef(err, "while removing instances %v", names)
}
var failed []string
for _, name := range names {
if !checkInstanceName(name, instances) {
// We ignore unknown instance names.
continue
}
if err := client.removeInstance(name); err != nil {
failed = append(failed, name)
logger.Errorf("while removing instance %q: %v", name, err)
}
}
if len(failed) != 0 {
return errors.Errorf("some instance removals failed: %v", failed)
}
return nil
}
func checkInstanceName(name string, instances []Instance) bool {
for _, inst := range instances {
if inst.Name == name {
return true
}
}
return false
}
// Addresses returns the list of network.Addresses for this instance. It
// converts the information that LXD tracks into the Juju network model.
func (client *instanceClient) Addresses(name string) ([]network.Address, error) {
state, err := client.raw.ContainerState(name)
if err != nil {
return nil, err
}
networks := state.Network
if networks == nil {
return []network.Address{}, nil
}
addrs := []network.Address{}
for name, net := range networks {
if name == container.DefaultLxcBridge || name == container.DefaultLxdBridge {
continue
}
for _, addr := range net.Addresses {
if err != nil {
return nil, err
}
addr := network.NewAddress(addr.Address)
if addr.Scope == network.ScopeLinkLocal || addr.Scope == network.ScopeMachineLocal {
logger.Tracef("for container %q ignoring address %q", name, addr)
continue
}
addrs = append(addrs, addr)
}
}
return addrs, nil
}
// AttachDisk attaches a disk to an instance.
func (client *instanceClient) AttachDisk(instanceName, deviceName string, disk DiskDevice) error {
props := []string{"path=" + disk.Path, "source=" + disk.Source}
if disk.Pool != "" {
props = append(props, "pool="+disk.Pool)
}
if disk.ReadOnly {
props = append(props, "readonly=true")
}
resp, err := client.raw.ContainerDeviceAdd(instanceName, deviceName, "disk", props)
if err != nil {
return errors.Trace(err)
}
if err := client.raw.WaitForSuccess(resp.Operation); err != nil {
return errors.Trace(err)
}
return nil
}
// RemoveDevice removes a device from an instance.
func (client *instanceClient) RemoveDevice(instanceName, deviceName string) error {
resp, err := client.raw.ContainerDeviceDelete(instanceName, deviceName)
if err != nil {
return errors.Trace(err)
}
if err := client.raw.WaitForSuccess(resp.Operation); err != nil {
return errors.Trace(err)
}
return nil
}