forked from kubernetes/kubernetes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rkt.go
2327 lines (2031 loc) · 74.7 KB
/
rkt.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
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright 2015 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package rkt
import (
"bufio"
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"os"
"os/exec"
"path"
"path/filepath"
"sort"
"strconv"
"strings"
"sync"
"syscall"
"time"
appcschema "github.com/appc/spec/schema"
appctypes "github.com/appc/spec/schema/types"
"github.com/coreos/go-systemd/unit"
rktapi "github.com/coreos/rkt/api/v1alpha"
"github.com/golang/glog"
"golang.org/x/net/context"
"google.golang.org/grpc"
"k8s.io/kubernetes/pkg/api"
"k8s.io/kubernetes/pkg/client/record"
"k8s.io/kubernetes/pkg/credentialprovider"
kubecontainer "k8s.io/kubernetes/pkg/kubelet/container"
"k8s.io/kubernetes/pkg/kubelet/leaky"
"k8s.io/kubernetes/pkg/kubelet/lifecycle"
"k8s.io/kubernetes/pkg/kubelet/network"
"k8s.io/kubernetes/pkg/kubelet/network/hairpin"
proberesults "k8s.io/kubernetes/pkg/kubelet/prober/results"
"k8s.io/kubernetes/pkg/kubelet/types"
"k8s.io/kubernetes/pkg/kubelet/util/format"
"k8s.io/kubernetes/pkg/securitycontext"
kubetypes "k8s.io/kubernetes/pkg/types"
"k8s.io/kubernetes/pkg/util"
"k8s.io/kubernetes/pkg/util/errors"
utilexec "k8s.io/kubernetes/pkg/util/exec"
"k8s.io/kubernetes/pkg/util/flowcontrol"
"k8s.io/kubernetes/pkg/util/selinux"
utilstrings "k8s.io/kubernetes/pkg/util/strings"
utilwait "k8s.io/kubernetes/pkg/util/wait"
)
const (
RktType = "rkt"
DefaultRktAPIServiceEndpoint = "localhost:15441"
minimumRktBinVersion = "1.9.1"
recommendedRktBinVersion = "1.9.1"
minimumRktApiVersion = "1.0.0-alpha"
minimumSystemdVersion = "219"
systemdServiceDir = "/run/systemd/system"
rktDataDir = "/var/lib/rkt"
rktLocalConfigDir = "/etc/rkt"
kubernetesUnitPrefix = "k8s_"
unitKubernetesSection = "X-Kubernetes"
unitPodUID = "PodUID"
unitPodName = "PodName"
unitPodNamespace = "PodNamespace"
unitPodHostNetwork = "PodHostNetwork"
k8sRktKubeletAnno = "rkt.kubernetes.io/managed-by-kubelet"
k8sRktKubeletAnnoValue = "true"
k8sRktContainerHashAnno = "rkt.kubernetes.io/container-hash"
k8sRktRestartCountAnno = "rkt.kubernetes.io/restart-count"
k8sRktTerminationMessagePathAnno = "rkt.kubernetes.io/termination-message-path"
// TODO(euank): This has significant security concerns as a stage1 image is
// effectively root.
// Furthermore, this (using an annotation) is a hack to pass an extra
// non-portable argument in. It should not be relied on to be stable.
// In the future, this might be subsumed by a first-class api object, or by a
// kitchen-sink params object (#17064).
// See discussion in #23944
// Also, do we want more granularity than path-at-the-kubelet-level and
// image/name-at-the-pod-level?
k8sRktStage1NameAnno = "rkt.alpha.kubernetes.io/stage1-name-override"
dockerPrefix = "docker://"
authDir = "auth.d"
dockerAuthTemplate = `{"rktKind":"dockerAuth","rktVersion":"v1","registries":[%q],"credentials":{"user":%q,"password":%q}}`
defaultRktAPIServiceAddr = "localhost:15441"
// ndots specifies the minimum number of dots that a domain name must contain for the resolver to consider it as FQDN (fully-qualified)
// we want to able to consider SRV lookup names like _dns._udp.kube-dns.default.svc to be considered relative.
// hence, setting ndots to be 5.
// TODO(yifan): Move this and dockertools.ndotsDNSOption to a common package.
defaultDNSOption = "ndots:5"
// Annotations for the ENTRYPOINT and CMD for an ACI that's converted from Docker image.
// TODO(yifan): Import them from docker2aci. See https://github.com/appc/docker2aci/issues/133.
appcDockerEntrypoint = "appc.io/docker/entrypoint"
appcDockerCmd = "appc.io/docker/cmd"
// TODO(yifan): Reuse this const with Docker runtime.
minimumGracePeriodInSeconds = 2
// The network name of the network when no-op plugin is being used.
// TODO(yifan): This is not ideal since today we cannot make the rkt's 'net.d' dir point to the
// CNI directory specified by kubelet. Once that is fixed, we can just use the network config
// under the CNI directory directly.
// See https://github.com/coreos/rkt/pull/2312#issuecomment-200068370.
defaultNetworkName = "rkt.kubernetes.io"
// defaultRequestTimeout is the default timeout of rkt requests.
defaultRequestTimeout = 2 * time.Minute
)
// Runtime implements the Containerruntime for rkt. The implementation
// uses systemd, so in order to run this runtime, systemd must be installed
// on the machine.
type Runtime struct {
cli cliInterface
systemd systemdInterface
// The grpc client for rkt api-service.
apisvcConn *grpc.ClientConn
apisvc rktapi.PublicAPIClient
config *Config
// TODO(yifan): Refactor this to be generic keyring.
dockerKeyring credentialprovider.DockerKeyring
containerRefManager *kubecontainer.RefManager
podGetter podGetter
runtimeHelper kubecontainer.RuntimeHelper
recorder record.EventRecorder
livenessManager proberesults.Manager
imagePuller kubecontainer.ImagePuller
runner kubecontainer.HandlerRunner
execer utilexec.Interface
os kubecontainer.OSInterface
// Network plugin.
networkPlugin network.NetworkPlugin
// If true, the "hairpin mode" flag is set on container interfaces.
// A false value means the kubelet just backs off from setting it,
// it might already be true.
configureHairpinMode bool
// used for a systemd Exec, which requires the full path.
touchPath string
nsenterPath string
versions versions
// requestTimeout is the timeout of rkt requests.
requestTimeout time.Duration
}
var _ kubecontainer.Runtime = &Runtime{}
// TODO(yifan): This duplicates the podGetter in dockertools.
type podGetter interface {
GetPodByUID(kubetypes.UID) (*api.Pod, bool)
}
// cliInterface wrapps the command line calls for testing purpose.
type cliInterface interface {
// RunCommand creates rkt commands and runs it with the given config.
// If the config is nil, it will use the one inferred from rkt API service.
RunCommand(config *Config, args ...string) (result []string, err error)
}
// New creates the rkt container runtime which implements the container runtime interface.
// It will test if the rkt binary is in the $PATH, and whether we can get the
// version of it. If so, creates the rkt container runtime, otherwise returns an error.
func New(
apiEndpoint string,
config *Config,
runtimeHelper kubecontainer.RuntimeHelper,
recorder record.EventRecorder,
containerRefManager *kubecontainer.RefManager,
podGetter podGetter,
livenessManager proberesults.Manager,
httpClient types.HttpGetter,
networkPlugin network.NetworkPlugin,
hairpinMode bool,
execer utilexec.Interface,
os kubecontainer.OSInterface,
imageBackOff *flowcontrol.Backoff,
serializeImagePulls bool,
requestTimeout time.Duration,
) (*Runtime, error) {
// Create dbus connection.
systemd, err := newSystemd()
if err != nil {
return nil, fmt.Errorf("rkt: cannot create systemd interface: %v", err)
}
// TODO(yifan): Use secure connection.
apisvcConn, err := grpc.Dial(apiEndpoint, grpc.WithInsecure())
if err != nil {
return nil, fmt.Errorf("rkt: cannot connect to rkt api service: %v", err)
}
// TODO(yifan): Get the rkt path from API service.
if config.Path == "" {
// No default rkt path was set, so try to find one in $PATH.
var err error
config.Path, err = execer.LookPath("rkt")
if err != nil {
return nil, fmt.Errorf("cannot find rkt binary: %v", err)
}
}
touchPath, err := execer.LookPath("touch")
if err != nil {
return nil, fmt.Errorf("cannot find touch binary: %v", err)
}
nsenterPath, err := execer.LookPath("nsenter")
if err != nil {
return nil, fmt.Errorf("cannot find nsenter binary: %v", err)
}
if requestTimeout == 0 {
requestTimeout = defaultRequestTimeout
}
rkt := &Runtime{
os: kubecontainer.RealOS{},
systemd: systemd,
apisvcConn: apisvcConn,
apisvc: rktapi.NewPublicAPIClient(apisvcConn),
config: config,
dockerKeyring: credentialprovider.NewDockerKeyring(),
containerRefManager: containerRefManager,
podGetter: podGetter,
runtimeHelper: runtimeHelper,
recorder: recorder,
livenessManager: livenessManager,
networkPlugin: networkPlugin,
execer: execer,
touchPath: touchPath,
nsenterPath: nsenterPath,
requestTimeout: requestTimeout,
}
rkt.config, err = rkt.getConfig(rkt.config)
if err != nil {
return nil, fmt.Errorf("rkt: cannot get config from rkt api service: %v", err)
}
rkt.runner = lifecycle.NewHandlerRunner(httpClient, rkt, rkt)
if serializeImagePulls {
rkt.imagePuller = kubecontainer.NewSerializedImagePuller(recorder, rkt, imageBackOff)
} else {
rkt.imagePuller = kubecontainer.NewImagePuller(recorder, rkt, imageBackOff)
}
if err := rkt.getVersions(); err != nil {
return nil, fmt.Errorf("rkt: error getting version info: %v", err)
}
rkt.cli = rkt
return rkt, nil
}
func buildCommand(config *Config, args ...string) *exec.Cmd {
cmd := exec.Command(config.Path)
cmd.Args = append(cmd.Args, config.buildGlobalOptions()...)
cmd.Args = append(cmd.Args, args...)
return cmd
}
// convertToACName converts a string into ACName.
func convertToACName(name string) appctypes.ACName {
// Note that as the 'name' already matches 'DNS_LABEL'
// defined in pkg/api/types.go, there shouldn't be error or panic.
acname, _ := appctypes.SanitizeACName(name)
return *appctypes.MustACName(acname)
}
// RunCommand invokes rkt binary with arguments and returns the result
// from stdout in a list of strings. Each string in the list is a line.
// If config is non-nil, it will use the given config instead of the config
// inferred from rkt API service.
func (r *Runtime) RunCommand(config *Config, args ...string) ([]string, error) {
if config == nil {
config = r.config
}
glog.V(4).Infof("rkt: Run command: %q with config: %+v", args, config)
var stdout, stderr bytes.Buffer
cmd := buildCommand(config, args...)
cmd.Stdout, cmd.Stderr = &stdout, &stderr
if err := cmd.Run(); err != nil {
return nil, fmt.Errorf("failed to run %v: %v\nstdout: %v\nstderr: %v", args, err, stdout.String(), stderr.String())
}
return strings.Split(strings.TrimSpace(stdout.String()), "\n"), nil
}
// makePodServiceFileName constructs the unit file name for a pod using its rkt pod uuid.
func makePodServiceFileName(uuid string) string {
// TODO(yifan): Add name for readability? We need to consider the
// limit of the length.
return fmt.Sprintf("%s%s.service", kubernetesUnitPrefix, uuid)
}
func getRktUUIDFromServiceFileName(filename string) string {
return strings.TrimPrefix(strings.TrimSuffix(filename, path.Ext(filename)), kubernetesUnitPrefix)
}
// setIsolators sets the apps' isolators according to the security context and resource spec.
func setIsolators(app *appctypes.App, c *api.Container, ctx *api.SecurityContext) error {
var isolators []appctypes.Isolator
// Capabilities isolators.
if ctx != nil {
var addCaps, dropCaps []string
if ctx.Capabilities != nil {
addCaps, dropCaps = securitycontext.MakeCapabilities(ctx.Capabilities.Add, ctx.Capabilities.Drop)
}
if ctx.Privileged != nil && *ctx.Privileged {
addCaps, dropCaps = allCapabilities(), []string{}
}
if len(addCaps) > 0 {
set, err := appctypes.NewLinuxCapabilitiesRetainSet(addCaps...)
if err != nil {
return err
}
isolators = append(isolators, set.AsIsolator())
}
if len(dropCaps) > 0 {
set, err := appctypes.NewLinuxCapabilitiesRevokeSet(dropCaps...)
if err != nil {
return err
}
isolators = append(isolators, set.AsIsolator())
}
}
// Resources isolators.
type resource struct {
limit string
request string
}
// If limit is empty, populate it with request and vice versa.
resources := make(map[api.ResourceName]*resource)
for name, quantity := range c.Resources.Limits {
resources[name] = &resource{limit: quantity.String(), request: quantity.String()}
}
for name, quantity := range c.Resources.Requests {
r, ok := resources[name]
if ok {
r.request = quantity.String()
continue
}
resources[name] = &resource{limit: quantity.String(), request: quantity.String()}
}
for name, res := range resources {
switch name {
case api.ResourceCPU:
cpu, err := appctypes.NewResourceCPUIsolator(res.request, res.limit)
if err != nil {
return err
}
isolators = append(isolators, cpu.AsIsolator())
case api.ResourceMemory:
memory, err := appctypes.NewResourceMemoryIsolator(res.request, res.limit)
if err != nil {
return err
}
isolators = append(isolators, memory.AsIsolator())
default:
return fmt.Errorf("resource type not supported: %v", name)
}
}
mergeIsolators(app, isolators)
return nil
}
// mergeIsolators replaces the app.Isolators with isolators.
func mergeIsolators(app *appctypes.App, isolators []appctypes.Isolator) {
for _, is := range isolators {
found := false
for j, js := range app.Isolators {
if is.Name.Equals(js.Name) {
switch is.Name {
case appctypes.LinuxCapabilitiesRetainSetName:
// TODO(yifan): More fine grain merge for capability set instead of override.
fallthrough
case appctypes.LinuxCapabilitiesRevokeSetName:
fallthrough
case appctypes.ResourceCPUName:
fallthrough
case appctypes.ResourceMemoryName:
app.Isolators[j] = is
default:
panic(fmt.Sprintf("unexpected isolator name: %v", is.Name))
}
found = true
break
}
}
if !found {
app.Isolators = append(app.Isolators, is)
}
}
}
// mergeEnv merges the optEnv with the image's environments.
// The environments defined in the image will be overridden by
// the ones with the same name in optEnv.
func mergeEnv(app *appctypes.App, optEnv []kubecontainer.EnvVar) {
envMap := make(map[string]string)
for _, e := range app.Environment {
envMap[e.Name] = e.Value
}
for _, e := range optEnv {
envMap[e.Name] = e.Value
}
app.Environment = nil
for name, value := range envMap {
app.Environment = append(app.Environment, appctypes.EnvironmentVariable{
Name: name,
Value: value,
})
}
}
// mergeMounts merges the optMounts with the image's mount points.
// The mount points defined in the image will be overridden by the ones
// with the same name in optMounts.
func mergeMounts(app *appctypes.App, optMounts []kubecontainer.Mount) {
mountMap := make(map[appctypes.ACName]appctypes.MountPoint)
for _, m := range app.MountPoints {
mountMap[m.Name] = m
}
for _, m := range optMounts {
mpName := convertToACName(m.Name)
mountMap[mpName] = appctypes.MountPoint{
Name: mpName,
Path: m.ContainerPath,
ReadOnly: m.ReadOnly,
}
}
app.MountPoints = nil
for _, mount := range mountMap {
app.MountPoints = append(app.MountPoints, mount)
}
}
// mergePortMappings merges the optPortMappings with the image's port mappings.
// The port mappings defined in the image will be overridden by the ones
// with the same name in optPortMappings.
func mergePortMappings(app *appctypes.App, optPortMappings []kubecontainer.PortMapping) {
portMap := make(map[appctypes.ACName]appctypes.Port)
for _, p := range app.Ports {
portMap[p.Name] = p
}
for _, p := range optPortMappings {
pName := convertToACName(p.Name)
portMap[pName] = appctypes.Port{
Name: pName,
Protocol: string(p.Protocol),
Port: uint(p.ContainerPort),
}
}
app.Ports = nil
for _, port := range portMap {
app.Ports = append(app.Ports, port)
}
}
func verifyNonRoot(app *appctypes.App, ctx *api.SecurityContext) error {
if ctx != nil && ctx.RunAsNonRoot != nil && *ctx.RunAsNonRoot {
if ctx.RunAsUser != nil && *ctx.RunAsUser == 0 {
return fmt.Errorf("container's runAsUser breaks non-root policy")
}
if ctx.RunAsUser == nil && app.User == "0" {
return fmt.Errorf("container has no runAsUser and image will run as root")
}
}
return nil
}
func setSupplementaryGIDs(app *appctypes.App, podCtx *api.PodSecurityContext) {
if podCtx != nil {
app.SupplementaryGIDs = app.SupplementaryGIDs[:0]
for _, v := range podCtx.SupplementalGroups {
app.SupplementaryGIDs = append(app.SupplementaryGIDs, int(v))
}
if podCtx.FSGroup != nil {
app.SupplementaryGIDs = append(app.SupplementaryGIDs, int(*podCtx.FSGroup))
}
}
}
// setApp merges the container spec with the image's manifest.
func setApp(imgManifest *appcschema.ImageManifest, c *api.Container, opts *kubecontainer.RunContainerOptions, ctx *api.SecurityContext, podCtx *api.PodSecurityContext) error {
app := imgManifest.App
// Set up Exec.
var command, args []string
cmd, ok := imgManifest.Annotations.Get(appcDockerEntrypoint)
if ok {
err := json.Unmarshal([]byte(cmd), &command)
if err != nil {
return fmt.Errorf("cannot unmarshal ENTRYPOINT %q: %v", cmd, err)
}
}
ag, ok := imgManifest.Annotations.Get(appcDockerCmd)
if ok {
err := json.Unmarshal([]byte(ag), &args)
if err != nil {
return fmt.Errorf("cannot unmarshal CMD %q: %v", ag, err)
}
}
userCommand, userArgs := kubecontainer.ExpandContainerCommandAndArgs(c, opts.Envs)
if len(userCommand) > 0 {
command = userCommand
args = nil // If 'command' is specified, then drop the default args.
}
if len(userArgs) > 0 {
args = userArgs
}
exec := append(command, args...)
if len(exec) > 0 {
app.Exec = exec
}
// Set UID and GIDs.
if err := verifyNonRoot(app, ctx); err != nil {
return err
}
if ctx != nil && ctx.RunAsUser != nil {
app.User = strconv.Itoa(int(*ctx.RunAsUser))
}
setSupplementaryGIDs(app, podCtx)
// If 'User' or 'Group' are still empty at this point,
// then apply the root UID and GID.
// TODO(yifan): If only the GID is empty, rkt should be able to determine the GID
// using the /etc/passwd file in the image.
// See https://github.com/appc/docker2aci/issues/175.
// Maybe we can remove this check in the future.
if app.User == "" {
app.User = "0"
app.Group = "0"
}
if app.Group == "" {
return fmt.Errorf("cannot determine the GID of the app %q", imgManifest.Name)
}
// Set working directory.
if len(c.WorkingDir) > 0 {
app.WorkingDirectory = c.WorkingDir
}
// Notes that we don't create Mounts section in the pod manifest here,
// as Mounts will be automatically generated by rkt.
mergeMounts(app, opts.Mounts)
mergeEnv(app, opts.Envs)
mergePortMappings(app, opts.PortMappings)
return setIsolators(app, c, ctx)
}
// makePodManifest transforms a kubelet pod spec to the rkt pod manifest.
func (r *Runtime) makePodManifest(pod *api.Pod, podIP string, pullSecrets []api.Secret) (*appcschema.PodManifest, error) {
manifest := appcschema.BlankPodManifest()
ctx, cancel := context.WithTimeout(context.Background(), r.requestTimeout)
defer cancel()
listResp, err := r.apisvc.ListPods(ctx, &rktapi.ListPodsRequest{
Detail: true,
Filters: kubernetesPodFilters(pod.UID),
})
if err != nil {
return nil, fmt.Errorf("couldn't list pods: %v", err)
}
restartCount := 0
for _, pod := range listResp.Pods {
manifest := &appcschema.PodManifest{}
err = json.Unmarshal(pod.Manifest, manifest)
if err != nil {
glog.Warningf("rkt: error unmatshaling pod manifest: %v", err)
continue
}
if countString, ok := manifest.Annotations.Get(k8sRktRestartCountAnno); ok {
num, err := strconv.Atoi(countString)
if err != nil {
glog.Warningf("rkt: error reading restart count on pod: %v", err)
continue
}
if num+1 > restartCount {
restartCount = num + 1
}
}
}
requiresPrivileged := false
manifest.Annotations.Set(*appctypes.MustACIdentifier(k8sRktKubeletAnno), k8sRktKubeletAnnoValue)
manifest.Annotations.Set(*appctypes.MustACIdentifier(types.KubernetesPodUIDLabel), string(pod.UID))
manifest.Annotations.Set(*appctypes.MustACIdentifier(types.KubernetesPodNameLabel), pod.Name)
manifest.Annotations.Set(*appctypes.MustACIdentifier(types.KubernetesPodNamespaceLabel), pod.Namespace)
manifest.Annotations.Set(*appctypes.MustACIdentifier(types.KubernetesContainerNameLabel), leaky.PodInfraContainerName)
manifest.Annotations.Set(*appctypes.MustACIdentifier(k8sRktRestartCountAnno), strconv.Itoa(restartCount))
if stage1Name, ok := pod.Annotations[k8sRktStage1NameAnno]; ok {
requiresPrivileged = true
manifest.Annotations.Set(*appctypes.MustACIdentifier(k8sRktStage1NameAnno), stage1Name)
}
for _, c := range pod.Spec.Containers {
err := r.newAppcRuntimeApp(pod, podIP, c, requiresPrivileged, pullSecrets, manifest)
if err != nil {
return nil, err
}
}
// TODO(yifan): Set pod-level isolators once it's supported in kubernetes.
return manifest, nil
}
// TODO(yifan): Can make rkt handle this when '--net=host'. See https://github.com/coreos/rkt/issues/2430.
func makeHostNetworkMount(opts *kubecontainer.RunContainerOptions) (*kubecontainer.Mount, *kubecontainer.Mount) {
hostsMount := kubecontainer.Mount{
Name: "kubernetes-hostnetwork-hosts-conf",
ContainerPath: "/etc/hosts",
HostPath: "/etc/hosts",
ReadOnly: true,
}
resolvMount := kubecontainer.Mount{
Name: "kubernetes-hostnetwork-resolv-conf",
ContainerPath: "/etc/resolv.conf",
HostPath: "/etc/resolv.conf",
ReadOnly: true,
}
opts.Mounts = append(opts.Mounts, hostsMount, resolvMount)
return &hostsMount, &resolvMount
}
// podFinishedMarkerPath returns the path to a file which should be used to
// indicate the pod exiting, and the time thereof.
// If the file at the path does not exist, the pod should not be exited. If it
// does exist, then the ctime of the file should indicate the time the pod
// exited.
func podFinishedMarkerPath(podDir string, rktUID string) string {
return filepath.Join(podDir, "finished-"+rktUID)
}
func podFinishedMarkCommand(touchPath, podDir, rktUID string) string {
// TODO, if the path has a `'` character in it, this breaks.
return touchPath + " " + podFinishedMarkerPath(podDir, rktUID)
}
// podFinishedAt returns the time that a pod exited, or a zero time if it has
// not.
func (r *Runtime) podFinishedAt(podUID kubetypes.UID, rktUID string) time.Time {
markerFile := podFinishedMarkerPath(r.runtimeHelper.GetPodDir(podUID), rktUID)
stat, err := r.os.Stat(markerFile)
if err != nil {
if !os.IsNotExist(err) {
glog.Warningf("rkt: unexpected fs error checking pod finished marker: %v", err)
}
return time.Time{}
}
return stat.ModTime()
}
func (r *Runtime) makeContainerLogMount(opts *kubecontainer.RunContainerOptions, container *api.Container) (*kubecontainer.Mount, error) {
if opts.PodContainerDir == "" || container.TerminationMessagePath == "" {
return nil, nil
}
// In docker runtime, the container log path contains the container ID.
// However, for rkt runtime, we cannot get the container ID before the
// the container is launched, so here we generate a random uuid to enable
// us to map a container's termination message path to an unique log file
// on the disk.
randomUID := util.NewUUID()
containerLogPath := path.Join(opts.PodContainerDir, string(randomUID))
fs, err := r.os.Create(containerLogPath)
if err != nil {
return nil, err
}
if err := fs.Close(); err != nil {
return nil, err
}
mnt := kubecontainer.Mount{
// Use a random name for the termination message mount, so that
// when a container restarts, it will not overwrite the old termination
// message.
Name: fmt.Sprintf("termination-message-%s", randomUID),
ContainerPath: container.TerminationMessagePath,
HostPath: containerLogPath,
ReadOnly: false,
}
opts.Mounts = append(opts.Mounts, mnt)
return &mnt, nil
}
func (r *Runtime) newAppcRuntimeApp(pod *api.Pod, podIP string, c api.Container, requiresPrivileged bool, pullSecrets []api.Secret, manifest *appcschema.PodManifest) error {
if requiresPrivileged && !securitycontext.HasPrivilegedRequest(&c) {
return fmt.Errorf("cannot make %q: running a custom stage1 requires a privileged security context", format.Pod(pod))
}
if err, _ := r.imagePuller.PullImage(pod, &c, pullSecrets); err != nil {
return nil
}
imgManifest, err := r.getImageManifest(c.Image)
if err != nil {
return err
}
if imgManifest.App == nil {
imgManifest.App = new(appctypes.App)
}
imageID, err := r.getImageID(c.Image)
if err != nil {
return err
}
hash, err := appctypes.NewHash(imageID)
if err != nil {
return err
}
// TODO: determine how this should be handled for rkt
opts, err := r.runtimeHelper.GenerateRunContainerOptions(pod, &c, podIP)
if err != nil {
return err
}
// create the container log file and make a mount pair.
mnt, err := r.makeContainerLogMount(opts, &c)
if err != nil {
return err
}
// If run in 'hostnetwork' mode, then mount the host's /etc/resolv.conf and /etc/hosts,
// and add volumes.
var hostsMnt, resolvMnt *kubecontainer.Mount
if kubecontainer.IsHostNetworkPod(pod) {
hostsMnt, resolvMnt = makeHostNetworkMount(opts)
manifest.Volumes = append(manifest.Volumes, appctypes.Volume{
Name: convertToACName(hostsMnt.Name),
Kind: "host",
Source: hostsMnt.HostPath,
})
manifest.Volumes = append(manifest.Volumes, appctypes.Volume{
Name: convertToACName(resolvMnt.Name),
Kind: "host",
Source: resolvMnt.HostPath,
})
}
ctx := securitycontext.DetermineEffectiveSecurityContext(pod, &c)
if err := setApp(imgManifest, &c, opts, ctx, pod.Spec.SecurityContext); err != nil {
return err
}
for _, mnt := range opts.Mounts {
readOnly := mnt.ReadOnly
manifest.Volumes = append(manifest.Volumes, appctypes.Volume{
Name: convertToACName(mnt.Name),
Source: mnt.HostPath,
Kind: "host",
ReadOnly: &readOnly,
})
}
ra := appcschema.RuntimeApp{
Name: convertToACName(c.Name),
Image: appcschema.RuntimeImage{ID: *hash},
App: imgManifest.App,
Annotations: []appctypes.Annotation{
{
Name: *appctypes.MustACIdentifier(k8sRktContainerHashAnno),
Value: strconv.FormatUint(kubecontainer.HashContainer(&c), 10),
},
{
Name: *appctypes.MustACIdentifier(types.KubernetesContainerNameLabel),
Value: c.Name,
},
},
}
if c.SecurityContext != nil && c.SecurityContext.ReadOnlyRootFilesystem != nil {
ra.ReadOnlyRootFS = *c.SecurityContext.ReadOnlyRootFilesystem
}
if mnt != nil {
ra.Annotations = append(ra.Annotations, appctypes.Annotation{
Name: *appctypes.MustACIdentifier(k8sRktTerminationMessagePathAnno),
Value: mnt.HostPath,
})
manifest.Volumes = append(manifest.Volumes, appctypes.Volume{
Name: convertToACName(mnt.Name),
Kind: "host",
Source: mnt.HostPath,
})
}
manifest.Apps = append(manifest.Apps, ra)
// Set global ports.
for _, port := range opts.PortMappings {
if port.HostPort == 0 {
continue
}
manifest.Ports = append(manifest.Ports, appctypes.ExposedPort{
Name: convertToACName(port.Name),
HostPort: uint(port.HostPort),
})
}
return nil
}
func runningKubernetesPodFilters(uid kubetypes.UID) []*rktapi.PodFilter {
return []*rktapi.PodFilter{
{
States: []rktapi.PodState{
rktapi.PodState_POD_STATE_RUNNING,
},
Annotations: []*rktapi.KeyValue{
{
Key: k8sRktKubeletAnno,
Value: k8sRktKubeletAnnoValue,
},
{
Key: types.KubernetesPodUIDLabel,
Value: string(uid),
},
},
},
}
}
func kubernetesPodFilters(uid kubetypes.UID) []*rktapi.PodFilter {
return []*rktapi.PodFilter{
{
Annotations: []*rktapi.KeyValue{
{
Key: k8sRktKubeletAnno,
Value: k8sRktKubeletAnnoValue,
},
{
Key: types.KubernetesPodUIDLabel,
Value: string(uid),
},
},
},
}
}
func kubernetesPodsFilters() []*rktapi.PodFilter {
return []*rktapi.PodFilter{
{
Annotations: []*rktapi.KeyValue{
{
Key: k8sRktKubeletAnno,
Value: k8sRktKubeletAnnoValue,
},
},
},
}
}
func newUnitOption(section, name, value string) *unit.UnitOption {
return &unit.UnitOption{Section: section, Name: name, Value: value}
}
// apiPodToruntimePod converts an api.Pod to kubelet/container.Pod.
func apiPodToruntimePod(uuid string, pod *api.Pod) *kubecontainer.Pod {
p := &kubecontainer.Pod{
ID: pod.UID,
Name: pod.Name,
Namespace: pod.Namespace,
}
for i := range pod.Spec.Containers {
c := &pod.Spec.Containers[i]
p.Containers = append(p.Containers, &kubecontainer.Container{
ID: buildContainerID(&containerID{uuid, c.Name}),
Name: c.Name,
Image: c.Image,
Hash: kubecontainer.HashContainer(c),
})
}
return p
}
// serviceFilePath returns the absolute path of the service file.
func serviceFilePath(serviceName string) string {
return path.Join(systemdServiceDir, serviceName)
}
// shouldCreateNetns returns true if:
// The pod does not run in host network. And
// The pod runs inside a netns created outside of rkt.
func (r *Runtime) shouldCreateNetns(pod *api.Pod) bool {
return !kubecontainer.IsHostNetworkPod(pod) && r.networkPlugin.Name() != network.DefaultPluginName
}
// usesRktHostNetwork returns true if:
// The pod runs in the host network. Or
// The pod runs inside a netns created outside of rkt.
func (r *Runtime) usesRktHostNetwork(pod *api.Pod) bool {
return kubecontainer.IsHostNetworkPod(pod) || r.shouldCreateNetns(pod)
}
// generateRunCommand crafts a 'rkt run-prepared' command with necessary parameters.
func (r *Runtime) generateRunCommand(pod *api.Pod, uuid, netnsName string) (string, error) {
runPrepared := buildCommand(r.config, "run-prepared").Args
var hostname string
var err error
osInfos, err := getOSReleaseInfo()
if err != nil {
glog.Errorf("rkt: Failed to read the os release info: %v", err)
}
// Overlay fs is not supported for SELinux yet on many distros.
// See https://github.com/coreos/rkt/issues/1727#issuecomment-173203129.
// For now, coreos carries a patch to support it: https://github.com/coreos/coreos-overlay/pull/1703
if osInfos["ID"] != "coreos" && pod.Spec.SecurityContext != nil && pod.Spec.SecurityContext.SELinuxOptions != nil {
runPrepared = append(runPrepared, "--no-overlay=true")
}
// Apply '--net=host' to pod that is running on host network or inside a network namespace.
if r.usesRktHostNetwork(pod) {
runPrepared = append(runPrepared, "--net=host")
} else {
runPrepared = append(runPrepared, fmt.Sprintf("--net=%s", defaultNetworkName))
}
if kubecontainer.IsHostNetworkPod(pod) {
// TODO(yifan): Let runtimeHelper.GeneratePodHostNameAndDomain() to handle this.
hostname, err = r.os.Hostname()
if err != nil {
return "", err
}
} else {
// Setup DNS.
dnsServers, dnsSearches, err := r.runtimeHelper.GetClusterDNS(pod)
if err != nil {
return "", err
}
for _, server := range dnsServers {
runPrepared = append(runPrepared, fmt.Sprintf("--dns=%s", server))
}
for _, search := range dnsSearches {
runPrepared = append(runPrepared, fmt.Sprintf("--dns-search=%s", search))
}
if len(dnsServers) > 0 || len(dnsSearches) > 0 {
runPrepared = append(runPrepared, fmt.Sprintf("--dns-opt=%s", defaultDNSOption))
}
// TODO(yifan): host domain is not being used.
hostname, _, err = r.runtimeHelper.GeneratePodHostNameAndDomain(pod)
if err != nil {
return "", err
}
}
runPrepared = append(runPrepared, fmt.Sprintf("--hostname=%s", hostname))
runPrepared = append(runPrepared, uuid)