This repository has been archived by the owner on Feb 24, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 886
/
pod.go
1199 lines (1014 loc) · 38.4 KB
/
pod.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 2014 The rkt 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.
//+build linux
package common
import (
"bytes"
"errors"
"fmt"
"io"
"io/ioutil"
"os"
"path"
"path/filepath"
"regexp"
"strconv"
"strings"
"github.com/coreos/rkt/pkg/acl"
stage1commontypes "github.com/coreos/rkt/stage1/common/types"
"github.com/appc/spec/schema"
"github.com/appc/spec/schema/types"
"github.com/coreos/go-systemd/unit"
"github.com/hashicorp/errwrap"
"github.com/coreos/rkt/common"
"github.com/coreos/rkt/common/cgroup"
"github.com/coreos/rkt/pkg/fileutil"
"github.com/coreos/rkt/pkg/user"
)
const (
// FlavorFile names the file storing the pod's flavor
FlavorFile = "flavor"
SharedVolPerm = os.FileMode(0755)
)
var (
defaultEnv = map[string]string{
"PATH": "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
"SHELL": "/bin/sh",
"USER": "root",
"LOGNAME": "root",
"HOME": "/root",
}
)
type Stage1InsecureOptions struct {
DisablePaths bool
DisableCapabilities bool
DisableSeccomp bool
}
// execEscape uses Golang's string quoting for ", \, \n, and regex for special cases
func execEscape(i int, str string) string {
escapeMap := map[string]string{
`'`: `\`,
}
if i > 0 { // These are escaped only after the first argument
escapeMap[`$`] = `$`
}
escArg := fmt.Sprintf("%q", str)
for k := range escapeMap {
reStr := `([` + regexp.QuoteMeta(k) + `])`
re := regexp.MustCompile(reStr)
escArg = re.ReplaceAllStringFunc(escArg, func(s string) string {
escaped := escapeMap[s] + s
return escaped
})
}
return escArg
}
// quoteExec returns an array of quoted strings appropriate for systemd execStart usage
func quoteExec(exec []string) string {
if len(exec) == 0 {
// existing callers always include at least the binary so this shouldn't occur.
panic("empty exec")
}
var qexec []string
for i, arg := range exec {
escArg := execEscape(i, arg)
qexec = append(qexec, escArg)
}
return strings.Join(qexec, " ")
}
// WriteDefaultTarget writes the default.target unit file
// which is responsible for bringing up the applications
func WriteDefaultTarget(p *stage1commontypes.Pod) error {
opts := []*unit.UnitOption{
unit.NewUnitOption("Unit", "Description", "rkt apps target"),
unit.NewUnitOption("Unit", "DefaultDependencies", "false"),
}
for i := range p.Manifest.Apps {
ra := &p.Manifest.Apps[i]
serviceName := ServiceUnitName(ra.Name)
opts = append(opts, unit.NewUnitOption("Unit", "After", serviceName))
opts = append(opts, unit.NewUnitOption("Unit", "Wants", serviceName))
}
unitsPath := filepath.Join(common.Stage1RootfsPath(p.Root), UnitsDir)
file, err := os.OpenFile(filepath.Join(unitsPath, "default.target"), os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
if err != nil {
return err
}
defer file.Close()
if _, err = io.Copy(file, unit.Serialize(opts)); err != nil {
return err
}
return nil
}
// WritePrepareAppTemplate writes service unit files for preparing the pod's applications
func WritePrepareAppTemplate(p *stage1commontypes.Pod) error {
opts := []*unit.UnitOption{
unit.NewUnitOption("Unit", "Description", "Prepare minimum environment for chrooted applications"),
unit.NewUnitOption("Unit", "DefaultDependencies", "false"),
unit.NewUnitOption("Unit", "OnFailureJobMode", "fail"),
unit.NewUnitOption("Unit", "Requires", "systemd-journald.service"),
unit.NewUnitOption("Unit", "After", "systemd-journald.service"),
unit.NewUnitOption("Service", "Type", "oneshot"),
unit.NewUnitOption("Service", "Restart", "no"),
unit.NewUnitOption("Service", "ExecStart", "/prepare-app %I"),
unit.NewUnitOption("Service", "User", "0"),
unit.NewUnitOption("Service", "Group", "0"),
unit.NewUnitOption("Service", "CapabilityBoundingSet", "CAP_SYS_ADMIN CAP_DAC_OVERRIDE"),
}
unitsPath := filepath.Join(common.Stage1RootfsPath(p.Root), UnitsDir)
file, err := os.OpenFile(filepath.Join(unitsPath, "prepare-app@.service"), os.O_WRONLY|os.O_CREATE, 0644)
if err != nil {
return errwrap.Wrap(errors.New("failed to create service unit file"), err)
}
defer file.Close()
if _, err = io.Copy(file, unit.Serialize(opts)); err != nil {
return errwrap.Wrap(errors.New("failed to write service unit file"), err)
}
return nil
}
func writeAppReaper(p *stage1commontypes.Pod, appName string, appRootDirectory string, binPath string) error {
opts := []*unit.UnitOption{
unit.NewUnitOption("Unit", "Description", fmt.Sprintf("%s Reaper", appName)),
unit.NewUnitOption("Unit", "DefaultDependencies", "false"),
unit.NewUnitOption("Unit", "StopWhenUnneeded", "yes"),
unit.NewUnitOption("Unit", "Wants", "shutdown.service"),
unit.NewUnitOption("Unit", "After", "shutdown.service"),
unit.NewUnitOption("Unit", "Conflicts", "exit.target"),
unit.NewUnitOption("Unit", "Conflicts", "halt.target"),
unit.NewUnitOption("Unit", "Conflicts", "poweroff.target"),
unit.NewUnitOption("Service", "RemainAfterExit", "yes"),
unit.NewUnitOption("Service", "ExecStop", fmt.Sprintf("/reaper.sh \"%s\" \"%s\" \"%s\"", appName, appRootDirectory, binPath)),
}
unitsPath := filepath.Join(common.Stage1RootfsPath(p.Root), UnitsDir)
file, err := os.OpenFile(filepath.Join(unitsPath, fmt.Sprintf("reaper-%s.service", appName)), os.O_WRONLY|os.O_CREATE, 0644)
if err != nil {
return errwrap.Wrap(errors.New("failed to create service unit file"), err)
}
defer file.Close()
if _, err = io.Copy(file, unit.Serialize(opts)); err != nil {
return errwrap.Wrap(errors.New("failed to write service unit file"), err)
}
return nil
}
// SetJournalPermissions sets ACLs and permissions so the rkt group can access
// the pod's logs
func SetJournalPermissions(p *stage1commontypes.Pod) error {
s1 := common.Stage1ImagePath(p.Root)
rktgid, err := common.LookupGid(common.RktGroup)
if err != nil {
return fmt.Errorf("group %q not found", common.RktGroup)
}
journalPath := filepath.Join(s1, "rootfs", "var", "log", "journal")
if err := os.MkdirAll(journalPath, os.FileMode(0755)); err != nil {
return errwrap.Wrap(errors.New("error creating journal dir"), err)
}
a, err := acl.InitACL()
if err != nil {
return err
}
defer a.Free()
if err := a.ParseACL(fmt.Sprintf("g:%d:r-x,m:r-x", rktgid)); err != nil {
return errwrap.Wrap(errors.New("error parsing ACL string"), err)
}
if err := a.AddBaseEntries(journalPath); err != nil {
return errwrap.Wrap(errors.New("error adding base ACL entries"), err)
}
if err := a.Valid(); err != nil {
return err
}
if err := a.SetFileACLDefault(journalPath); err != nil {
return errwrap.Wrap(fmt.Errorf("error setting default ACLs on %q", journalPath), err)
}
return nil
}
func generateGidArg(gid int, supplGid []int) string {
arg := []string{strconv.Itoa(gid)}
for _, sg := range supplGid {
arg = append(arg, strconv.Itoa(sg))
}
return strings.Join(arg, ",")
}
// findHostPort returns the port number on the host that corresponds to an
// image manifest port identified by name
func findHostPort(pm schema.PodManifest, name types.ACName) uint {
var port uint
for _, p := range pm.Ports {
if p.Name == name {
port = p.HostPort
}
}
return port
}
// generateSysusers generates systemd sysusers files for a given app so that
// corresponding entries in /etc/passwd and /etc/group are created in stage1.
// This is needed to use the "User=" and "Group=" options in the systemd
// service files of apps.
// If there're several apps defining the same UIDs/GIDs, systemd will take care
// of only generating one /etc/{passwd,group} entry
func generateSysusers(p *stage1commontypes.Pod, ra *schema.RuntimeApp, uid_ int, gid_ int, uidRange *user.UidRange) error {
var toShift []string
app := ra.App
appName := ra.Name
sysusersDir := path.Join(common.Stage1RootfsPath(p.Root), "usr/lib/sysusers.d")
toShift = append(toShift, sysusersDir)
if err := os.MkdirAll(sysusersDir, 0755); err != nil {
return err
}
gids := append(app.SupplementaryGIDs, gid_)
// Create the Unix user and group
var sysusersConf []string
for _, g := range gids {
groupname := "gen" + strconv.Itoa(g)
sysusersConf = append(sysusersConf, fmt.Sprintf("g %s %d\n", groupname, g))
}
username := "gen" + strconv.Itoa(uid_)
sysusersConf = append(sysusersConf, fmt.Sprintf("u %s %d \"%s\"\n", username, uid_, username))
sysusersFile := path.Join(common.Stage1RootfsPath(p.Root), "usr/lib/sysusers.d", ServiceUnitName(appName)+".conf")
toShift = append(toShift, sysusersFile)
if err := ioutil.WriteFile(sysusersFile, []byte(strings.Join(sysusersConf, "\n")), 0640); err != nil {
return err
}
if err := shiftFiles(toShift, uidRange); err != nil {
return err
}
return nil
}
// lookupPathInsideApp returns the path (relative to the app rootfs) of the
// given binary. It will look up on "paths" (also relative to the app rootfs)
// and evaluate possible symlinks to check if the resulting path is actually
// executable.
func lookupPathInsideApp(bin string, paths string, appRootfs string, workDir string) (string, error) {
pathsArr := filepath.SplitList(paths)
var appPathsArr []string
for _, p := range pathsArr {
if !filepath.IsAbs(p) {
p = filepath.Join(workDir, p)
}
appPathsArr = append(appPathsArr, filepath.Join(appRootfs, p))
}
for _, path := range appPathsArr {
binPath := filepath.Join(path, bin)
stage2Path := strings.TrimPrefix(binPath, appRootfs)
binRealPath, err := EvaluateSymlinksInsideApp(appRootfs, stage2Path)
if err != nil {
return "", errwrap.Wrap(fmt.Errorf("could not evaluate path %v", stage2Path), err)
}
binRealPath = filepath.Join(appRootfs, binRealPath)
if fileutil.IsExecutable(binRealPath) {
// The real path is executable, return the path relative to the app
return stage2Path, nil
}
}
return "", fmt.Errorf("unable to find %q in %q", bin, paths)
}
// appSearchPaths returns a list of paths where we should search for
// non-absolute exec binaries
func appSearchPaths(p *stage1commontypes.Pod, workDir string, app types.App) []string {
appEnv := app.Environment
if imgPath, ok := appEnv.Get("PATH"); ok {
return strings.Split(imgPath, ":")
}
// emulate exec(3) behavior, first check working directory and then the
// list of directories returned by confstr(_CS_PATH). That's typically
// "/bin:/usr/bin" so let's use that.
return []string{workDir, "/bin", "/usr/bin"}
}
// findBinPath takes a binary path and returns a the absolute path of the
// binary relative to the app rootfs. This can be passed to ExecStart on the
// app's systemd service file directly.
func findBinPath(p *stage1commontypes.Pod, appName types.ACName, app types.App, workDir string, bin string) (string, error) {
var binPath string
switch {
// absolute path, just use it
case filepath.IsAbs(bin):
binPath = bin
// non-absolute path containing a slash, look in the working dir
case strings.Contains(bin, "/"):
binPath = filepath.Join(workDir, bin)
// filename, search in the app's $PATH
default:
absRoot, err := filepath.Abs(p.Root)
if err != nil {
return "", errwrap.Wrap(errors.New("could not get pod's root absolute path"), err)
}
appRootfs := common.AppRootfsPath(absRoot, appName)
appPathDirs := appSearchPaths(p, workDir, app)
appPath := strings.Join(appPathDirs, ":")
binPath, err = lookupPathInsideApp(bin, appPath, appRootfs, workDir)
if err != nil {
return "", errwrap.Wrap(fmt.Errorf("error looking up %q", bin), err)
}
}
return binPath, nil
}
// shiftFiles shifts filesToshift by the amounts specified in uidRange
func shiftFiles(filesToShift []string, uidRange *user.UidRange) error {
if uidRange.Shift != 0 && uidRange.Count != 0 {
for _, f := range filesToShift {
if err := os.Chown(f, int(uidRange.Shift), int(uidRange.Shift)); err != nil {
return err
}
}
}
return nil
}
// generateDeviceAllows generates a DeviceAllow= line for an app.
// To make it work, the path needs to start with "/dev" but the device won't
// exist inside the container. So for a given mount, if the volume is a device
// node, we create a symlink to its target in "/rkt/volumes". Later,
// prepare-app will copy those to "/dev/.rkt/" so that's what we use in the
// DeviceAllow= line.
func generateDeviceAllows(root string, appName types.ACName, mountPoints []types.MountPoint, mounts []mountWrapper, vols map[types.ACName]types.Volume, uidRange *user.UidRange) ([]string, error) {
var devAllow []string
rktVolumeLinksPath := filepath.Join(root, "rkt", "volumes")
if err := os.MkdirAll(rktVolumeLinksPath, 0600); err != nil {
return nil, err
}
if err := shiftFiles([]string{rktVolumeLinksPath}, uidRange); err != nil {
return nil, err
}
for _, m := range mounts {
v := vols[m.Volume]
if v.Kind != "host" {
continue
}
if fileutil.IsDeviceNode(v.Source) {
mode := "r"
if !IsMountReadOnly(v, mountPoints) {
mode += "w"
}
tgt := filepath.Join(common.RelAppRootfsPath(appName), m.Path)
// the DeviceAllow= line needs the link path in /dev/.rkt/
linkRel := filepath.Join("/dev/.rkt", v.Name.String())
// the real link should be in /rkt/volumes for now
link := filepath.Join(rktVolumeLinksPath, v.Name.String())
err := os.Symlink(tgt, link)
// if the link already exists, we don't need to do anything
if err != nil && !os.IsExist(err) {
return nil, err
}
devAllow = append(devAllow, linkRel+" "+mode)
}
}
return devAllow, nil
}
// appToSystemd transforms the provided RuntimeApp+ImageManifest into systemd units
func appToSystemd(p *stage1commontypes.Pod, ra *schema.RuntimeApp, interactive bool, flavor string, privateUsers string, insecureOptions Stage1InsecureOptions) error {
app := ra.App
appName := ra.Name
imgName := p.AppNameToImageName(appName)
if len(app.Exec) == 0 {
return fmt.Errorf(`image %q has an empty "exec" (try --exec=BINARY)`, imgName)
}
workDir := "/"
if app.WorkingDirectory != "" {
workDir = app.WorkingDirectory
}
env := app.Environment
env.Set("AC_APP_NAME", appName.String())
if p.MetadataServiceURL != "" {
env.Set("AC_METADATA_URL", p.MetadataServiceURL)
}
envFilePath := EnvFilePath(p.Root, appName)
uidRange := user.NewBlankUidRange()
if err := uidRange.Deserialize([]byte(privateUsers)); err != nil {
return err
}
if err := writeEnvFile(p, env, appName, uidRange, '\n', envFilePath); err != nil {
return errwrap.Wrap(errors.New("unable to write environment file for systemd"), err)
}
u, g, err := parseUserGroup(p, ra, uidRange)
if err != nil {
return err
}
if err := generateSysusers(p, ra, u, g, uidRange); err != nil {
return errwrap.Wrap(errors.New("unable to generate sysusers"), err)
}
binPath, err := findBinPath(p, appName, *app, workDir, app.Exec[0])
if err != nil {
return err
}
var supplementaryGroups []string
for _, g := range app.SupplementaryGIDs {
supplementaryGroups = append(supplementaryGroups, strconv.Itoa(g))
}
capabilitiesStr, err := getAppCapabilities(app.Isolators)
if err != nil {
return err
}
execStart := append([]string{binPath}, app.Exec[1:]...)
execStartString := quoteExec(execStart)
opts := []*unit.UnitOption{
unit.NewUnitOption("Unit", "Description", fmt.Sprintf("Application=%v Image=%v", appName, imgName)),
unit.NewUnitOption("Unit", "DefaultDependencies", "false"),
unit.NewUnitOption("Unit", "Wants", fmt.Sprintf("reaper-%s.service", appName)),
unit.NewUnitOption("Service", "Restart", "no"),
unit.NewUnitOption("Service", "ExecStart", execStartString),
unit.NewUnitOption("Service", "RootDirectory", common.RelAppRootfsPath(appName)),
// MountFlags=shared creates a new mount namespace and (as unintuitive
// as it might seem) makes sure the mount is slave+shared.
unit.NewUnitOption("Service", "MountFlags", "shared"),
unit.NewUnitOption("Service", "WorkingDirectory", workDir),
unit.NewUnitOption("Service", "EnvironmentFile", RelEnvFilePath(appName)),
unit.NewUnitOption("Service", "User", strconv.Itoa(u)),
unit.NewUnitOption("Service", "Group", strconv.Itoa(g)),
unit.NewUnitOption("Service", "SupplementaryGroups", strings.Join(supplementaryGroups, " ")),
// This helps working around a race
// (https://github.com/systemd/systemd/issues/2913) that causes the
// systemd unit name not getting written to the journal if the unit is
// short-lived and runs as non-root.
unit.NewUnitOption("Service", "SyslogIdentifier", appName.String()),
}
if !insecureOptions.DisableCapabilities {
opts = append(opts, unit.NewUnitOption("Service", "CapabilityBoundingSet", strings.Join(capabilitiesStr, " ")))
}
noNewPrivileges := getAppNoNewPrivileges(app.Isolators)
// Apply seccomp isolator, if any and not opt-ing out;
// see https://www.freedesktop.org/software/systemd/man/systemd.exec.html#SystemCallFilter=
if !insecureOptions.DisableSeccomp {
var forceNoNewPrivileges bool
unprivileged := (u != 0)
opts, forceNoNewPrivileges, err = getSeccompFilter(opts, p, unprivileged, app.Isolators)
if err != nil {
return err
}
// Seccomp filters require NoNewPrivileges for unprivileged apps, that may override
// manifest annotation.
if forceNoNewPrivileges {
noNewPrivileges = true
}
}
opts = append(opts, unit.NewUnitOption("Service", "NoNewPrivileges", strconv.FormatBool(noNewPrivileges)))
if ra.ReadOnlyRootFS {
opts = append(opts, unit.NewUnitOption("Service", "ReadOnlyDirectories", common.RelAppRootfsPath(appName)))
}
// TODO(tmrts): Extract this logic into a utility function.
vols := make(map[types.ACName]types.Volume)
for _, v := range p.Manifest.Volumes {
vols[v.Name] = v
}
absRoot, err := filepath.Abs(p.Root) // Absolute path to the pod's rootfs.
if err != nil {
return err
}
appRootfs := common.AppRootfsPath(absRoot, appName)
rwDirs := []string{}
imageManifest := p.Images[appName.String()]
mounts := GenerateMounts(ra, vols, imageManifest)
for _, m := range mounts {
mntPath, err := EvaluateSymlinksInsideApp(appRootfs, m.Path)
if err != nil {
return err
}
if !IsMountReadOnly(vols[m.Volume], app.MountPoints) {
rwDirs = append(rwDirs, filepath.Join(common.RelAppRootfsPath(appName), mntPath))
}
}
// Restrict access to sensitive paths (eg. procfs) and devices
if !insecureOptions.DisablePaths {
opts = protectSystemFiles(opts, appName)
opts = append(opts, unit.NewUnitOption("Service", "DevicePolicy", "closed"))
deviceAllows, err := generateDeviceAllows(common.Stage1RootfsPath(absRoot), appName, app.MountPoints, mounts, vols, uidRange)
if err != nil {
return err
}
for _, dev := range deviceAllows {
opts = append(opts, unit.NewUnitOption("Service", "DeviceAllow", dev))
}
}
opts = append(opts, unit.NewUnitOption("Service", "ReadWriteDirectories", strings.Join(rwDirs, " ")))
if interactive {
opts = append(opts, unit.NewUnitOption("Service", "StandardInput", "tty"))
opts = append(opts, unit.NewUnitOption("Service", "StandardOutput", "tty"))
opts = append(opts, unit.NewUnitOption("Service", "StandardError", "tty"))
} else {
opts = append(opts, unit.NewUnitOption("Service", "StandardOutput", "journal+console"))
opts = append(opts, unit.NewUnitOption("Service", "StandardError", "journal+console"))
}
// When an app fails, we shut down the pod
opts = append(opts, unit.NewUnitOption("Unit", "OnFailure", "halt.target"))
for _, eh := range app.EventHandlers {
var typ string
switch eh.Name {
case "pre-start":
typ = "ExecStartPre"
case "post-stop":
typ = "ExecStopPost"
default:
return fmt.Errorf("unrecognized eventHandler: %v", eh.Name)
}
exec := quoteExec(eh.Exec)
opts = append(opts, unit.NewUnitOption("Service", typ, exec))
}
// Some pre-start jobs take a long time, set the timeout to 0
opts = append(opts, unit.NewUnitOption("Service", "TimeoutStartSec", "0"))
var saPorts []types.Port
for _, p := range app.Ports {
if p.SocketActivated {
saPorts = append(saPorts, p)
}
}
for _, i := range app.Isolators {
switch v := i.Value().(type) {
case *types.ResourceMemory:
opts, err = cgroup.MaybeAddIsolator(opts, "memory", v.Limit())
if err != nil {
return err
}
case *types.ResourceCPU:
opts, err = cgroup.MaybeAddIsolator(opts, "cpu", v.Limit())
if err != nil {
return err
}
}
}
if len(saPorts) > 0 {
sockopts := []*unit.UnitOption{
unit.NewUnitOption("Unit", "Description", fmt.Sprintf("Application=%v Image=%v %s", appName, imgName, "socket-activated ports")),
unit.NewUnitOption("Unit", "DefaultDependencies", "false"),
unit.NewUnitOption("Socket", "BindIPv6Only", "both"),
unit.NewUnitOption("Socket", "Service", ServiceUnitName(appName)),
}
for _, sap := range saPorts {
var proto string
switch sap.Protocol {
case "tcp":
proto = "ListenStream"
case "udp":
proto = "ListenDatagram"
default:
return fmt.Errorf("unrecognized protocol: %v", sap.Protocol)
}
// We find the host port for the pod's port and use that in the
// socket unit file.
// This is so because systemd inside the pod will match based on
// the socket port number, and since the socket was created on the
// host, it will have the host port number.
port := findHostPort(*p.Manifest, sap.Name)
if port == 0 {
log.Printf("warning: no --port option for socket-activated port %q, assuming port %d as specified in the manifest", sap.Name, sap.Port)
port = sap.Port
}
sockopts = append(sockopts, unit.NewUnitOption("Socket", proto, fmt.Sprintf("%v", port)))
}
file, err := os.OpenFile(SocketUnitPath(p.Root, appName), os.O_WRONLY|os.O_CREATE, 0644)
if err != nil {
return errwrap.Wrap(errors.New("failed to create socket file"), err)
}
defer file.Close()
if _, err = io.Copy(file, unit.Serialize(sockopts)); err != nil {
return errwrap.Wrap(errors.New("failed to write socket unit file"), err)
}
if err = os.Symlink(path.Join("..", SocketUnitName(appName)), SocketWantPath(p.Root, appName)); err != nil {
return errwrap.Wrap(errors.New("failed to link socket want"), err)
}
opts = append(opts, unit.NewUnitOption("Unit", "Requires", SocketUnitName(appName)))
}
opts = append(opts, unit.NewUnitOption("Unit", "Requires", InstantiatedPrepareAppUnitName(appName)))
opts = append(opts, unit.NewUnitOption("Unit", "After", InstantiatedPrepareAppUnitName(appName)))
opts = append(opts, unit.NewUnitOption("Unit", "Requires", "sysusers.service"))
opts = append(opts, unit.NewUnitOption("Unit", "After", "sysusers.service"))
file, err := os.OpenFile(ServiceUnitPath(p.Root, appName), os.O_WRONLY|os.O_CREATE, 0644)
if err != nil {
return errwrap.Wrap(errors.New("failed to create service unit file"), err)
}
defer file.Close()
if _, err = io.Copy(file, unit.Serialize(opts)); err != nil {
return errwrap.Wrap(errors.New("failed to write service unit file"), err)
}
if err = os.Symlink(path.Join("..", ServiceUnitName(appName)), ServiceWantPath(p.Root, appName)); err != nil {
return errwrap.Wrap(errors.New("failed to link service want"), err)
}
if err = writeAppReaper(p, appName.String(), common.RelAppRootfsPath(appName), binPath); err != nil {
return errwrap.Wrap(fmt.Errorf("failed to write app %q reaper service", appName), err)
}
return nil
}
// parseUserGroup parses the User and Group fields of an App and returns its
// UID and GID.
// The User and Group fields accept several formats:
// 1. the hardcoded string "root"
// 2. a path
// 3. a number
// 4. a name in reference to /etc/{group,passwd} in the image
// See https://github.com/appc/spec/blob/master/spec/aci.md#image-manifest-schema
func parseUserGroup(p *stage1commontypes.Pod, ra *schema.RuntimeApp, uidRange *user.UidRange) (int, int, error) {
var uidResolver, gidResolver user.Resolver
var uid, gid int
var err error
root := common.AppRootfsPath(p.Root, ra.Name)
uidResolver, err = user.NumericIDs(ra.App.User)
if err != nil {
uidResolver, err = user.IDsFromStat(root, ra.App.User, uidRange)
}
if err != nil {
uidResolver, err = user.IDsFromEtc(root, ra.App.User, "")
}
if err != nil { // give up
return -1, -1, errwrap.Wrap(fmt.Errorf("invalid user %q", ra.App.User), err)
}
if uid, _, err = uidResolver.IDs(); err != nil {
return -1, -1, errwrap.Wrap(fmt.Errorf("failed to configure user %q", ra.App.User), err)
}
gidResolver, err = user.NumericIDs(ra.App.Group)
if err != nil {
gidResolver, err = user.IDsFromStat(root, ra.App.Group, uidRange)
}
if err != nil {
gidResolver, err = user.IDsFromEtc(root, "", ra.App.Group)
}
if err != nil { // give up
return -1, -1, errwrap.Wrap(fmt.Errorf("invalid group %q", ra.App.Group), err)
}
if _, gid, err = gidResolver.IDs(); err != nil {
return -1, -1, errwrap.Wrap(fmt.Errorf("failed to configure group %q", ra.App.Group), err)
}
return uid, gid, nil
}
func writeShutdownService(p *stage1commontypes.Pod) error {
flavor, systemdVersion, err := GetFlavor(p)
if err != nil {
return err
}
opts := []*unit.UnitOption{
unit.NewUnitOption("Unit", "Description", "Pod shutdown"),
unit.NewUnitOption("Unit", "AllowIsolate", "true"),
unit.NewUnitOption("Unit", "StopWhenUnneeded", "yes"),
unit.NewUnitOption("Unit", "DefaultDependencies", "false"),
unit.NewUnitOption("Service", "RemainAfterExit", "yes"),
}
shutdownVerb := "exit"
// systemd <v227 doesn't allow the "exit" verb when running as PID 1, so
// use "halt".
// If systemdVersion is 0 it means it couldn't be guessed, assume it's new
// enough for "systemctl exit".
// This can happen, for example, when building rkt with:
//
// ./configure --with-stage1-flavors=src --with-stage1-systemd-version=master
//
// The patches for the "exit" verb are backported to the "coreos" flavor, so
// don't rely on the systemd version on the "coreos" flavor.
if flavor != "coreos" && systemdVersion != 0 && systemdVersion < 227 {
shutdownVerb = "halt"
}
opts = append(opts, unit.NewUnitOption("Service", "ExecStop", fmt.Sprintf("/usr/bin/systemctl --force %s", shutdownVerb)))
unitsPath := filepath.Join(common.Stage1RootfsPath(p.Root), UnitsDir)
file, err := os.OpenFile(filepath.Join(unitsPath, "shutdown.service"), os.O_WRONLY|os.O_CREATE, 0644)
if err != nil {
return errwrap.Wrap(errors.New("failed to create unit file"), err)
}
defer file.Close()
if _, err = io.Copy(file, unit.Serialize(opts)); err != nil {
return errwrap.Wrap(errors.New("failed to write unit file"), err)
}
return nil
}
// writeEnvFile creates an environment file for given app name, the minimum
// required environment variables by the appc spec will be set to sensible
// defaults here if they're not provided by env.
func writeEnvFile(p *stage1commontypes.Pod, env types.Environment, appName types.ACName, uidRange *user.UidRange, separator byte, envFilePath string) error {
ef := bytes.Buffer{}
for dk, dv := range defaultEnv {
if _, exists := env.Get(dk); !exists {
fmt.Fprintf(&ef, "%s=%s%c", dk, dv, separator)
}
}
for _, e := range env {
fmt.Fprintf(&ef, "%s=%s%c", e.Name, e.Value, separator)
}
if err := ioutil.WriteFile(envFilePath, ef.Bytes(), 0644); err != nil {
return err
}
if err := shiftFiles([]string{envFilePath}, uidRange); err != nil {
return err
}
return nil
}
// PodToSystemd creates the appropriate systemd service unit files for
// all the constituent apps of the Pod
func PodToSystemd(p *stage1commontypes.Pod, interactive bool, flavor string, privateUsers string, insecureOptions Stage1InsecureOptions) error {
for i := range p.Manifest.Apps {
ra := &p.Manifest.Apps[i]
if err := appToSystemd(p, ra, interactive, flavor, privateUsers, insecureOptions); err != nil {
return errwrap.Wrap(fmt.Errorf("failed to transform app %q into systemd service", ra.Name), err)
}
}
if err := writeShutdownService(p); err != nil {
return errwrap.Wrap(errors.New("failed to write shutdown service"), err)
}
return nil
}
// EvaluateSymlinksInsideApp tries to resolve symlinks within the path.
// It returns the actual path relative to the app rootfs for the given path.
func EvaluateSymlinksInsideApp(appRootfs, path string) (string, error) {
link := appRootfs
paths := strings.Split(path, "/")
for i, p := range paths {
next := filepath.Join(link, p)
if !strings.HasPrefix(next, appRootfs) {
return "", fmt.Errorf("path escapes app's root: %q", path)
}
fi, err := os.Lstat(next)
if err != nil {
if os.IsNotExist(err) {
link = filepath.Join(append([]string{link}, paths[i:]...)...)
break
}
return "", err
}
if fi.Mode()&os.ModeType != os.ModeSymlink {
link = filepath.Join(link, p)
continue
}
// Evaluate the symlink.
target, err := os.Readlink(next)
if err != nil {
return "", err
}
if filepath.IsAbs(target) {
link = filepath.Join(appRootfs, target)
} else {
link = filepath.Join(link, target)
}
if !strings.HasPrefix(link, appRootfs) {
return "", fmt.Errorf("symlink %q escapes app's root with value %q", next, target)
}
}
return strings.TrimPrefix(link, appRootfs), nil
}
// appToNspawnArgs transforms the given app manifest, with the given associated
// app name, into a subset of applicable systemd-nspawn argument
func appToNspawnArgs(p *stage1commontypes.Pod, ra *schema.RuntimeApp, insecureOptions Stage1InsecureOptions) ([]string, error) {
var args []string
appName := ra.Name
app := ra.App
sharedVolPath := common.SharedVolumesPath(p.Root)
if err := os.MkdirAll(sharedVolPath, SharedVolPerm); err != nil {
return nil, errwrap.Wrap(errors.New("could not create shared volumes directory"), err)
}
if err := os.Chmod(sharedVolPath, SharedVolPerm); err != nil {
return nil, errwrap.Wrap(fmt.Errorf("could not change permissions of %q", sharedVolPath), err)
}
vols := make(map[types.ACName]types.Volume)
for _, v := range p.Manifest.Volumes {
vols[v.Name] = v
}
imageManifest := p.Images[appName.String()]
mounts := GenerateMounts(ra, vols, imageManifest)
for _, m := range mounts {
vol := vols[m.Volume]
shPath := filepath.Join(sharedVolPath, vol.Name.String())
absRoot, err := filepath.Abs(p.Root) // Absolute path to the pod's rootfs.
if err != nil {
return nil, errwrap.Wrap(errors.New("could not get pod's root absolute path"), err)
}
appRootfs := common.AppRootfsPath(absRoot, appName)
// TODO(yifan): This is a temporary fix for systemd-nspawn not handling symlink mounts well.
// Could be removed when https://github.com/systemd/systemd/issues/2860 is resolved, and systemd
// version is bumped.
mntPath, err := EvaluateSymlinksInsideApp(appRootfs, m.Path)
if err != nil {
return nil, errwrap.Wrap(fmt.Errorf("could not evaluate path %v", m.Path), err)
}
mntAbsPath := filepath.Join(appRootfs, mntPath)
if err := PrepareMountpoints(shPath, mntAbsPath, &vol, m.DockerImplicit); err != nil {
return nil, err
}
opt := make([]string, 4)
if IsMountReadOnly(vol, app.MountPoints) {
opt[0] = "--bind-ro="
} else {
opt[0] = "--bind="
}
switch vol.Kind {
case "host":
opt[1] = vol.Source
case "empty":
opt[1] = filepath.Join(common.SharedVolumesPath(absRoot), vol.Name.String())
default:
return nil, fmt.Errorf(`invalid volume kind %q. Must be one of "host" or "empty"`, vol.Kind)
}
opt[2] = ":"
opt[3] = filepath.Join(common.RelAppRootfsPath(appName), mntPath)
args = append(args, strings.Join(opt, ""))
}
if !insecureOptions.DisableCapabilities {
capabilitiesStr, err := getAppCapabilities(app.Isolators)
if err != nil {
return nil, err
}
capList := strings.Join(capabilitiesStr, ",")
args = append(args, "--capability="+capList)
}
return args, nil
}
// PodToNspawnArgs renders a prepared Pod as a systemd-nspawn
// argument list ready to be executed
func PodToNspawnArgs(p *stage1commontypes.Pod, insecureOptions Stage1InsecureOptions) ([]string, error) {
args := []string{
"--uuid=" + p.UUID.String(),
"--machine=" + GetMachineID(p),
"--directory=" + common.Stage1RootfsPath(p.Root),
}
for i := range p.Manifest.Apps {
aa, err := appToNspawnArgs(p, &p.Manifest.Apps[i], insecureOptions)
if err != nil {
return nil, err
}
args = append(args, aa...)
}
if insecureOptions.DisableCapabilities {
args = append(args, "--capability=all")
}
return args, nil
}
// GetFlavor populates a flavor string based on the flavor itself and respectively the systemd version