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
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
|
// +build !remoteclient
package adapter
import (
"context"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strconv"
"strings"
"sync"
"syscall"
"time"
"github.com/containers/libpod/cmd/podman/cliconfig"
"github.com/containers/libpod/cmd/podman/shared"
"github.com/containers/libpod/libpod"
"github.com/containers/libpod/pkg/adapter/shortcuts"
"github.com/containers/storage"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
)
// GetLatestContainer gets the latest Container and wraps it in an adapter Container
func (r *LocalRuntime) GetLatestContainer() (*Container, error) {
Container := Container{}
c, err := r.Runtime.GetLatestContainer()
Container.Container = c
return &Container, err
}
// GetAllContainers gets all Containers and wraps each one in an adapter Container
func (r *LocalRuntime) GetAllContainers() ([]*Container, error) {
var containers []*Container
allContainers, err := r.Runtime.GetAllContainers()
if err != nil {
return nil, err
}
for _, c := range allContainers {
containers = append(containers, &Container{c})
}
return containers, nil
}
// LookupContainer gets a Container by name or id and wraps it in an adapter Container
func (r *LocalRuntime) LookupContainer(idOrName string) (*Container, error) {
ctr, err := r.Runtime.LookupContainer(idOrName)
if err != nil {
return nil, err
}
return &Container{ctr}, nil
}
// StopContainers stops container(s) based on CLI inputs.
// Returns list of successful id(s), map of failed id(s) + error, or error not from container
func (r *LocalRuntime) StopContainers(ctx context.Context, cli *cliconfig.StopValues) ([]string, map[string]error, error) {
var timeout *uint
if cli.Flags().Changed("timeout") || cli.Flags().Changed("time") {
t := uint(cli.Timeout)
timeout = &t
}
maxWorkers := shared.DefaultPoolSize("stop")
if cli.GlobalIsSet("max-workers") {
maxWorkers = cli.GlobalFlags.MaxWorks
}
logrus.Debugf("Setting maximum stop workers to %d", maxWorkers)
ctrs, err := shortcuts.GetContainersByContext(cli.All, cli.Latest, cli.InputArgs, r.Runtime)
if err != nil {
return nil, nil, err
}
pool := shared.NewPool("stop", maxWorkers, len(ctrs))
for _, c := range ctrs {
c := c
if timeout == nil {
t := c.StopTimeout()
timeout = &t
logrus.Debugf("Set timeout to container %s default (%d)", c.ID(), *timeout)
}
pool.Add(shared.Job{
c.ID(),
func() error {
err := c.StopWithTimeout(*timeout)
if err != nil {
if errors.Cause(err) == libpod.ErrCtrStopped {
logrus.Debugf("Container %s is already stopped", c.ID())
return nil
}
logrus.Debugf("Failed to stop container %s: %s", c.ID(), err.Error())
}
return err
},
})
}
return pool.Run()
}
// KillContainers sends signal to container(s) based on CLI inputs.
// Returns list of successful id(s), map of failed id(s) + error, or error not from container
func (r *LocalRuntime) KillContainers(ctx context.Context, cli *cliconfig.KillValues, signal syscall.Signal) ([]string, map[string]error, error) {
maxWorkers := shared.DefaultPoolSize("kill")
if cli.GlobalIsSet("max-workers") {
maxWorkers = cli.GlobalFlags.MaxWorks
}
logrus.Debugf("Setting maximum kill workers to %d", maxWorkers)
ctrs, err := shortcuts.GetContainersByContext(cli.All, cli.Latest, cli.InputArgs, r.Runtime)
if err != nil {
return nil, nil, err
}
pool := shared.NewPool("kill", maxWorkers, len(ctrs))
for _, c := range ctrs {
c := c
pool.Add(shared.Job{
c.ID(),
func() error {
return c.Kill(uint(signal))
},
})
}
return pool.Run()
}
// RemoveContainers removes container(s) based on CLI inputs.
func (r *LocalRuntime) RemoveContainers(ctx context.Context, cli *cliconfig.RmValues) ([]string, map[string]error, error) {
var (
ok = []string{}
failures = map[string]error{}
)
maxWorkers := shared.DefaultPoolSize("rm")
if cli.GlobalIsSet("max-workers") {
maxWorkers = cli.GlobalFlags.MaxWorks
}
logrus.Debugf("Setting maximum rm workers to %d", maxWorkers)
ctrs, err := shortcuts.GetContainersByContext(cli.All, cli.Latest, cli.InputArgs, r.Runtime)
if err != nil {
// Force may be used to remove containers no longer found in the database
if cli.Force && len(cli.InputArgs) > 0 && errors.Cause(err) == libpod.ErrNoSuchCtr {
r.RemoveContainersFromStorage(cli.InputArgs)
}
return ok, failures, err
}
pool := shared.NewPool("rm", maxWorkers, len(ctrs))
for _, c := range ctrs {
c := c
pool.Add(shared.Job{
c.ID(),
func() error {
err := r.RemoveContainer(ctx, c, cli.Force, cli.Volumes)
if err != nil {
logrus.Debugf("Failed to remove container %s: %s", c.ID(), err.Error())
}
return err
},
})
}
return pool.Run()
}
// UmountRootFilesystems removes container(s) based on CLI inputs.
func (r *LocalRuntime) UmountRootFilesystems(ctx context.Context, cli *cliconfig.UmountValues) ([]string, map[string]error, error) {
var (
ok = []string{}
failures = map[string]error{}
)
ctrs, err := shortcuts.GetContainersByContext(cli.All, cli.Latest, cli.InputArgs, r.Runtime)
if err != nil {
return ok, failures, err
}
for _, ctr := range ctrs {
state, err := ctr.State()
if err != nil {
logrus.Debugf("Error umounting container %s state: %s", ctr.ID(), err.Error())
continue
}
if state == libpod.ContainerStateRunning {
logrus.Debugf("Error umounting container %s, is running", ctr.ID())
continue
}
if err := ctr.Unmount(cli.Force); err != nil {
if cli.All && errors.Cause(err) == storage.ErrLayerNotMounted {
logrus.Debugf("Error umounting container %s, storage.ErrLayerNotMounted", ctr.ID())
continue
}
failures[ctr.ID()] = errors.Wrapf(err, "error unmounting continaner %s", ctr.ID())
} else {
ok = append(ok, ctr.ID())
}
}
return ok, failures, nil
}
// WaitOnContainers waits for all given container(s) to stop
func (r *LocalRuntime) WaitOnContainers(ctx context.Context, cli *cliconfig.WaitValues, interval time.Duration) ([]string, map[string]error, error) {
var (
ok = []string{}
failures = map[string]error{}
)
ctrs, err := shortcuts.GetContainersByContext(false, cli.Latest, cli.InputArgs, r.Runtime)
if err != nil {
return ok, failures, err
}
for _, c := range ctrs {
if returnCode, err := c.WaitWithInterval(interval); err == nil {
ok = append(ok, strconv.Itoa(int(returnCode)))
} else {
failures[c.ID()] = err
}
}
return ok, failures, err
}
// Log logs one or more containers
func (r *LocalRuntime) Log(c *cliconfig.LogsValues, options *libpod.LogOptions) error {
var wg sync.WaitGroup
options.WaitGroup = &wg
if len(c.InputArgs) > 1 {
options.Multi = true
}
logChannel := make(chan *libpod.LogLine, int(c.Tail)*len(c.InputArgs)+1)
containers, err := shortcuts.GetContainersByContext(false, c.Latest, c.InputArgs, r.Runtime)
if err != nil {
return err
}
if err := r.Runtime.Log(containers, options, logChannel); err != nil {
return err
}
go func() {
wg.Wait()
close(logChannel)
}()
for line := range logChannel {
fmt.Println(line.String(options))
}
return nil
}
// CreateContainer creates a libpod container
func (r *LocalRuntime) CreateContainer(ctx context.Context, c *cliconfig.CreateValues) (string, error) {
results := shared.NewIntermediateLayer(&c.PodmanCommand, false)
ctr, _, err := shared.CreateContainer(ctx, &results, r.Runtime)
if err != nil {
return "", err
}
return ctr.ID(), nil
}
// Run a libpod container
func (r *LocalRuntime) Run(ctx context.Context, c *cliconfig.RunValues, exitCode int) (int, error) {
results := shared.NewIntermediateLayer(&c.PodmanCommand, false)
ctr, createConfig, err := shared.CreateContainer(ctx, &results, r.Runtime)
if err != nil {
return exitCode, err
}
if logrus.GetLevel() == logrus.DebugLevel {
cgroupPath, err := ctr.CGroupPath()
if err == nil {
logrus.Debugf("container %q has CgroupParent %q", ctr.ID(), cgroupPath)
}
}
// Handle detached start
if createConfig.Detach {
// if the container was created as part of a pod, also start its dependencies, if any.
if err := ctr.Start(ctx, c.IsSet("pod")); err != nil {
// This means the command did not exist
exitCode = 127
if strings.Index(err.Error(), "permission denied") > -1 {
exitCode = 126
}
return exitCode, err
}
fmt.Printf("%s\n", ctr.ID())
exitCode = 0
return exitCode, nil
}
outputStream := os.Stdout
errorStream := os.Stderr
inputStream := os.Stdin
// If -i is not set, clear stdin
if !c.Bool("interactive") {
inputStream = nil
}
// If attach is set, clear stdin/stdout/stderr and only attach requested
if c.IsSet("attach") || c.IsSet("a") {
outputStream = nil
errorStream = nil
if !c.Bool("interactive") {
inputStream = nil
}
attachTo := c.StringSlice("attach")
for _, stream := range attachTo {
switch strings.ToLower(stream) {
case "stdout":
outputStream = os.Stdout
case "stderr":
errorStream = os.Stderr
case "stdin":
inputStream = os.Stdin
default:
return exitCode, errors.Wrapf(libpod.ErrInvalidArg, "invalid stream %q for --attach - must be one of stdin, stdout, or stderr", stream)
}
}
}
// if the container was created as part of a pod, also start its dependencies, if any.
if err := StartAttachCtr(ctx, ctr, outputStream, errorStream, inputStream, c.String("detach-keys"), c.Bool("sig-proxy"), true, c.IsSet("pod")); err != nil {
// We've manually detached from the container
// Do not perform cleanup, or wait for container exit code
// Just exit immediately
if errors.Cause(err) == libpod.ErrDetach {
exitCode = 0
return exitCode, nil
}
// This means the command did not exist
exitCode = 127
if strings.Index(err.Error(), "permission denied") > -1 {
exitCode = 126
}
if c.IsSet("rm") {
if deleteError := r.Runtime.RemoveContainer(ctx, ctr, true, false); deleteError != nil {
logrus.Errorf("unable to remove container %s after failing to start and attach to it", ctr.ID())
}
}
return exitCode, err
}
if ecode, err := ctr.Wait(); err != nil {
if errors.Cause(err) == libpod.ErrNoSuchCtr {
// The container may have been removed
// Go looking for an exit file
config, err := r.Runtime.GetConfig()
if err != nil {
return exitCode, err
}
ctrExitCode, err := ReadExitFile(config.TmpDir, ctr.ID())
if err != nil {
logrus.Errorf("Cannot get exit code: %v", err)
exitCode = 127
} else {
exitCode = ctrExitCode
}
}
} else {
exitCode = int(ecode)
}
if c.IsSet("rm") {
r.Runtime.RemoveContainer(ctx, ctr, false, true)
}
return exitCode, nil
}
// ReadExitFile reads a container's exit file
func ReadExitFile(runtimeTmp, ctrID string) (int, error) {
exitFile := filepath.Join(runtimeTmp, "exits", fmt.Sprintf("%s-old", ctrID))
logrus.Debugf("Attempting to read container %s exit code from file %s", ctrID, exitFile)
// Check if it exists
if _, err := os.Stat(exitFile); err != nil {
return 0, errors.Wrapf(err, "error getting exit file for container %s", ctrID)
}
// File exists, read it in and convert to int
statusStr, err := ioutil.ReadFile(exitFile)
if err != nil {
return 0, errors.Wrapf(err, "error reading exit file for container %s", ctrID)
}
exitCode, err := strconv.Atoi(string(statusStr))
if err != nil {
return 0, errors.Wrapf(err, "error parsing exit code for container %s", ctrID)
}
return exitCode, nil
}
// Ps ...
func (r *LocalRuntime) Ps(c *cliconfig.PsValues, opts shared.PsOptions) ([]shared.PsContainerOutput, error) {
maxWorkers := shared.Parallelize("ps")
if c.GlobalIsSet("max-workers") {
maxWorkers = c.GlobalFlags.MaxWorks
}
logrus.Debugf("Setting maximum workers to %d", maxWorkers)
return shared.GetPsContainerOutput(r.Runtime, opts, c.Filter, maxWorkers)
}
// Attach ...
func (r *LocalRuntime) Attach(ctx context.Context, c *cliconfig.AttachValues) error {
var (
ctr *libpod.Container
err error
)
if c.Latest {
ctr, err = r.Runtime.GetLatestContainer()
} else {
ctr, err = r.Runtime.LookupContainer(c.InputArgs[0])
}
if err != nil {
return errors.Wrapf(err, "unable to exec into %s", c.InputArgs[0])
}
conState, err := ctr.State()
if err != nil {
return errors.Wrapf(err, "unable to determine state of %s", ctr.ID())
}
if conState != libpod.ContainerStateRunning {
return errors.Errorf("you can only attach to running containers")
}
inputStream := os.Stdin
if c.NoStdin {
inputStream = nil
}
// If the container is in a pod, also set to recursively start dependencies
if err := StartAttachCtr(ctx, ctr, os.Stdout, os.Stderr, inputStream, c.DetachKeys, c.SigProxy, false, ctr.PodID() != ""); err != nil && errors.Cause(err) != libpod.ErrDetach {
return errors.Wrapf(err, "error attaching to container %s", ctr.ID())
}
return nil
}
// Checkpoint one or more containers
func (r *LocalRuntime) Checkpoint(c *cliconfig.CheckpointValues, options libpod.ContainerCheckpointOptions) error {
var (
containers []*libpod.Container
err, lastError error
)
if c.All {
containers, err = r.Runtime.GetRunningContainers()
} else {
containers, err = shortcuts.GetContainersByContext(false, c.Latest, c.InputArgs, r.Runtime)
}
if err != nil {
return err
}
for _, ctr := range containers {
if err = ctr.Checkpoint(context.TODO(), options); err != nil {
if lastError != nil {
fmt.Fprintln(os.Stderr, lastError)
}
lastError = errors.Wrapf(err, "failed to checkpoint container %v", ctr.ID())
} else {
fmt.Println(ctr.ID())
}
}
return lastError
}
// Restore one or more containers
func (r *LocalRuntime) Restore(c *cliconfig.RestoreValues, options libpod.ContainerCheckpointOptions) error {
var (
containers []*libpod.Container
err, lastError error
filterFuncs []libpod.ContainerFilter
)
filterFuncs = append(filterFuncs, func(c *libpod.Container) bool {
state, _ := c.State()
return state == libpod.ContainerStateExited
})
if c.All {
containers, err = r.GetContainers(filterFuncs...)
} else {
containers, err = shortcuts.GetContainersByContext(false, c.Latest, c.InputArgs, r.Runtime)
}
if err != nil {
return err
}
for _, ctr := range containers {
if err = ctr.Restore(context.TODO(), options); err != nil {
if lastError != nil {
fmt.Fprintln(os.Stderr, lastError)
}
lastError = errors.Wrapf(err, "failed to restore container %v", ctr.ID())
} else {
fmt.Println(ctr.ID())
}
}
return lastError
}
// Start will start a container
func (r *LocalRuntime) Start(ctx context.Context, c *cliconfig.StartValues, sigProxy bool) (int, error) {
var (
exitCode = 125
lastError error
)
args := c.InputArgs
if c.Latest {
lastCtr, err := r.GetLatestContainer()
if err != nil {
return 0, errors.Wrapf(err, "unable to get latest container")
}
args = append(args, lastCtr.ID())
}
for _, container := range args {
ctr, err := r.LookupContainer(container)
if err != nil {
if lastError != nil {
fmt.Fprintln(os.Stderr, lastError)
}
lastError = errors.Wrapf(err, "unable to find container %s", container)
continue
}
ctrState, err := ctr.State()
if err != nil {
return exitCode, errors.Wrapf(err, "unable to get container state")
}
ctrRunning := ctrState == libpod.ContainerStateRunning
if c.Attach {
inputStream := os.Stdin
if !c.Interactive {
inputStream = nil
}
// attach to the container and also start it not already running
// If the container is in a pod, also set to recursively start dependencies
err = StartAttachCtr(ctx, ctr.Container, os.Stdout, os.Stderr, inputStream, c.DetachKeys, sigProxy, !ctrRunning, ctr.PodID() != "")
if errors.Cause(err) == libpod.ErrDetach {
// User manually detached
// Exit cleanly immediately
exitCode = 0
return exitCode, nil
}
if ctrRunning {
return 0, err
}
if err != nil {
return exitCode, errors.Wrapf(err, "unable to start container %s", ctr.ID())
}
if ecode, err := ctr.Wait(); err != nil {
if errors.Cause(err) == libpod.ErrNoSuchCtr {
// The container may have been removed
// Go looking for an exit file
rtc, err := r.GetConfig()
if err != nil {
return 0, err
}
ctrExitCode, err := ReadExitFile(rtc.TmpDir, ctr.ID())
if err != nil {
logrus.Errorf("Cannot get exit code: %v", err)
exitCode = 127
} else {
exitCode = ctrExitCode
}
}
} else {
exitCode = int(ecode)
}
return exitCode, nil
}
if ctrRunning {
fmt.Println(ctr.ID())
continue
}
// Handle non-attach start
// If the container is in a pod, also set to recursively start dependencies
if err := ctr.Start(ctx, ctr.PodID() != ""); err != nil {
if lastError != nil {
fmt.Fprintln(os.Stderr, lastError)
}
lastError = errors.Wrapf(err, "unable to start container %q", container)
continue
}
fmt.Println(container)
}
return exitCode, lastError
}
// PauseContainers removes container(s) based on CLI inputs.
func (r *LocalRuntime) PauseContainers(ctx context.Context, cli *cliconfig.PauseValues) ([]string, map[string]error, error) {
var (
ok = []string{}
failures = map[string]error{}
ctrs []*libpod.Container
err error
)
maxWorkers := shared.DefaultPoolSize("pause")
if cli.GlobalIsSet("max-workers") {
maxWorkers = cli.GlobalFlags.MaxWorks
}
logrus.Debugf("Setting maximum rm workers to %d", maxWorkers)
if cli.All {
ctrs, err = r.GetRunningContainers()
} else {
ctrs, err = shortcuts.GetContainersByContext(false, false, cli.InputArgs, r.Runtime)
}
if err != nil {
return ok, failures, err
}
pool := shared.NewPool("pause", maxWorkers, len(ctrs))
for _, c := range ctrs {
ctr := c
pool.Add(shared.Job{
ID: ctr.ID(),
Fn: func() error {
err := ctr.Pause()
if err != nil {
logrus.Debugf("Failed to pause container %s: %s", ctr.ID(), err.Error())
}
return err
},
})
}
return pool.Run()
}
// UnpauseContainers removes container(s) based on CLI inputs.
func (r *LocalRuntime) UnpauseContainers(ctx context.Context, cli *cliconfig.UnpauseValues) ([]string, map[string]error, error) {
var (
ok = []string{}
failures = map[string]error{}
ctrs []*libpod.Container
err error
)
maxWorkers := shared.DefaultPoolSize("pause")
if cli.GlobalIsSet("max-workers") {
maxWorkers = cli.GlobalFlags.MaxWorks
}
logrus.Debugf("Setting maximum rm workers to %d", maxWorkers)
if cli.All {
var filterFuncs []libpod.ContainerFilter
filterFuncs = append(filterFuncs, func(c *libpod.Container) bool {
state, _ := c.State()
return state == libpod.ContainerStatePaused
})
ctrs, err = r.GetContainers(filterFuncs...)
} else {
ctrs, err = shortcuts.GetContainersByContext(false, false, cli.InputArgs, r.Runtime)
}
if err != nil {
return ok, failures, err
}
pool := shared.NewPool("pause", maxWorkers, len(ctrs))
for _, c := range ctrs {
ctr := c
pool.Add(shared.Job{
ID: ctr.ID(),
Fn: func() error {
err := ctr.Unpause()
if err != nil {
logrus.Debugf("Failed to unpause container %s: %s", ctr.ID(), err.Error())
}
return err
},
})
}
return pool.Run()
}
|