-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
containers.go
796 lines (723 loc) · 21.8 KB
/
containers.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
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
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
//go:build !remote
package compat
import (
"encoding/json"
"errors"
"fmt"
"net/http"
"sort"
"strconv"
"strings"
"syscall"
"time"
"github.com/containers/podman/v5/libpod"
"github.com/containers/podman/v5/libpod/define"
"github.com/containers/podman/v5/pkg/api/handlers"
"github.com/containers/podman/v5/pkg/api/handlers/utils"
api "github.com/containers/podman/v5/pkg/api/types"
"github.com/containers/podman/v5/pkg/domain/entities"
"github.com/containers/podman/v5/pkg/domain/filters"
"github.com/containers/podman/v5/pkg/domain/infra/abi"
"github.com/containers/podman/v5/pkg/ps"
"github.com/containers/podman/v5/pkg/signal"
"github.com/containers/podman/v5/pkg/util"
"github.com/docker/docker/api/types"
dockerBackend "github.com/docker/docker/api/types/backend"
"github.com/docker/docker/api/types/container"
"github.com/docker/docker/api/types/network"
"github.com/docker/go-connections/nat"
"github.com/docker/go-units"
spec "github.com/opencontainers/runtime-spec/specs-go"
"github.com/sirupsen/logrus"
)
func RemoveContainer(w http.ResponseWriter, r *http.Request) {
decoder := utils.GetDecoder(r)
query := struct {
Force bool `schema:"force"`
Ignore bool `schema:"ignore"`
Depend bool `schema:"depend"`
Link bool `schema:"link"`
Timeout *uint `schema:"timeout"`
DockerVolumes bool `schema:"v"`
LibpodVolumes bool `schema:"volumes"`
}{
// override any golang type defaults
}
if err := decoder.Decode(&query, r.URL.Query()); err != nil {
utils.Error(w, http.StatusBadRequest, fmt.Errorf("failed to parse parameters for %s: %w", r.URL.String(), err))
return
}
options := entities.RmOptions{
Force: query.Force,
Ignore: query.Ignore,
}
if utils.IsLibpodRequest(r) {
options.Volumes = query.LibpodVolumes
options.Timeout = query.Timeout
options.Depend = query.Depend
} else {
if query.Link {
utils.Error(w, http.StatusBadRequest, utils.ErrLinkNotSupport)
return
}
options.Volumes = query.DockerVolumes
}
runtime := r.Context().Value(api.RuntimeKey).(*libpod.Runtime)
// Now use the ABI implementation to prevent us from having duplicate
// code.
containerEngine := abi.ContainerEngine{Libpod: runtime}
name := utils.GetName(r)
reports, err := containerEngine.ContainerRm(r.Context(), []string{name}, options)
if err != nil {
if errors.Is(err, define.ErrNoSuchCtr) {
utils.ContainerNotFound(w, name, err)
return
}
utils.InternalServerError(w, err)
return
}
if len(reports) > 0 && reports[0].Err != nil {
err = reports[0].Err
if errors.Is(err, define.ErrNoSuchCtr) {
utils.ContainerNotFound(w, name, err)
return
}
utils.InternalServerError(w, err)
return
}
if utils.IsLibpodRequest(r) {
utils.WriteResponse(w, http.StatusOK, reports)
return
}
utils.WriteResponse(w, http.StatusNoContent, nil)
}
func ListContainers(w http.ResponseWriter, r *http.Request) {
runtime := r.Context().Value(api.RuntimeKey).(*libpod.Runtime)
decoder := utils.GetDecoder(r)
query := struct {
All bool `schema:"all"`
Limit int `schema:"limit"`
Size bool `schema:"size"`
}{
// override any golang type defaults
}
filterMap, err := util.PrepareFilters(r)
if err != nil {
utils.Error(w, http.StatusInternalServerError, fmt.Errorf("failed to decode filter parameters for %s: %w", r.URL.String(), err))
return
}
if err := decoder.Decode(&query, r.URL.Query()); err != nil {
utils.Error(w, http.StatusInternalServerError, fmt.Errorf("failed to parse parameters for %s: %w", r.URL.String(), err))
return
}
filterFuncs := make([]libpod.ContainerFilter, 0, len(*filterMap))
all := query.All || query.Limit > 0
if len(*filterMap) > 0 {
for k, v := range *filterMap {
generatedFunc, err := filters.GenerateContainerFilterFuncs(k, v, runtime)
if err != nil {
utils.InternalServerError(w, err)
return
}
filterFuncs = append(filterFuncs, generatedFunc)
}
}
// Docker thinks that if status is given as an input, then we should override
// the all setting and always deal with all containers.
if len((*filterMap)["status"]) > 0 {
all = true
}
if !all {
runningOnly, err := filters.GenerateContainerFilterFuncs("status", []string{define.ContainerStateRunning.String()}, runtime)
if err != nil {
utils.InternalServerError(w, err)
return
}
filterFuncs = append(filterFuncs, runningOnly)
}
containers, err := runtime.GetContainers(false, filterFuncs...)
if err != nil {
utils.InternalServerError(w, err)
return
}
if _, found := r.URL.Query()["limit"]; found && query.Limit > 0 {
// Sort the libpod containers
sort.Sort(ps.SortCreateTime{SortContainers: containers})
// we should perform the lopping before we start getting
// the expensive information on containers
if len(containers) > query.Limit {
containers = containers[:query.Limit]
}
}
list := make([]*handlers.Container, 0, len(containers))
for _, ctnr := range containers {
api, err := LibpodToContainer(ctnr, query.Size)
if err != nil {
if errors.Is(err, define.ErrNoSuchCtr) {
// container was removed between the initial fetch of the list and conversion
logrus.Debugf("Container %s removed between initial fetch and conversion, ignoring in output", ctnr.ID())
continue
}
utils.InternalServerError(w, err)
return
}
list = append(list, api)
}
utils.WriteResponse(w, http.StatusOK, list)
}
func GetContainer(w http.ResponseWriter, r *http.Request) {
runtime := r.Context().Value(api.RuntimeKey).(*libpod.Runtime)
decoder := utils.GetDecoder(r)
query := struct {
Size bool `schema:"size"`
}{
// override any golang type defaults
}
if err := decoder.Decode(&query, r.URL.Query()); err != nil {
utils.Error(w, http.StatusBadRequest, fmt.Errorf("failed to parse parameters for %s: %w", r.URL.String(), err))
return
}
name := utils.GetName(r)
ctnr, err := runtime.LookupContainer(name)
if err != nil {
utils.ContainerNotFound(w, name, err)
return
}
api, err := LibpodToContainerJSON(ctnr, query.Size)
if err != nil {
utils.InternalServerError(w, err)
return
}
utils.WriteResponse(w, http.StatusOK, api)
}
func KillContainer(w http.ResponseWriter, r *http.Request) {
// /{version}/containers/(name)/kill
runtime := r.Context().Value(api.RuntimeKey).(*libpod.Runtime)
decoder := utils.GetDecoder(r)
query := struct {
Signal string `schema:"signal"`
}{
Signal: "KILL",
}
if err := decoder.Decode(&query, r.URL.Query()); err != nil {
utils.Error(w, http.StatusBadRequest, fmt.Errorf("failed to parse parameters for %s: %w", r.URL.String(), err))
return
}
// Now use the ABI implementation to prevent us from having duplicate
// code.
containerEngine := abi.ContainerEngine{Libpod: runtime}
name := utils.GetName(r)
options := entities.KillOptions{
Signal: query.Signal,
}
report, err := containerEngine.ContainerKill(r.Context(), []string{name}, options)
if err != nil {
if errors.Is(err, define.ErrCtrStateInvalid) ||
errors.Is(err, define.ErrCtrStopped) {
utils.Error(w, http.StatusConflict, err)
return
}
if errors.Is(err, define.ErrNoSuchCtr) {
utils.ContainerNotFound(w, name, err)
return
}
utils.InternalServerError(w, err)
return
}
if len(report) > 0 && report[0].Err != nil {
if errors.Is(report[0].Err, define.ErrCtrStateInvalid) ||
errors.Is(report[0].Err, define.ErrCtrStopped) {
utils.Error(w, http.StatusConflict, report[0].Err)
return
}
utils.InternalServerError(w, report[0].Err)
return
}
// Docker waits for the container to stop if the signal is 0 or
// SIGKILL.
if !utils.IsLibpodRequest(r) {
sig, err := signal.ParseSignalNameOrNumber(query.Signal)
if err != nil {
utils.InternalServerError(w, err)
return
}
if sig == 0 || sig == syscall.SIGKILL {
opts := entities.WaitOptions{
Conditions: []string{define.ContainerStateExited.String(), define.ContainerStateStopped.String()},
Interval: time.Millisecond * 250,
}
if _, err := containerEngine.ContainerWait(r.Context(), []string{name}, opts); err != nil {
utils.Error(w, http.StatusInternalServerError, err)
return
}
}
}
// Success
utils.WriteResponse(w, http.StatusNoContent, nil)
}
func WaitContainer(w http.ResponseWriter, r *http.Request) {
// /{version}/containers/(name)/wait
utils.WaitContainerDocker(w, r)
}
func LibpodToContainer(l *libpod.Container, sz bool) (*handlers.Container, error) {
imageID, imageName := l.Image()
var (
err error
sizeRootFs int64
sizeRW int64
state define.ContainerStatus
status string
)
if state, err = l.State(); err != nil {
return nil, err
}
stateStr := state.String()
// Some docker states are not the same as ours. This makes sure the state string stays true to the Docker API
if state == define.ContainerStateCreated {
stateStr = define.ContainerStateConfigured.String()
}
switch state {
case define.ContainerStateConfigured, define.ContainerStateCreated:
status = "Created"
case define.ContainerStateStopped, define.ContainerStateExited:
exitCode, _, err := l.ExitCode()
if err != nil {
return nil, err
}
finishedTime, err := l.FinishedTime()
if err != nil {
return nil, err
}
status = fmt.Sprintf("Exited (%d) %s ago", exitCode, units.HumanDuration(time.Since(finishedTime)))
case define.ContainerStateRunning, define.ContainerStatePaused:
startedTime, err := l.StartedTime()
if err != nil {
return nil, err
}
status = fmt.Sprintf("Up %s", units.HumanDuration(time.Since(startedTime)))
if state == define.ContainerStatePaused {
status += " (Paused)"
}
case define.ContainerStateRemoving:
status = "Removal In Progress"
case define.ContainerStateStopping:
status = "Stopping"
default:
status = "Unknown"
}
if sz {
if sizeRW, err = l.RWSize(); err != nil {
return nil, err
}
if sizeRootFs, err = l.RootFsSize(); err != nil {
return nil, err
}
}
portMappings, err := l.PortMappings()
if err != nil {
return nil, err
}
ports := make([]types.Port, len(portMappings))
for idx, portMapping := range portMappings {
ports[idx] = types.Port{
IP: portMapping.HostIP,
PrivatePort: portMapping.ContainerPort,
PublicPort: portMapping.HostPort,
Type: portMapping.Protocol,
}
}
inspect, err := l.Inspect(false)
if err != nil {
return nil, err
}
n, err := json.Marshal(inspect.NetworkSettings)
if err != nil {
return nil, err
}
networkSettings := types.SummaryNetworkSettings{}
if err := json.Unmarshal(n, &networkSettings); err != nil {
return nil, err
}
m, err := json.Marshal(inspect.Mounts)
if err != nil {
return nil, err
}
mounts := []types.MountPoint{}
if err := json.Unmarshal(m, &mounts); err != nil {
return nil, err
}
return &handlers.Container{
Container: types.Container{
ID: l.ID(),
Names: []string{fmt.Sprintf("/%s", l.Name())},
Image: imageName,
ImageID: "sha256:" + imageID,
Command: strings.Join(l.Command(), " "),
Created: l.CreatedTime().Unix(),
Ports: ports,
SizeRw: sizeRW,
SizeRootFs: sizeRootFs,
Labels: l.Labels(),
State: stateStr,
Status: status,
// FIXME: this seems broken, the field is never shown in the API output.
HostConfig: struct {
NetworkMode string `json:",omitempty"`
Annotations map[string]string `json:",omitempty"`
}{
NetworkMode: "host",
// TODO: add annotations here for >= v1.46
},
NetworkSettings: &networkSettings,
Mounts: mounts,
},
ContainerCreateConfig: dockerBackend.ContainerCreateConfig{},
}, nil
}
func convertSecondaryIPPrefixLen(input *define.InspectNetworkSettings, output *types.NetworkSettings) {
for index, ip := range input.SecondaryIPAddresses {
output.SecondaryIPAddresses[index].PrefixLen = ip.PrefixLength
}
for index, ip := range input.SecondaryIPv6Addresses {
output.SecondaryIPv6Addresses[index].PrefixLen = ip.PrefixLength
}
}
func LibpodToContainerJSON(l *libpod.Container, sz bool) (*types.ContainerJSON, error) {
imageID, imageName := l.Image()
inspect, err := l.Inspect(sz)
if err != nil {
return nil, err
}
// Docker uses UTC
if inspect != nil && inspect.State != nil {
inspect.State.StartedAt = inspect.State.StartedAt.UTC()
inspect.State.FinishedAt = inspect.State.FinishedAt.UTC()
}
i, err := json.Marshal(inspect.State)
if err != nil {
return nil, err
}
state := types.ContainerState{}
if err := json.Unmarshal(i, &state); err != nil {
return nil, err
}
// docker considers paused to be running
if state.Paused {
state.Running = true
}
// Dockers created state is our configured state
if state.Status == define.ContainerStateCreated.String() {
state.Status = define.ContainerStateConfigured.String()
}
if l.HasHealthCheck() && state.Status != "created" {
state.Health = &types.Health{}
if inspect.State.Health != nil {
state.Health.Status = inspect.State.Health.Status
state.Health.FailingStreak = inspect.State.Health.FailingStreak
log := inspect.State.Health.Log
for _, item := range log {
res := &types.HealthcheckResult{}
s, err := time.Parse(time.RFC3339Nano, item.Start)
if err != nil {
return nil, err
}
e, err := time.Parse(time.RFC3339Nano, item.End)
if err != nil {
return nil, err
}
res.Start = s
res.End = e
res.ExitCode = item.ExitCode
res.Output = item.Output
state.Health.Log = append(state.Health.Log, res)
}
}
}
formatCapabilities(inspect.HostConfig.CapDrop)
formatCapabilities(inspect.HostConfig.CapAdd)
h, err := json.Marshal(inspect.HostConfig)
if err != nil {
return nil, err
}
hc := container.HostConfig{}
if err := json.Unmarshal(h, &hc); err != nil {
return nil, err
}
sort.Strings(hc.Binds)
// k8s-file == json-file
if hc.LogConfig.Type == define.KubernetesLogging {
hc.LogConfig.Type = define.JSONLogging
}
g, err := json.Marshal(inspect.GraphDriver)
if err != nil {
return nil, err
}
graphDriver := types.GraphDriverData{}
if err := json.Unmarshal(g, &graphDriver); err != nil {
return nil, err
}
cb := types.ContainerJSONBase{
ID: l.ID(),
Created: l.CreatedTime().UTC().Format(time.RFC3339Nano), // Docker uses UTC
Path: inspect.Path,
Args: inspect.Args,
State: &state,
Image: "sha256:" + imageID,
ResolvConfPath: inspect.ResolvConfPath,
HostnamePath: inspect.HostnamePath,
HostsPath: inspect.HostsPath,
LogPath: l.LogPath(),
Node: nil,
Name: fmt.Sprintf("/%s", l.Name()),
RestartCount: int(inspect.RestartCount),
Driver: inspect.Driver,
Platform: "linux",
MountLabel: inspect.MountLabel,
ProcessLabel: inspect.ProcessLabel,
AppArmorProfile: inspect.AppArmorProfile,
ExecIDs: inspect.ExecIDs,
HostConfig: &hc,
GraphDriver: graphDriver,
SizeRw: inspect.SizeRw,
SizeRootFs: &inspect.SizeRootFs,
}
// set Path and Args
processArgs := l.Config().Spec.Process.Args
if len(processArgs) > 0 {
cb.Path = processArgs[0]
}
if len(processArgs) > 1 {
cb.Args = processArgs[1:]
}
stopTimeout := int(l.StopTimeout())
var healthcheck *container.HealthConfig
if inspect.Config.Healthcheck != nil {
healthcheck = &container.HealthConfig{
Test: inspect.Config.Healthcheck.Test,
Interval: inspect.Config.Healthcheck.Interval,
Timeout: inspect.Config.Healthcheck.Timeout,
StartPeriod: inspect.Config.Healthcheck.StartPeriod,
Retries: inspect.Config.Healthcheck.Retries,
}
}
// Apparently the compiler can't convert a map[string]struct{} into a nat.PortSet
// (Despite a nat.PortSet being that exact struct with some types added)
var exposedPorts nat.PortSet
if len(inspect.Config.ExposedPorts) > 0 {
exposedPorts = make(nat.PortSet)
for p := range inspect.Config.ExposedPorts {
exposedPorts[nat.Port(p)] = struct{}{}
}
}
config := container.Config{
Hostname: l.Hostname(),
Domainname: inspect.Config.DomainName,
User: l.User(),
AttachStdin: inspect.Config.AttachStdin,
AttachStdout: inspect.Config.AttachStdout,
AttachStderr: inspect.Config.AttachStderr,
ExposedPorts: exposedPorts,
Tty: inspect.Config.Tty,
OpenStdin: inspect.Config.OpenStdin,
StdinOnce: inspect.Config.StdinOnce,
Env: inspect.Config.Env,
Cmd: l.Command(),
Healthcheck: healthcheck,
ArgsEscaped: false,
Image: imageName,
Volumes: nil,
WorkingDir: l.WorkingDir(),
Entrypoint: l.Entrypoint(),
NetworkDisabled: false,
MacAddress: "",
OnBuild: nil,
Labels: l.Labels(),
StopSignal: strconv.Itoa(int(l.StopSignal())),
StopTimeout: &stopTimeout,
Shell: nil,
}
m, err := json.Marshal(inspect.Mounts)
if err != nil {
return nil, err
}
mounts := []types.MountPoint{}
if err := json.Unmarshal(m, &mounts); err != nil {
return nil, err
}
p, err := json.Marshal(inspect.NetworkSettings.Ports)
if err != nil {
return nil, err
}
ports := nat.PortMap{}
if err := json.Unmarshal(p, &ports); err != nil {
return nil, err
}
n, err := json.Marshal(inspect.NetworkSettings)
if err != nil {
return nil, err
}
networkSettings := types.NetworkSettings{}
if err := json.Unmarshal(n, &networkSettings); err != nil {
return nil, err
}
convertSecondaryIPPrefixLen(inspect.NetworkSettings, &networkSettings)
// do not report null instead use an empty map
if networkSettings.Networks == nil {
networkSettings.Networks = map[string]*network.EndpointSettings{}
}
c := types.ContainerJSON{
ContainerJSONBase: &cb,
Mounts: mounts,
Config: &config,
NetworkSettings: &networkSettings,
}
return &c, nil
}
func formatCapabilities(slice []string) {
for i := range slice {
slice[i] = strings.TrimPrefix(slice[i], "CAP_")
}
}
func RenameContainer(w http.ResponseWriter, r *http.Request) {
runtime := r.Context().Value(api.RuntimeKey).(*libpod.Runtime)
decoder := utils.GetDecoder(r)
name := utils.GetName(r)
query := struct {
Name string `schema:"name"`
}{}
if err := decoder.Decode(&query, r.URL.Query()); err != nil {
utils.Error(w, http.StatusBadRequest, fmt.Errorf("failed to parse parameters for %s: %w", r.URL.String(), err))
return
}
ctr, err := runtime.LookupContainer(name)
if err != nil {
utils.ContainerNotFound(w, name, err)
return
}
if _, err := runtime.RenameContainer(r.Context(), ctr, query.Name); err != nil {
if errors.Is(err, define.ErrPodExists) || errors.Is(err, define.ErrCtrExists) {
utils.Error(w, http.StatusConflict, err)
return
}
utils.InternalServerError(w, err)
return
}
utils.WriteResponse(w, http.StatusNoContent, nil)
}
func UpdateContainer(w http.ResponseWriter, r *http.Request) {
runtime := r.Context().Value(api.RuntimeKey).(*libpod.Runtime)
name := utils.GetName(r)
ctr, err := runtime.LookupContainer(name)
if err != nil {
utils.ContainerNotFound(w, name, err)
return
}
options := new(container.UpdateConfig)
if err := json.NewDecoder(r.Body).Decode(options); err != nil {
utils.Error(w, http.StatusInternalServerError, fmt.Errorf("decoding request body: %w", err))
return
}
// Only handle the bits of update that Docker uses as examples.
// For example, the update API claims to be able to update devices for
// existing containers... Which I am very dubious about.
// Ignore bits like that unless someone asks us for them.
// We're going to be editing this, so we have to deep-copy to not affect
// the container's own resources
resources := new(spec.LinuxResources)
oldResources := ctr.LinuxResources()
if oldResources != nil {
if err := libpod.JSONDeepCopy(oldResources, resources); err != nil {
utils.Error(w, http.StatusInternalServerError, fmt.Errorf("copying old resource limits: %w", err))
return
}
}
// CPU limits
cpu := resources.CPU
if cpu == nil {
cpu = new(spec.LinuxCPU)
}
useCPU := false
if options.CPUShares != 0 {
shares := uint64(options.CPUShares)
cpu.Shares = &shares
useCPU = true
}
if options.CPUPeriod != 0 {
period := uint64(options.CPUPeriod)
cpu.Period = &period
useCPU = true
}
if options.CPUQuota != 0 {
cpu.Quota = &options.CPUQuota
useCPU = true
}
if options.CPURealtimeRuntime != 0 {
cpu.RealtimeRuntime = &options.CPURealtimeRuntime
useCPU = true
}
if options.CPURealtimePeriod != 0 {
period := uint64(options.CPURealtimePeriod)
cpu.RealtimePeriod = &period
useCPU = true
}
if options.CpusetCpus != "" {
cpu.Cpus = options.CpusetCpus
useCPU = true
}
if options.CpusetMems != "" {
cpu.Mems = options.CpusetMems
useCPU = true
}
if useCPU {
resources.CPU = cpu
}
// Memory limits
mem := resources.Memory
if mem == nil {
mem = new(spec.LinuxMemory)
}
useMem := false
if options.Memory != 0 {
mem.Limit = &options.Memory
useMem = true
}
if options.MemorySwap != 0 {
mem.Swap = &options.MemorySwap
useMem = true
}
if options.MemoryReservation != 0 {
mem.Reservation = &options.MemoryReservation
useMem = true
}
if useMem {
resources.Memory = mem
}
// PIDs limit
if options.PidsLimit != nil {
if resources.Pids == nil {
resources.Pids = new(spec.LinuxPids)
}
resources.Pids.Limit = *options.PidsLimit
}
// Blkio Weight
if options.BlkioWeight != 0 {
if resources.BlockIO == nil {
resources.BlockIO = new(spec.LinuxBlockIO)
}
resources.BlockIO.Weight = &options.BlkioWeight
}
// Restart policy
localPolicy := string(options.RestartPolicy.Name)
restartPolicy := &localPolicy
var restartRetries *uint
if options.RestartPolicy.MaximumRetryCount != 0 {
localRetries := uint(options.RestartPolicy.MaximumRetryCount)
restartRetries = &localRetries
}
if err := ctr.Update(resources, restartPolicy, restartRetries, &define.UpdateHealthCheckConfig{}); err != nil {
utils.Error(w, http.StatusInternalServerError, fmt.Errorf("updating container: %w", err))
return
}
responseStruct := container.ContainerUpdateOKBody{}
utils.WriteResponse(w, http.StatusOK, responseStruct)
}