forked from cloudfoundry/bosh-agent
-
Notifications
You must be signed in to change notification settings - Fork 1
/
linux_platform.go
1504 lines (1229 loc) · 44.4 KB
/
linux_platform.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
package platform
import (
"bytes"
"fmt"
"os"
"path"
"path/filepath"
"regexp"
"strconv"
"strings"
"text/template"
boshdpresolv "github.com/cloudfoundry/bosh-agent/infrastructure/devicepathresolver"
boshcert "github.com/cloudfoundry/bosh-agent/platform/cert"
boshdevutil "github.com/cloudfoundry/bosh-agent/platform/deviceutil"
boshdisk "github.com/cloudfoundry/bosh-agent/platform/disk"
boshnet "github.com/cloudfoundry/bosh-agent/platform/net"
boshstats "github.com/cloudfoundry/bosh-agent/platform/stats"
boshvitals "github.com/cloudfoundry/bosh-agent/platform/vitals"
boshsettings "github.com/cloudfoundry/bosh-agent/settings"
boshdir "github.com/cloudfoundry/bosh-agent/settings/directories"
boshdirs "github.com/cloudfoundry/bosh-agent/settings/directories"
bosherr "github.com/cloudfoundry/bosh-utils/errors"
boshcmd "github.com/cloudfoundry/bosh-utils/fileutil"
boshlog "github.com/cloudfoundry/bosh-utils/logger"
boshretry "github.com/cloudfoundry/bosh-utils/retrystrategy"
boshsys "github.com/cloudfoundry/bosh-utils/system"
boshuuid "github.com/cloudfoundry/bosh-utils/uuid"
)
const (
ephemeralDiskPermissions = os.FileMode(0750)
persistentDiskPermissions = os.FileMode(0700)
logDirPermissions = os.FileMode(0750)
runDirPermissions = os.FileMode(0750)
jobsDirPermissions = os.FileMode(0750)
packagesDirPermissions = os.FileMode(0755)
userBaseDirPermissions = os.FileMode(0755)
disksDirPermissions = os.FileMode(0755)
userRootLogDirPermissions = os.FileMode(0775)
tmpDirPermissions = os.FileMode(0755) // 0755 to make sure that vcap user can use new temp dir
blobsDirPermissions = os.FileMode(0700)
sshDirPermissions = os.FileMode(0700)
sshAuthKeysFilePermissions = os.FileMode(0600)
minRootEphemeralSpaceInBytes = uint64(1024 * 1024 * 1024)
maxFdiskPartitionSize = uint64(2 * 1024 * 1024 * 1024 * 1024)
)
type LinuxOptions struct {
// When set to true loop back device
// is not going to be overlayed over /tmp to limit /tmp dir size
UseDefaultTmpDir bool
// When set to true the agent will scrub ephemeral disk if agent version is
// different with stemcell version
ScrubEphemeralDisk bool
// When set to true persistent disk will be assumed to be pre-formatted;
// otherwise agent will partition and format it right before mounting
UsePreformattedPersistentDisk bool
// When set to true persistent disk will be mounted as a bind-mount
BindMountPersistentDisk bool
// When set to true and no ephemeral disk is mounted, the agent will create
// a partition on the same device as the root partition to use as the
// ephemeral disk
CreatePartitionIfNoEphemeralDisk bool
// When set to true the agent will skip both root and ephemeral disk partitioning
SkipDiskSetup bool
// Strategy for resolving device paths;
// possible values: virtio, scsi, ""
DevicePathResolutionType string
// Strategy for resolving ephemeral & persistent disk partitioners;
// possible values: parted, "" (default is sfdisk if disk < 2TB, parted otherwise)
PartitionerType string
}
type linux struct {
fs boshsys.FileSystem
cmdRunner boshsys.CmdRunner
collector boshstats.Collector
compressor boshcmd.Compressor
copier boshcmd.Copier
dirProvider boshdirs.Provider
vitalsService boshvitals.Service
cdutil boshdevutil.DeviceUtil
diskManager boshdisk.Manager
netManager boshnet.Manager
certManager boshcert.Manager
monitRetryStrategy boshretry.RetryStrategy
devicePathResolver boshdpresolv.DevicePathResolver
options LinuxOptions
state *BootstrapState
logger boshlog.Logger
defaultNetworkResolver boshsettings.DefaultNetworkResolver
uuidGenerator boshuuid.Generator
auditLogger AuditLogger
}
func NewLinuxPlatform(
fs boshsys.FileSystem,
cmdRunner boshsys.CmdRunner,
collector boshstats.Collector,
compressor boshcmd.Compressor,
copier boshcmd.Copier,
dirProvider boshdirs.Provider,
vitalsService boshvitals.Service,
cdutil boshdevutil.DeviceUtil,
diskManager boshdisk.Manager,
netManager boshnet.Manager,
certManager boshcert.Manager,
monitRetryStrategy boshretry.RetryStrategy,
devicePathResolver boshdpresolv.DevicePathResolver,
state *BootstrapState,
options LinuxOptions,
logger boshlog.Logger,
defaultNetworkResolver boshsettings.DefaultNetworkResolver,
uuidGenerator boshuuid.Generator,
auditLogger AuditLogger,
) Platform {
return &linux{
fs: fs,
cmdRunner: cmdRunner,
collector: collector,
compressor: compressor,
copier: copier,
dirProvider: dirProvider,
vitalsService: vitalsService,
cdutil: cdutil,
diskManager: diskManager,
netManager: netManager,
certManager: certManager,
monitRetryStrategy: monitRetryStrategy,
devicePathResolver: devicePathResolver,
state: state,
options: options,
logger: logger,
defaultNetworkResolver: defaultNetworkResolver,
uuidGenerator: uuidGenerator,
auditLogger: auditLogger,
}
}
const logTag = "linuxPlatform"
func (p linux) AssociateDisk(name string, settings boshsettings.DiskSettings) error {
disksDir := p.dirProvider.DisksDir()
err := p.fs.MkdirAll(disksDir, disksDirPermissions)
if err != nil {
bosherr.WrapError(err, "Associating disk: ")
}
linkPath := path.Join(disksDir, name)
devicePath, _, err := p.devicePathResolver.GetRealDevicePath(settings)
if err != nil {
return bosherr.WrapErrorf(err, "Associating disk with name %s", name)
}
return p.fs.Symlink(devicePath, linkPath)
}
func (p linux) GetFs() (fs boshsys.FileSystem) {
return p.fs
}
func (p linux) GetRunner() (runner boshsys.CmdRunner) {
return p.cmdRunner
}
func (p linux) GetCompressor() (runner boshcmd.Compressor) {
return p.compressor
}
func (p linux) GetCopier() (runner boshcmd.Copier) {
return p.copier
}
func (p linux) GetDirProvider() (dirProvider boshdir.Provider) {
return p.dirProvider
}
func (p linux) GetVitalsService() (service boshvitals.Service) {
return p.vitalsService
}
func (p linux) GetFileContentsFromCDROM(fileName string) (content []byte, err error) {
contents, err := p.cdutil.GetFilesContents([]string{fileName})
if err != nil {
return []byte{}, err
}
return contents[0], nil
}
func (p linux) GetFilesContentsFromDisk(diskPath string, fileNames []string) ([][]byte, error) {
return p.diskManager.GetDiskUtil(diskPath).GetFilesContents(fileNames)
}
func (p linux) GetDevicePathResolver() (devicePathResolver boshdpresolv.DevicePathResolver) {
return p.devicePathResolver
}
func (p linux) GetAuditLogger() AuditLogger {
return p.auditLogger
}
func (p linux) SetupNetworking(networks boshsettings.Networks) (err error) {
return p.netManager.SetupNetworking(networks, nil)
}
func (p linux) GetConfiguredNetworkInterfaces() ([]string, error) {
return p.netManager.GetConfiguredNetworkInterfaces()
}
func (p linux) GetCertManager() boshcert.Manager {
return p.certManager
}
func (p linux) GetHostPublicKey() (string, error) {
hostPublicKeyPath := "/etc/ssh/ssh_host_rsa_key.pub"
hostPublicKey, err := p.fs.ReadFileString(hostPublicKeyPath)
if err != nil {
return "", bosherr.WrapErrorf(err, "Unable to read host public key file: %s", hostPublicKeyPath)
}
return hostPublicKey, nil
}
func (p linux) SetupRuntimeConfiguration() (err error) {
_, _, _, err = p.cmdRunner.RunCommand("bosh-agent-rc")
if err != nil {
err = bosherr.WrapError(err, "Shelling out to bosh-agent-rc")
}
return
}
func (p linux) CreateUser(username, basePath string) error {
err := p.fs.MkdirAll(basePath, userBaseDirPermissions)
if err != nil {
return bosherr.WrapError(err, "Making user base path")
}
args := []string{"-m", "-b", basePath, "-s", "/bin/bash", username}
_, _, _, err = p.cmdRunner.RunCommand("useradd", args...)
if err != nil {
return bosherr.WrapError(err, "Shelling out to useradd")
}
userHomeDir, err := p.fs.HomeDir(username)
if err != nil {
return bosherr.WrapErrorf(err, "Unable to retrieve home directory for user %s", username)
}
_, _, _, err = p.cmdRunner.RunCommand("chmod", "700", userHomeDir)
if err != nil {
return bosherr.WrapError(err, "Shelling out to chmod")
}
return nil
}
func (p linux) AddUserToGroups(username string, groups []string) error {
_, _, _, err := p.cmdRunner.RunCommand("usermod", "-G", strings.Join(groups, ","), username)
if err != nil {
return bosherr.WrapError(err, "Shelling out to usermod")
}
return nil
}
func (p linux) DeleteEphemeralUsersMatching(reg string) error {
compiledReg, err := regexp.Compile(reg)
if err != nil {
return bosherr.WrapError(err, "Compiling regexp")
}
matchingUsers, err := p.findEphemeralUsersMatching(compiledReg)
if err != nil {
return bosherr.WrapError(err, "Finding ephemeral users")
}
for _, user := range matchingUsers {
err = p.deleteUser(user)
if err != nil {
return bosherr.WrapError(err, "Deleting user")
}
}
return nil
}
func (p linux) deleteUser(user string) (err error) {
_, _, _, err = p.cmdRunner.RunCommand("userdel", "-r", user)
return
}
func (p linux) findEphemeralUsersMatching(reg *regexp.Regexp) (matchingUsers []string, err error) {
passwd, err := p.fs.ReadFileString("/etc/passwd")
if err != nil {
err = bosherr.WrapError(err, "Reading /etc/passwd")
return
}
for _, line := range strings.Split(passwd, "\n") {
user := strings.Split(line, ":")[0]
matchesPrefix := strings.HasPrefix(user, boshsettings.EphemeralUserPrefix)
matchesReg := reg.MatchString(user)
if matchesPrefix && matchesReg {
matchingUsers = append(matchingUsers, user)
}
}
return
}
func (p linux) SetupRootDisk(ephemeralDiskPath string) error {
if p.options.SkipDiskSetup {
return nil
}
//if there is ephemeral disk we can safely autogrow, if not we should not.
if (ephemeralDiskPath == "") && (p.options.CreatePartitionIfNoEphemeralDisk == true) {
p.logger.Info(logTag, "No Ephemeral Disk provided, Skipping growing of the Root Filesystem")
return nil
}
// in case growpart is not available for another flavour of linux, don't stop the agent from running,
// without this integration-test would not run since the bosh-lite vm doesn't have it
if p.cmdRunner.CommandExists("growpart") == false {
p.logger.Info(logTag, "The program 'growpart' is not installed, Root Filesystem cannot be grown")
return nil
}
rootDevicePath, rootDeviceNumber, err := p.findRootDevicePathAndNumber()
if err != nil {
return bosherr.WrapError(err, "findRootDevicePath")
}
stdout, _, _, err := p.cmdRunner.RunCommand(
"growpart",
rootDevicePath,
strconv.Itoa(rootDeviceNumber),
)
if err != nil {
if strings.Contains(stdout, "NOCHANGE") == false {
return bosherr.WrapError(err, "growpart")
}
}
_, _, _, err = p.cmdRunner.RunCommand(
"resize2fs",
"-f",
fmt.Sprintf("%s%d", rootDevicePath, rootDeviceNumber),
)
if err != nil {
return bosherr.WrapError(err, "resize2fs")
}
return nil
}
func (p linux) SetupSSH(publicKeys []string, username string) error {
homeDir, err := p.fs.HomeDir(username)
if err != nil {
return bosherr.WrapError(err, "Finding home dir for user")
}
sshPath := path.Join(homeDir, ".ssh")
err = p.fs.MkdirAll(sshPath, sshDirPermissions)
if err != nil {
return bosherr.WrapError(err, "Making ssh directory")
}
err = p.fs.Chown(sshPath, username)
if err != nil {
return bosherr.WrapError(err, "Chowning ssh directory")
}
authKeysPath := path.Join(sshPath, "authorized_keys")
publicKeyString := strings.Join(publicKeys, "\n")
err = p.fs.WriteFileString(authKeysPath, publicKeyString)
if err != nil {
return bosherr.WrapError(err, "Creating authorized_keys file")
}
err = p.fs.Chown(authKeysPath, username)
if err != nil {
return bosherr.WrapError(err, "Chowning key path")
}
err = p.fs.Chmod(authKeysPath, sshAuthKeysFilePermissions)
if err != nil {
return bosherr.WrapError(err, "Chmoding key path")
}
return nil
}
func (p linux) SetUserPassword(user, encryptedPwd string) (err error) {
if encryptedPwd == "" {
encryptedPwd = "*"
}
_, _, _, err = p.cmdRunner.RunCommand("usermod", "-p", encryptedPwd, user)
if err != nil {
err = bosherr.WrapError(err, "Shelling out to usermod")
}
return
}
func (p linux) SetupRecordsJSONPermission(path string) error {
if err := p.fs.Chmod(path, 0640); err != nil {
return bosherr.WrapError(err, "Chmoding records JSON file")
}
if err := p.fs.Chown(path, "root:vcap"); err != nil {
return bosherr.WrapError(err, "Chowning records JSON file")
}
return nil
}
const EtcHostsTemplate = `127.0.0.1 localhost {{ . }}
# The following lines are desirable for IPv6 capable hosts
::1 localhost ip6-localhost ip6-loopback {{ . }}
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
ff02::3 ip6-allhosts
`
func (p linux) SaveDNSRecords(dnsRecords boshsettings.DNSRecords, hostname string) error {
dnsRecordsContents, err := p.generateDefaultEtcHosts(hostname)
if err != nil {
return bosherr.WrapError(err, "Generating default /etc/hosts")
}
for _, dnsRecord := range dnsRecords.Records {
dnsRecordsContents.WriteString(fmt.Sprintf("%s %s\n", dnsRecord[0], dnsRecord[1]))
}
uuid, err := p.uuidGenerator.Generate()
if err != nil {
return bosherr.WrapError(err, "Generating UUID")
}
etcHostsUUIDFileName := fmt.Sprintf("/etc/hosts-%s", uuid)
err = p.fs.WriteFileQuietly(etcHostsUUIDFileName, dnsRecordsContents.Bytes())
if err != nil {
return bosherr.WrapError(err, fmt.Sprintf("Writing to %s", etcHostsUUIDFileName))
}
err = p.fs.Rename(etcHostsUUIDFileName, "/etc/hosts")
if err != nil {
return bosherr.WrapError(err, fmt.Sprintf("Renaming %s to /etc/hosts", etcHostsUUIDFileName))
}
return nil
}
func (p linux) SetupIPv6(config boshsettings.IPv6) error {
return p.netManager.SetupIPv6(config, nil)
}
func (p linux) SetupHostname(hostname string) error {
if !p.state.Linux.HostsConfigured {
_, _, _, err := p.cmdRunner.RunCommand("hostname", hostname)
if err != nil {
return bosherr.WrapError(err, "Setting hostname")
}
err = p.fs.WriteFileString("/etc/hostname", hostname)
if err != nil {
return bosherr.WrapError(err, "Writing to /etc/hostname")
}
buffer, err := p.generateDefaultEtcHosts(hostname)
if err != nil {
return err
}
err = p.fs.WriteFile("/etc/hosts", buffer.Bytes())
if err != nil {
return bosherr.WrapError(err, "Writing to /etc/hosts")
}
p.state.Linux.HostsConfigured = true
err = p.state.SaveState()
if err != nil {
return bosherr.WrapError(err, "Setting up hostname")
}
}
return nil
}
func (p linux) SetupLogrotate(groupName, basePath, size string) (err error) {
buffer := bytes.NewBuffer([]byte{})
t := template.Must(template.New("logrotate-d-config").Parse(etcLogrotateDTemplate))
type logrotateArgs struct {
BasePath string
Size string
}
err = t.Execute(buffer, logrotateArgs{basePath, size})
if err != nil {
err = bosherr.WrapError(err, "Generating logrotate config")
return
}
err = p.fs.WriteFile(path.Join("/etc/logrotate.d", groupName), buffer.Bytes())
if err != nil {
err = bosherr.WrapError(err, "Writing to /etc/logrotate.d")
return
}
return
}
// Logrotate config file - /etc/logrotate.d/<group-name>
// Stemcell stage logrotate_config configures logrotate to run every hour
const etcLogrotateDTemplate = `# Generated by bosh-agent
{{ .BasePath }}/data/sys/log/*.log {{ .BasePath }}/data/sys/log/.*.log {{ .BasePath }}/data/sys/log/*/*.log {{ .BasePath }}/data/sys/log/*/.*.log {{ .BasePath }}/data/sys/log/*/*/*.log {{ .BasePath }}/data/sys/log/*/*/.*.log {
missingok
rotate 7
compress
copytruncate
size={{ .Size }}
}
`
func (p linux) SetTimeWithNtpServers(servers []string) (err error) {
serversFilePath := path.Join(p.dirProvider.BaseDir(), "/bosh/etc/ntpserver")
if len(servers) == 0 {
return
}
err = p.fs.WriteFileString(serversFilePath, strings.Join(servers, " "))
if err != nil {
err = bosherr.WrapErrorf(err, "Writing to %s", serversFilePath)
return
}
// Make a best effort to sync time now but don't error
_, _, _, _ = p.cmdRunner.RunCommand("sync-time")
return
}
func (p linux) SetupEphemeralDiskWithPath(realPath string, desiredSwapSizeInBytes *uint64) error {
p.logger.Info(logTag, "Setting up ephemeral disk...")
mountPoint := p.dirProvider.DataDir()
mountPointGlob := path.Join(mountPoint, "*")
contents, err := p.fs.Glob(mountPointGlob)
if err != nil {
return bosherr.WrapErrorf(err, "Globbing ephemeral disk mount point `%s'", mountPointGlob)
}
if contents != nil && len(contents) > 0 {
// When agent bootstraps for the first time data directory should be empty.
// It might be non-empty on subsequent agent restarts. The ephemeral disk setup
// should be idempotent and partitioning will be skipped if disk is already
// partitioned as needed. If disk is not partitioned as needed we still want to
// partition it even if data directory is not empty.
p.logger.Debug(logTag, "Existing ephemeral mount `%s' is not empty. Contents: %s", mountPoint, contents)
}
err = p.fs.MkdirAll(mountPoint, ephemeralDiskPermissions)
if err != nil {
return bosherr.WrapError(err, "Creating data dir")
}
if p.options.SkipDiskSetup {
return nil
}
var swapPartitionPath, dataPartitionPath string
// Agent can only setup ephemeral data directory either on ephemeral device
// or on separate root partition.
// The real path can be empty if CPI did not provide ephemeral disk
// or if the provided disk was not found.
if realPath == "" {
if !p.options.CreatePartitionIfNoEphemeralDisk {
// Agent can not use root partition for ephemeral data directory.
return bosherr.Error("No ephemeral disk found, cannot use root partition as ephemeral disk")
}
swapPartitionPath, dataPartitionPath, err = p.createEphemeralPartitionsOnRootDevice(desiredSwapSizeInBytes)
if err != nil {
return bosherr.WrapError(err, "Creating ephemeral partitions on root device")
}
} else {
swapPartitionPath, dataPartitionPath, err = p.partitionEphemeralDisk(realPath, desiredSwapSizeInBytes)
if err != nil {
return bosherr.WrapError(err, "Partitioning ephemeral disk")
}
}
if len(swapPartitionPath) > 0 {
p.logger.Info(logTag, "Formatting `%s' as swap", swapPartitionPath)
err = p.diskManager.GetFormatter().Format(swapPartitionPath, boshdisk.FileSystemSwap)
if err != nil {
return bosherr.WrapError(err, "Formatting swap")
}
}
p.logger.Info(logTag, "Formatting `%s' as ext4", dataPartitionPath)
err = p.diskManager.GetFormatter().Format(dataPartitionPath, boshdisk.FileSystemExt4)
if err != nil {
return bosherr.WrapError(err, "Formatting data partition with ext4")
}
if len(swapPartitionPath) > 0 {
p.logger.Info(logTag, "Mounting `%s' as swap", swapPartitionPath)
err = p.diskManager.GetMounter().SwapOn(swapPartitionPath)
if err != nil {
return bosherr.WrapError(err, "Mounting swap")
}
}
p.logger.Info(logTag, "Mounting `%s' at `%s'", dataPartitionPath, mountPoint)
err = p.diskManager.GetMounter().Mount(dataPartitionPath, mountPoint)
if err != nil {
return bosherr.WrapError(err, "Mounting data partition")
}
if p.options.ScrubEphemeralDisk {
contents, err := p.fs.Glob(mountPointGlob)
if err != nil {
return bosherr.WrapErrorf(err, "Globbing ephemeral disk mount point '%s'", mountPointGlob)
}
err = p.scrubEphemeralDisk(contents)
if err != nil {
return bosherr.WrapError(err, "Scrubbing ephemeral disk")
}
}
return nil
}
func (p linux) SetupRawEphemeralDisks(devices []boshsettings.DiskSettings) (err error) {
if p.options.SkipDiskSetup {
return nil
}
p.logger.Info(logTag, "Setting up raw ephemeral disks")
for i, device := range devices {
realPath, _, err := p.devicePathResolver.GetRealDevicePath(device)
if err != nil {
return bosherr.WrapError(err, "Getting real device path")
}
// check if device is already partitioned correctly
stdout, stderr, _, err := p.cmdRunner.RunCommand(
"parted",
"-s",
realPath,
"p",
)
if err != nil {
// "unrecognised disk label" is acceptable, since the disk may not have been partitioned
if strings.Contains(stdout, "unrecognised disk label") == false &&
strings.Contains(stderr, "unrecognised disk label") == false {
return bosherr.WrapError(err, "Setting up raw ephemeral disks")
}
}
if strings.Contains(stdout, "Partition Table: gpt") && strings.Contains(stdout, "raw-ephemeral-") {
continue
}
// change to gpt partition type, change units to percentage, make partition with name and span from 0-100%
p.logger.Info(logTag, "Creating partition on `%s'", realPath)
_, _, _, err = p.cmdRunner.RunCommand(
"parted",
"-s",
realPath,
"mklabel",
"gpt",
"unit",
"%",
"mkpart",
fmt.Sprintf("raw-ephemeral-%d", i),
"0",
"100",
)
if err != nil {
return bosherr.WrapError(err, "Setting up raw ephemeral disks")
}
}
return nil
}
func (p linux) scrubEphemeralDisk(contents []string) error {
agentVersionFilePath := path.Join(p.dirProvider.DataDir(), ".bosh", "agent_version")
stemcellVersionFilePath := path.Join(p.dirProvider.EtcDir(), "stemcell_version")
stemcellVersion, err := p.fs.ReadFileString(stemcellVersionFilePath)
if err != nil {
return bosherr.WrapError(err, "Reading stemcell version file")
}
if !p.fs.FileExists(agentVersionFilePath) {
// need to remove contents when it is upgrading from a stemcell without scrubEphemeralDisk enabled
for _, content := range contents {
err = p.fs.RemoveAll(content)
if err != nil {
return bosherr.WrapErrorf(err, "Removing '%s'", content)
}
}
err = p.fs.WriteFileString(agentVersionFilePath, stemcellVersion)
if err != nil {
return bosherr.WrapError(err, "Writting agent version file")
}
} else {
agentVersion, err := p.fs.ReadFileString(agentVersionFilePath)
if err != nil {
return bosherr.WrapError(err, "Reading agent version file")
}
if agentVersion != stemcellVersion {
for _, content := range contents {
err = p.fs.RemoveAll(content)
if err != nil {
return bosherr.WrapErrorf(err, "Removing '%s'", content)
}
}
err = p.fs.WriteFileString(agentVersionFilePath, stemcellVersion)
if err != nil {
return bosherr.WrapErrorf(err, "Updating agent version file '%s'", agentVersionFilePath)
}
}
}
return nil
}
func (p linux) SetupDataDir() error {
dataDir := p.dirProvider.DataDir()
sysDataDir := path.Join(dataDir, "sys")
logDir := path.Join(sysDataDir, "log")
err := p.fs.MkdirAll(logDir, logDirPermissions)
if err != nil {
return bosherr.WrapErrorf(err, "Making %s dir", logDir)
}
_, _, _, err = p.cmdRunner.RunCommand("chown", "root:vcap", sysDataDir)
if err != nil {
return bosherr.WrapErrorf(err, "chown %s", sysDataDir)
}
_, _, _, err = p.cmdRunner.RunCommand("chown", "root:vcap", logDir)
if err != nil {
return bosherr.WrapErrorf(err, "chown %s", logDir)
}
jobsDir := p.dirProvider.DataJobsDir()
err = p.fs.MkdirAll(jobsDir, jobsDirPermissions)
if err != nil {
return bosherr.WrapErrorf(err, "Making %s dir", jobsDir)
}
_, _, _, err = p.cmdRunner.RunCommand("chown", "root:vcap", jobsDir)
if err != nil {
return bosherr.WrapErrorf(err, "chown %s", jobsDir)
}
packagesDir := p.dirProvider.PkgDir()
err = p.fs.MkdirAll(packagesDir, packagesDirPermissions)
if err != nil {
return bosherr.WrapErrorf(err, "Making %s dir", packagesDir)
}
_, _, _, err = p.cmdRunner.RunCommand("chown", "root:vcap", packagesDir)
if err != nil {
return bosherr.WrapErrorf(err, "chown %s", packagesDir)
}
err = p.setupRunDir(sysDataDir)
if err != nil {
return err
}
sysDir := path.Join(path.Dir(dataDir), "sys")
err = p.fs.Symlink(sysDataDir, sysDir)
if err != nil {
return bosherr.WrapErrorf(err, "Symlinking '%s' to '%s'", sysDir, sysDataDir)
}
return nil
}
func (p linux) setupRunDir(sysDir string) error {
runDir := path.Join(sysDir, "run")
_, runDirIsMounted, err := p.IsMountPoint(runDir)
if err != nil {
return bosherr.WrapErrorf(err, "Checking for mount point %s", runDir)
}
if !runDirIsMounted {
err = p.fs.MkdirAll(runDir, runDirPermissions)
if err != nil {
return bosherr.WrapErrorf(err, "Making %s dir", runDir)
}
err = p.diskManager.GetMounter().MountFilesystem("tmpfs", runDir, "tmpfs", "size=1m")
if err != nil {
return bosherr.WrapErrorf(err, "Mounting tmpfs to %s", runDir)
}
_, _, _, err = p.cmdRunner.RunCommand("chown", "root:vcap", runDir)
if err != nil {
return bosherr.WrapErrorf(err, "chown %s", runDir)
}
}
return nil
}
func (p linux) SetupHomeDir() error {
mounter := boshdisk.NewLinuxBindMounter(p.diskManager.GetMounter())
isMounted, err := mounter.IsMounted("/home")
if err != nil {
return bosherr.WrapError(err, "Setup home dir, checking if mounted")
}
if !isMounted {
err := mounter.Mount("/home", "/home")
if err != nil {
return bosherr.WrapError(err, "Setup home dir, mounting home")
}
err = mounter.RemountInPlace("/home", "nodev")
if err != nil {
return bosherr.WrapError(err, "Setup home dir, remount in place")
}
}
return nil
}
func (p linux) SetupBlobsDir() error {
blobsDirPath := p.dirProvider.BlobsDir()
err := p.fs.MkdirAll(blobsDirPath, blobsDirPermissions)
if err != nil {
return bosherr.WrapError(err, "Creating blobs dir")
}
_, _, _, err = p.cmdRunner.RunCommand("chown", "root:vcap", blobsDirPath)
if err != nil {
return bosherr.WrapErrorf(err, "chown %s", blobsDirPath)
}
return nil
}
func (p linux) SetupTmpDir() error {
systemTmpDir := "/tmp"
boshTmpDir := p.dirProvider.TmpDir()
boshRootTmpPath := path.Join(p.dirProvider.DataDir(), "root_tmp")
err := p.fs.MkdirAll(boshTmpDir, tmpDirPermissions)
if err != nil {
return bosherr.WrapError(err, "Creating temp dir")
}
err = os.Setenv("TMPDIR", boshTmpDir)
if err != nil {
return bosherr.WrapError(err, "Setting TMPDIR")
}
err = p.changeTmpDirPermissions(systemTmpDir)
if err != nil {
return err
}
// /var/tmp is used for preserving temporary files between system reboots
varTmpDir := "/var/tmp"
err = p.changeTmpDirPermissions(varTmpDir)
if err != nil {
return err
}
if p.options.UseDefaultTmpDir {
return nil
}
_, _, _, err = p.cmdRunner.RunCommand("mkdir", "-p", boshRootTmpPath)
if err != nil {
return bosherr.WrapError(err, "Creating root tmp dir")
}
// change permissions
err = p.changeTmpDirPermissions(boshRootTmpPath)
if err != nil {
return bosherr.WrapError(err, "Chmoding root tmp dir")
}
err = p.bindMountDir(boshRootTmpPath, systemTmpDir)
if err != nil {
return err
}
err = p.bindMountDir(boshRootTmpPath, varTmpDir)
if err != nil {
return err
}
return nil
}
func (p linux) SetupLogDir() error {
logDir := "/var/log"
boshRootLogPath := path.Join(p.dirProvider.DataDir(), "root_log")
err := p.fs.MkdirAll(boshRootLogPath, userRootLogDirPermissions)
if err != nil {
return bosherr.WrapError(err, "Creating root log dir")
}
_, _, _, err = p.cmdRunner.RunCommand("chmod", "0770", boshRootLogPath)
if err != nil {
return bosherr.WrapError(err, "Chmoding /var/log dir")
}
auditDirPath := path.Join(boshRootLogPath, "audit")
_, _, _, err = p.cmdRunner.RunCommand("mkdir", "-p", auditDirPath)
if err != nil {
return bosherr.WrapError(err, "Creating audit log dir")
}
_, _, _, err = p.cmdRunner.RunCommand("chmod", "0750", auditDirPath)
if err != nil {
return bosherr.WrapError(err, "Chmoding audit log dir")
}
sysstatDirPath := path.Join(boshRootLogPath, "sysstat")
_, _, _, err = p.cmdRunner.RunCommand("mkdir", "-p", sysstatDirPath)
if err != nil {
return bosherr.WrapError(err, "Creating sysstat log dir")
}
_, _, _, err = p.cmdRunner.RunCommand("chmod", "0755", sysstatDirPath)
if err != nil {
return bosherr.WrapError(err, "Chmoding sysstat log dir")
}
// change ownership
_, _, _, err = p.cmdRunner.RunCommand("chown", "root:syslog", boshRootLogPath)
if err != nil {
return bosherr.WrapError(err, "Chowning root log dir")
}
err = p.ensureFile(fmt.Sprintf("%s/btmp", boshRootLogPath), "root:utmp", "0600")
if err != nil {
return err
}
err = p.ensureFile(fmt.Sprintf("%s/wtmp", boshRootLogPath), "root:utmp", "0664")
if err != nil {
return err
}
err = p.bindMountDir(boshRootLogPath, logDir)
if err != nil {
return err
}
return nil
}
func (p linux) ensureFile(path, owner, mode string) error {
_, _, _, err := p.cmdRunner.RunCommand("touch", path)
if err != nil {
return bosherr.WrapError(err, fmt.Sprintf("Touching '%s' file", path))
}
_, _, _, err = p.cmdRunner.RunCommand("chown", owner, path)
if err != nil {
return bosherr.WrapError(err, fmt.Sprintf("Chowning '%s' file", path))
}