/
internal.go
621 lines (516 loc) · 16 KB
/
internal.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
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
/*
Copyright © 2020-2024 Daniele Rondina <geaaru@gmail.com>
See AUTHORS and LICENSE for the license details and contributors.
*/
package executor
import (
"fmt"
"strings"
"time"
lxd "github.com/canonical/lxd/client"
lxd_api "github.com/canonical/lxd/shared/api"
lxd_cli "github.com/canonical/lxd/shared/cmd"
)
func (e *LxdCExecutor) LaunchContainer(name, fingerprint string, profiles []string) error {
return e.LaunchContainerType(name, fingerprint, profiles, map[string]string{}, e.Ephemeral)
}
func (e *LxdCExecutor) LaunchContainerWithConfig(name, fingerprint string, profiles []string, configMap map[string]string) error {
return e.LaunchContainerType(name, fingerprint, profiles, configMap, e.Ephemeral)
}
func (e *LxdCExecutor) LaunchContainerType(name, fingerprint string, profiles []string, configMap map[string]string, ephemeral bool) error {
var err error
var image *lxd_api.Image
var remoteOperation lxd.RemoteOperation
var opInfo *lxd_api.Operation
if len(profiles) == 0 {
profiles = []string{"default"}
}
// Note: Avoid to create devece map for root /. We consider to handle this
// as profile. Same for different storage.
devicesMap := map[string]map[string]string{}
// Retrieve image info
image, _, err = e.LxdClient.GetImage(fingerprint)
if err != nil {
return err
}
if e.LegacyApi {
// Setup container creation request
req := lxd_api.ContainersPost{
Name: name,
}
req.Config = configMap
req.Devices = devicesMap
req.Profiles = profiles
req.Ephemeral = ephemeral
// Create the container
remoteOperation, err = e.LxdClient.CreateContainerFromImage(e.LxdClient, *image, req)
if err != nil {
return err
}
} else {
// Setup container creation request
req := lxd_api.InstancesPost{
Name: name,
Type: lxd_api.InstanceTypeContainer,
}
req.Config = configMap
req.Devices = devicesMap
req.Profiles = profiles
req.Ephemeral = ephemeral
// Create the container
remoteOperation, err = e.LxdClient.CreateInstanceFromImage(e.LxdClient, *image, req)
if err != nil {
return err
}
}
// Watch the background operation
progress := lxd_cli.ProgressRenderer{
Format: "Retrieving image: %s",
Quiet: false,
}
_, err = remoteOperation.AddHandler(progress.UpdateOp)
if err != nil {
progress.Done("")
return err
}
err = e.WaitOperation(remoteOperation, &progress)
if err != nil {
progress.Done("")
return err
}
progress.Done("")
// Extract the container name
opInfo, err = remoteOperation.GetTarget()
if err != nil {
return err
}
containers, ok := opInfo.Resources["containers"]
if !ok || len(containers) == 0 {
return fmt.Errorf("didn't get any affected image, container or snapshot from server")
}
e.Emitter.Emits(LxdContainerCreated, map[string]interface{}{
"name": name,
"profiles": profiles,
"ephemeral": e.Ephemeral,
})
// Start container
return e.DoAction2Container(name, "start")
}
func (e *LxdCExecutor) WaitOperation(rawOp interface{}, p *lxd_cli.ProgressRenderer) error {
var err error = nil
// NOTE: currently on ARM we have a weird behavior where the process that waits
// for LXD operation often remain blocked. It seems related to a concurrency
// problem on initializing Golang channel.
// As a workaround, I sleep some seconds before waiting for a response.
duration, err := time.ParseDuration(fmt.Sprintf("%ds", e.WaitSleep))
if err == nil {
time.Sleep(duration)
}
// TODO: Verify if could be a valid idea permit to use wait not cancelable.
// err = op.Wait()
if p != nil {
err = lxd_cli.CancelableWait(rawOp, p)
} else {
err = lxd_cli.CancelableWait(rawOp, nil)
}
return err
}
func (e *LxdCExecutor) DoAction2Container(name, action string) error {
var err error
var ephemeral bool
var containerStatus string
var operation lxd.Operation
if e.LegacyApi {
container, _, err := e.LxdClient.GetContainer(name)
if err != nil {
if action == "stop" {
e.Emitter.WarnLog(false,
fmt.Sprintf("Container %s not found. Already stopped nothing to do.", name))
return nil
}
return err
}
ephemeral = container.Ephemeral
containerStatus = container.Status
} else {
instance, _, err := e.LxdClient.GetInstance(name)
if err != nil {
if action == "stop" {
e.Emitter.WarnLog(false,
fmt.Sprintf("Container %s not found. Already stopped nothing to do.", name))
return nil
}
return err
}
ephemeral = instance.Ephemeral
containerStatus = instance.Status
}
if action == "start" && containerStatus == "Started" {
e.Emitter.WarnLog(false,
fmt.Sprintf("Container %s is already started!", name))
return nil
} else if action == "stop" && containerStatus == "Stopped" {
if ephemeral {
// POST: the container is stopped and/or in a weird status. I delete it.
e.Emitter.WarnLog(false,
fmt.Sprintf("Container %s is already stopped but ephemeral. Forcing delete.", name))
var currOper lxd.Operation
// Delete container
if e.LegacyApi {
currOper, err = e.LxdClient.DeleteContainer(name)
} else {
currOper, err = e.LxdClient.DeleteInstance(name)
}
if err != nil {
e.Emitter.ErrorLog(false, "Error on delete container: "+err.Error())
return err
}
_ = e.WaitOperation(currOper, nil)
} else {
e.Emitter.WarnLog(false,
fmt.Sprintf("Container %s is already stopped!", name))
}
return nil
}
if e.LegacyApi {
req := lxd_api.ContainerStatePut{
Action: action,
Timeout: 120,
Force: false,
Stateful: false,
}
operation, err = e.LxdClient.UpdateContainerState(name, req, "")
} else {
req := lxd_api.InstanceStatePut{
Action: action,
Timeout: 120,
Force: false,
Stateful: false,
}
operation, err = e.LxdClient.UpdateInstanceState(name, req, "")
}
if err != nil {
e.Emitter.ErrorLog(false, "Error on update container state: "+err.Error())
return err
}
progress := lxd_cli.ProgressRenderer{
Quiet: false,
}
_, err = operation.AddHandler(progress.UpdateOp)
if err != nil {
e.Emitter.ErrorLog(false, "Error on add handler to progress bar: "+err.Error())
progress.Done("")
return err
}
err = e.WaitOperation(operation, &progress)
progress.Done("")
if err != nil {
e.Emitter.ErrorLog(false,
fmt.Sprintf("Error on stop container %s: %s", name, err))
return err
}
if action == "start" {
e.Emitter.Emits(LxdContainerStarted, map[string]interface{}{
"name": name,
})
} else {
e.Emitter.Emits(LxdContainerStopped, map[string]interface{}{
"name": name,
})
}
return nil
}
// Retrieve Image from alias or fingerprint to a specific remote.
func (e *LxdCExecutor) GetImage(image string, remote lxd.ImageServer) (*lxd_api.Image, error) {
var err error
var img *lxd_api.Image
var aliasEntry *lxd_api.ImageAliasesEntry
img, _, err = remote.GetImage(image)
if err != nil {
// POST: no image found with input fingerprint
// Try to search an image as alias.
connInfo, _ := remote.GetConnectionInfo()
remoteURL := ""
if connInfo != nil {
remoteURL = connInfo.URL
}
// Check if exists an image with input alias
aliasEntry, _, err = remote.GetImageAlias(image)
if err != nil {
e.Emitter.DebugLog(false,
fmt.Sprintf("On search image with alias %s receive from remote '%s': %s",
image, remoteURL, err.Error()))
img = nil
} else {
// POST: Find image with alias and so I try to retrieve api.Image
// object with all information.
img, _, err = remote.GetImage(aliasEntry.Target)
}
}
return img, err
}
// Delete alias from image of a specific ContainerServer if available
func (e *LxdCExecutor) DeleteImageAliases4Alias(imageAlias string, server lxd.ContainerServer) error {
var err error
var img *lxd_api.Image
img, _ = e.GetImage(imageAlias, server)
if img != nil {
err = e.DeleteImageAliases(img, server)
}
return err
}
// Delete all local alias defined on input Image to avoid conflict on pull.
func (e *LxdCExecutor) DeleteImageAliases(image *lxd_api.Image, server lxd.ContainerServer) error {
for _, alias := range image.Aliases {
// Retrieve image with alias
aliasEntry, _, _ := server.GetImageAlias(alias.Name)
if aliasEntry != nil {
// TODO: See how handle correctly this use case
e.Emitter.DebugLog(false,
fmt.Sprintf("Found old image %s with alias %s. I drop alias from it.",
aliasEntry.Target, alias.Name))
err := server.DeleteImageAlias(alias.Name)
if err != nil {
return err
}
}
}
return nil
}
func (e *LxdCExecutor) CopyImage(imageFingerprint string, remote lxd.ImageServer, to lxd.ContainerServer) error {
var err error
// Get the image information
i, _, err := remote.GetImage(imageFingerprint)
if err != nil {
return err
}
// NOTE: we can't use copy aliases here because
// LXD doesn't handle correctly concurrency copy
// of the same image.
// I use i.Aliases after that image is been copied.
copyArgs := &lxd.ImageCopyArgs{
Public: true,
AutoUpdate: false,
}
// Ask LXD to copy the image from the remote server
// CopyImage return an lxd.RemoteOperation does not implement lxd.Operation
// (missing Cancel method) so DownloadImage is not s
remoteOperation, err := to.CopyImage(remote, *i, copyArgs)
if err != nil {
e.Emitter.ErrorLog(false,
"Error on create copy image task "+err.Error())
return err
}
// Watch the background operation
progress := lxd_cli.ProgressRenderer{
Format: "Retrieving image: %s",
Quiet: false,
}
_, err = remoteOperation.AddHandler(progress.UpdateOp)
if err != nil {
progress.Done("")
return err
}
err = e.WaitOperation(remoteOperation, &progress)
progress.Done("")
if err != nil {
e.Emitter.ErrorLog(false, "Error on copy image "+err.Error())
return err
}
// Add aliases to images
for _, alias := range i.Aliases {
// Ignore error for handle parallel fetching.
e.AddAlias2Image(i.Fingerprint, alias, e.LxdClient)
}
e.Emitter.DebugLog(false, fmt.Sprintf("Image %s copy locally.", imageFingerprint))
return nil
}
func (e *LxdCExecutor) DownloadImage(imageFingerprint string, remote lxd.ImageServer) error {
return e.CopyImage(imageFingerprint, remote, e.LxdClient)
}
func (e *LxdCExecutor) AddAlias2Image(fingerprint string, alias lxd_api.ImageAlias,
server lxd.ContainerServer) error {
aliasPost := lxd_api.ImageAliasesPost{}
aliasPost.Name = alias.Name
aliasPost.Description = alias.Description
aliasPost.Target = fingerprint
return server.CreateImageAlias(aliasPost)
}
func (e *LxdCExecutor) PullImage(imageAlias, imageRemoteServer string) (string, error) {
var err error
var imageFingerprint, remote_name string
var remote lxd.ImageServer
var noRemoteImageFound = false
e.Emitter.InfoLog(false, "Searching image: "+imageAlias)
// Find image hashing id
imageFingerprint, remote, remote_name, err = e.FindImage(imageAlias, imageRemoteServer)
if err != nil {
noRemoteImageFound = true
if strings.Contains(imageAlias, "/") {
// Is not a fingerprint alias. I can't ensure right image.
return "", err
}
// POST: Try to see if there a local image with the fingerprint
imageFingerprint = imageAlias
}
if imageFingerprint == imageAlias {
e.Emitter.InfoLog(false, "Use directly fingerprint "+imageAlias)
} else {
e.Emitter.InfoLog(false,
"For image "+imageAlias+" found fingerprint "+imageFingerprint)
}
// Check if image is already present locally else we receive an error.
image, _, _ := e.LxdClient.GetImage(imageFingerprint)
if image == nil {
if noRemoteImageFound {
// No local image found. I return error.
return "", err
}
// NOTE: In concurrency could be happens that different image that
// share same aliases generate reset of aliases but
// if I work with fingerprint after FindImage I can ignore
// aliases.
// Delete local image with same target aliases to avoid error on pull.
err = e.DeleteImageAliases4Alias(imageAlias, e.LxdClient)
// Try to pull image to lxd instance
e.Emitter.InfoLog(false, fmt.Sprintf(
"Try to download image %s from remote %s...",
imageFingerprint, remote_name,
))
err = e.DownloadImage(imageFingerprint, remote)
} else {
e.Emitter.DebugLog(false,
"Image "+imageFingerprint+" already present.")
err = nil
}
return imageFingerprint, err
}
func (e *LxdCExecutor) FindImage(image, imageRemoteServer string) (string, lxd.ImageServer, string, error) {
var err error
var tmp_srv, srv lxd.ImageServer
var img, tmp_img *lxd_api.Image
var fingerprint string = ""
var srv_name string = ""
if imageRemoteServer == "" && !e.P2PMode {
// Force images if p2m mode is disabled.
imageRemoteServer = "images"
}
for remote, server := range e.LxdConfig.Remotes {
if remote == "local" && e.LocalDisable {
continue
}
if imageRemoteServer != "" && remote != imageRemoteServer && !e.P2PMode {
e.Emitter.DebugLog(false, fmt.Sprintf(
"Skipping remote %s. I will use %s.", remote, imageRemoteServer))
continue
}
e.Emitter.DebugLog(false, fmt.Sprintf(
"Found remote %s. I will search the image %s",
remote, image))
tmp_srv, err = e.LxdConfig.GetImageServer(remote)
if err != nil {
err = nil
e.Emitter.ErrorLog(false, fmt.Sprintf(
"Error on retrieve ImageServer for remote %s at addr %s",
remote, server.Addr,
))
continue
}
tmp_img, err = e.GetImage(image, tmp_srv)
if err != nil {
// POST: No image found with input alias/fingerprint.
// I go ahead to next remote
err = nil
continue
}
if img != nil {
// POST: A previous image is already found
if tmp_img.CreatedAt.After(img.CreatedAt) {
img = tmp_img
srv = tmp_srv
srv_name = remote
fingerprint = img.Fingerprint
}
} else {
// POST: first image matched
img = tmp_img
fingerprint = img.Fingerprint
srv = tmp_srv
srv_name = remote
}
}
if fingerprint == "" {
err = fmt.Errorf("No image found with alias or fingerprint %s", image)
}
return fingerprint, srv, srv_name, err
}
func (l *LxdCExecutor) CreateImageFromContainer(containerName string, aliases []string, properties map[string]string, compressionAlgorithm string, public bool) (string, error) {
var err error
imageAliases := []lxd_api.ImageAlias{}
compression := "none"
// TODO: Check how enable Expires on image created.
// Check if there is already a local image with same alias. If yes I drop alias.
for _, aliasName := range aliases {
aliasEntry, _, _ := l.LxdClient.GetImageAlias(aliasName)
if aliasEntry != nil {
l.Emitter.DebugLog(false, fmt.Sprintf(
"Found old image %s with alias %s. I drop alias from it.",
aliasEntry.Target, aliasName))
err = l.LxdClient.DeleteImageAlias(aliasName)
if err != nil {
return "", err
}
}
// Reformat aliases
alias := lxd_api.ImageAlias{}
alias.Name = aliasName
imageAliases = append(imageAliases, alias)
}
if compressionAlgorithm != "" {
compression = compressionAlgorithm
}
// Create the image
req := lxd_api.ImagesPost{
Source: &lxd_api.ImagesPostSource{
Type: "container",
Name: containerName,
},
// CompressionAlgorithm contains name of the binary called by LXD for compression.
// For any customization create custom script that wrap compression tools.
CompressionAlgorithm: compression,
}
req.Properties = properties
req.Public = public
// TODO: Take time and calculate how much time is required for create image
l.Emitter.InfoLog(false,
fmt.Sprintf("Starting creation of Image with aliases %s...", aliases))
op, err := l.LxdClient.CreateImage(req, nil)
if err != nil {
return "", err
}
err = l.WaitOperation(nil, nil)
if err != nil {
return "", err
}
opAPI := op.Get()
// Grab the fingerprint
fingerprint := opAPI.Metadata["fingerprint"].(string)
// Get the source image
_, _, err = l.LxdClient.GetImage(fingerprint)
if err != nil {
return "", err
}
l.Emitter.InfoLog(false, fmt.Sprintf(
"For container %s created image %s. Adding aliases %s to image.",
containerName, fingerprint, aliases))
for _, alias := range imageAliases {
aliasPost := lxd_api.ImageAliasesPost{}
aliasPost.Name = alias.Name
aliasPost.Target = fingerprint
err := l.LxdClient.CreateImageAlias(aliasPost)
if err != nil {
return "", fmt.Errorf("Failed to create alias %s", alias.Name)
}
}
return fingerprint, nil
}