forked from siderolabs/talos
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathv1alpha1_sequencer_tasks.go
More file actions
1971 lines (1564 loc) · 58.3 KB
/
Copy pathv1alpha1_sequencer_tasks.go
File metadata and controls
1971 lines (1564 loc) · 58.3 KB
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
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
package v1alpha1
import (
"bufio"
"bytes"
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io/fs"
"log"
"os"
"path/filepath"
"strconv"
"strings"
"syscall"
"time"
"github.com/cosi-project/runtime/pkg/resource"
"github.com/cosi-project/runtime/pkg/safe"
"github.com/cosi-project/runtime/pkg/state"
"github.com/dustin/go-humanize"
"github.com/foxboron/go-uefi/efi"
"github.com/hashicorp/go-multierror"
pprocfs "github.com/prometheus/procfs"
"github.com/siderolabs/gen/xslices"
"github.com/siderolabs/go-blockdevice/v2/block"
"github.com/siderolabs/go-cmd/pkg/cmd"
"github.com/siderolabs/go-cmd/pkg/cmd/proc"
"github.com/siderolabs/go-pointer"
"github.com/siderolabs/go-procfs/procfs"
clientv3 "go.etcd.io/etcd/client/v3"
"golang.org/x/sys/unix"
runtimeapi "k8s.io/cri-api/pkg/apis/runtime/v1"
"github.com/siderolabs/talos/internal/app/machined/pkg/runtime"
"github.com/siderolabs/talos/internal/app/machined/pkg/runtime/emergency"
"github.com/siderolabs/talos/internal/app/machined/pkg/runtime/v1alpha1/bootloader"
"github.com/siderolabs/talos/internal/app/machined/pkg/runtime/v1alpha1/bootloader/options"
"github.com/siderolabs/talos/internal/app/machined/pkg/runtime/v1alpha1/bootloader/sdboot"
"github.com/siderolabs/talos/internal/app/machined/pkg/runtime/v1alpha1/platform"
"github.com/siderolabs/talos/internal/app/machined/pkg/system"
"github.com/siderolabs/talos/internal/app/machined/pkg/system/events"
"github.com/siderolabs/talos/internal/app/machined/pkg/system/services"
"github.com/siderolabs/talos/internal/pkg/cri"
"github.com/siderolabs/talos/internal/pkg/environment"
"github.com/siderolabs/talos/internal/pkg/etcd"
"github.com/siderolabs/talos/internal/pkg/install"
"github.com/siderolabs/talos/internal/pkg/logind"
mountv3 "github.com/siderolabs/talos/internal/pkg/mount/v3"
"github.com/siderolabs/talos/internal/pkg/partition"
"github.com/siderolabs/talos/internal/pkg/selinux"
"github.com/siderolabs/talos/pkg/conditions"
"github.com/siderolabs/talos/pkg/images"
"github.com/siderolabs/talos/pkg/kernel/kspp"
"github.com/siderolabs/talos/pkg/kubernetes"
machineapi "github.com/siderolabs/talos/pkg/machinery/api/machine"
"github.com/siderolabs/talos/pkg/machinery/config/machine"
"github.com/siderolabs/talos/pkg/machinery/config/types/block/blockhelpers"
"github.com/siderolabs/talos/pkg/machinery/constants"
metamachinery "github.com/siderolabs/talos/pkg/machinery/meta"
blockres "github.com/siderolabs/talos/pkg/machinery/resources/block"
crires "github.com/siderolabs/talos/pkg/machinery/resources/cri"
resourcefiles "github.com/siderolabs/talos/pkg/machinery/resources/files"
"github.com/siderolabs/talos/pkg/machinery/resources/k8s"
resourceruntime "github.com/siderolabs/talos/pkg/machinery/resources/runtime"
resourcev1alpha1 "github.com/siderolabs/talos/pkg/machinery/resources/v1alpha1"
"github.com/siderolabs/talos/pkg/minimal"
)
// WaitForUSB represents the WaitForUSB task.
func WaitForUSB(runtime.Sequence, any) (runtime.TaskExecutionFunc, string) {
return func(ctx context.Context, logger *log.Logger, r runtime.Runtime) error {
// Wait for USB storage in the case that the install disk is supplied over
// USB. If we don't wait, there is the chance that we will fail to detect the
// install disk.
file := "/sys/module/usb_storage/parameters/delay_use"
_, err := os.Stat(file)
if err != nil {
if errors.Is(err, fs.ErrNotExist) {
return nil
}
return err
}
b, err := os.ReadFile(file)
if err != nil {
return err
}
val := strings.TrimSuffix(string(b), "\n")
var i int
i, err = strconv.Atoi(val)
if err != nil {
return err
}
logger.Printf("waiting %d second(s) for USB storage", i)
time.Sleep(time.Duration(i) * time.Second)
return nil
}, "waitForUSB"
}
// EnforceKSPPRequirements represents the EnforceKSPPRequirements task.
func EnforceKSPPRequirements(runtime.Sequence, any) (runtime.TaskExecutionFunc, string) {
return func(ctx context.Context, logger *log.Logger, r runtime.Runtime) (err error) {
if err = resourceruntime.NewKernelParamsSetCondition(r.State().V1Alpha2().Resources(), kspp.GetKernelParams()...).Wait(ctx); err != nil {
return err
}
return kspp.EnforceKSPPKernelParameters()
}, "enforceKSPPRequirements"
}
// LoadConfig represents the LoadConfig task.
func LoadConfig(runtime.Sequence, any) (runtime.TaskExecutionFunc, string) {
return func(ctx context.Context, logger *log.Logger, r runtime.Runtime) error {
// create a request to initialize the process acquisition process
request := resourcev1alpha1.NewAcquireConfigSpec()
if err := r.State().V1Alpha2().Resources().Create(ctx, request); err != nil {
return fmt.Errorf("failed to create config request: %w", err)
}
// wait for the config to be acquired
status := resourcev1alpha1.NewAcquireConfigStatus()
if _, err := r.State().V1Alpha2().Resources().WatchFor(ctx, status.Metadata(), state.WithEventTypes(state.Created)); err != nil {
return err
}
// clean up request to make sure controller doesn't work after this point
return r.State().V1Alpha2().Resources().Destroy(ctx, request.Metadata())
}, "loadConfig"
}
// Sleep represents the Sleep task.
func Sleep(d time.Duration) func(runtime.Sequence, any) (runtime.TaskExecutionFunc, string) {
return func(_ runtime.Sequence, _ any) (runtime.TaskExecutionFunc, string) {
return func(ctx context.Context, logger *log.Logger, r runtime.Runtime) error {
select {
case <-time.After(d):
case <-ctx.Done():
return ctx.Err()
}
return nil
}, "sleep"
}
}
// MemorySizeCheck represents the MemorySizeCheck task.
func MemorySizeCheck(runtime.Sequence, any) (runtime.TaskExecutionFunc, string) {
return func(ctx context.Context, logger *log.Logger, r runtime.Runtime) error {
if r.State().Platform().Mode() == runtime.ModeContainer {
logger.Println("skipping memory size check in the container")
return nil
}
pc, err := pprocfs.NewDefaultFS()
if err != nil {
return fmt.Errorf("failed to open procfs: %w", err)
}
info, err := pc.Meminfo()
if err != nil {
return fmt.Errorf("failed to read meminfo: %w", err)
}
minimum, recommended, err := minimal.Memory(r.Config().Machine().Type())
if err != nil {
return err
}
switch memTotal := pointer.SafeDeref(info.MemTotal) * humanize.KiByte; {
case memTotal < minimum:
logger.Println("WARNING: memory size is less than recommended")
logger.Println("WARNING: Talos may not work properly")
logger.Println("WARNING: minimum memory size is", minimum/humanize.MiByte, "MiB")
logger.Println("WARNING: recommended memory size is", recommended/humanize.MiByte, "MiB")
logger.Println("WARNING: current total memory size is", memTotal/humanize.MiByte, "MiB")
case memTotal < recommended:
logger.Println("NOTE: recommended memory size is", recommended/humanize.MiByte, "MiB")
logger.Println("NOTE: current total memory size is", memTotal/humanize.MiByte, "MiB")
default:
logger.Println("memory size is OK")
logger.Println("memory size is", memTotal/humanize.MiByte, "MiB")
}
return nil
}, "memorySizeCheck"
}
// DiskSizeCheck represents the DiskSizeCheck task.
func DiskSizeCheck(runtime.Sequence, any) (runtime.TaskExecutionFunc, string) {
return func(ctx context.Context, logger *log.Logger, r runtime.Runtime) error {
if r.State().Platform().Mode() == runtime.ModeContainer {
logger.Println("skipping disk size check in the container")
return nil
}
volumeStatus, err := r.State().V1Alpha2().Resources().WatchFor(
ctx,
blockres.NewVolumeStatus(blockres.NamespaceName, constants.EphemeralPartitionLabel).Metadata(),
state.WithCondition(func(r resource.Resource) (bool, error) {
volumeStatus, ok := r.(*blockres.VolumeStatus)
if !ok {
return false, nil
}
return volumeStatus.TypedSpec().Size > 0, nil
}),
)
if err != nil {
return fmt.Errorf("error waiting for volume %q to be discovered: %w", constants.EphemeralPartitionLabel, err)
}
diskSize := volumeStatus.(*blockres.VolumeStatus).TypedSpec().Size
if minimum := minimal.DiskSize(); diskSize < minimum {
logger.Println("WARNING: disk size is less than recommended")
logger.Println("WARNING: Talos may not work properly")
logger.Println("WARNING: minimum recommended disk size is", minimum/humanize.MiByte, "MiB")
logger.Println("WARNING: current total disk size is", diskSize/humanize.MiByte, "MiB")
} else {
logger.Println("disk size is OK")
logger.Println("disk size is", diskSize/humanize.MiByte, "MiB")
}
return nil
}, "diskSizeCheck"
}
// SetUserEnvVars represents the SetUserEnvVars task.
func SetUserEnvVars(runtime.Sequence, any) (runtime.TaskExecutionFunc, string) {
return func(ctx context.Context, logger *log.Logger, r runtime.Runtime) (err error) {
for _, env := range environment.Get(r.Config()) {
key, val, _ := strings.Cut(env, "=")
if err = os.Setenv(key, val); err != nil {
return fmt.Errorf("failed to set enivronment variable: %w", err)
}
}
return nil
}, "setUserEnvVars"
}
// StartContainerd represents the task to start containerd.
func StartContainerd(runtime.Sequence, any) (runtime.TaskExecutionFunc, string) {
return func(ctx context.Context, logger *log.Logger, r runtime.Runtime) (err error) {
svc := &services.Containerd{}
system.Services(r).LoadAndStart(svc)
ctx, cancel := context.WithTimeout(ctx, 5*time.Minute)
defer cancel()
return system.WaitForService(system.StateEventUp, svc.ID(r)).Wait(ctx)
}, "startContainerd"
}
// WriteUdevRules is the task that writes udev rules to a udev rules file.
// TODO: frezbo: move this to controller based since writing udev rules doesn't need a restart.
func WriteUdevRules(runtime.Sequence, any) (runtime.TaskExecutionFunc, string) {
return func(ctx context.Context, logger *log.Logger, r runtime.Runtime) (err error) {
rules := r.Config().Machine().Udev().Rules()
var content strings.Builder
for _, rule := range rules {
content.WriteString(strings.ReplaceAll(rule, "\n", "\\\n"))
content.WriteByte('\n')
}
if err = os.WriteFile(constants.UdevRulesPath, []byte(content.String()), 0o644); err != nil {
return fmt.Errorf("failed writing custom udev rules: %w", err)
}
if err = selinux.SetLabel(constants.UdevRulesPath, constants.UdevRulesLabel); err != nil {
return fmt.Errorf("failed labeling custom udev rules: %w", err)
}
if len(rules) > 0 {
if _, err := cmd.RunWithOptions(ctx, "/sbin/udevadm", []string{"control", "--reload"}); err != nil {
return err
}
if _, err := cmd.RunWithOptions(ctx, "/sbin/udevadm", []string{"trigger", "--type=devices", "--action=add"}); err != nil {
return err
}
if _, err := cmd.RunWithOptions(ctx, "/sbin/udevadm", []string{"trigger", "--type=subsystems", "--action=add"}); err != nil {
return err
}
// This ensures that `udevd` finishes processing kernel events, triggered by
// `udevd trigger`, to prevent a race condition when a user specifies a path
// under `/dev/disk/*` in any disk definitions.
_, err := cmd.RunWithOptions(ctx, "/sbin/udevadm", []string{"settle", "--timeout=50"})
return err
}
return nil
}, "writeUdevRules"
}
// StartMachined represents the task to start machined.
func StartMachined(_ runtime.Sequence, _ any) (runtime.TaskExecutionFunc, string) {
return func(ctx context.Context, logger *log.Logger, r runtime.Runtime) error {
svc := &services.Machined{}
id := svc.ID(r)
err := system.Services(r).Start(id)
if err != nil {
return fmt.Errorf("failed to start machined service: %w", err)
}
ctx, cancel := context.WithTimeout(ctx, 5*time.Minute)
defer cancel()
return system.WaitForService(system.StateEventUp, id).Wait(ctx)
}, "startMachined"
}
// StartSyslogd represents the task to start syslogd.
func StartSyslogd(r runtime.Sequence, _ any) (runtime.TaskExecutionFunc, string) {
return func(_ context.Context, _ *log.Logger, r runtime.Runtime) error {
system.Services(r).LoadAndStart(&services.Syslogd{})
return nil
}, "startSyslogd"
}
// StartApid represents the task to start apid.
func StartApid(r runtime.Sequence, _ any) (runtime.TaskExecutionFunc, string) {
return func(_ context.Context, _ *log.Logger, r runtime.Runtime) error {
system.Services(r).LoadAndStart(&services.APID{})
return nil
}, "startApid"
}
// StartAuditd represents the task to start auditd.
func StartAuditd(r runtime.Sequence, _ any) (runtime.TaskExecutionFunc, string) {
return func(_ context.Context, logger *log.Logger, r runtime.Runtime) error {
if !r.State().Platform().Mode().InContainer() {
disabledStr := procfs.ProcCmdline().Get(constants.KernelParamAuditdDisabled).First()
disabled, _ := strconv.ParseBool(pointer.SafeDeref(disabledStr)) //nolint:errcheck
if disabled {
logger.Printf("auditd is disabled by kernel parameter %s", constants.KernelParamAuditdDisabled)
return nil
}
}
system.Services(r).LoadAndStart(&services.Auditd{})
return nil
}, "startAuditd"
}
// StartDashboard represents the task to start dashboard.
func StartDashboard(_ runtime.Sequence, _ any) (runtime.TaskExecutionFunc, string) {
return func(_ context.Context, _ *log.Logger, r runtime.Runtime) error {
system.Services(r).LoadAndStart(&services.Dashboard{})
return nil
}, "startDashboard"
}
// StartUdevd represents the task to start udevd.
func StartUdevd(runtime.Sequence, any) (runtime.TaskExecutionFunc, string) {
return func(ctx context.Context, logger *log.Logger, r runtime.Runtime) (err error) {
mp := mountv3.NewSystemOverlay(
[]string{constants.UdevDir},
constants.UdevDir,
logger.Printf,
mountv3.WithShared(),
mountv3.WithSelinuxLabel(constants.UdevRulesLabel),
)
if _, err = mp.Mount(); err != nil {
return err
}
var extraSettleTime time.Duration
settleTimeStr := procfs.ProcCmdline().Get(constants.KernelParamDeviceSettleTime).First()
if settleTimeStr != nil {
extraSettleTime, err = time.ParseDuration(*settleTimeStr)
if err != nil {
return fmt.Errorf("failed to parse %s: %w", constants.KernelParamDeviceSettleTime, err)
}
logger.Printf("extra settle time: %s", extraSettleTime)
}
svc := &services.Udevd{
ExtraSettleTime: extraSettleTime,
}
system.Services(r).LoadAndStart(svc)
ctx, cancel := context.WithTimeout(ctx, 10*time.Minute)
defer cancel()
return system.WaitForService(system.StateEventUp, svc.ID(r)).Wait(ctx)
}, "startUdevd"
}
// StartAllServices represents the task to start the system services.
func StartAllServices(runtime.Sequence, any) (runtime.TaskExecutionFunc, string) {
return func(ctx context.Context, logger *log.Logger, r runtime.Runtime) (err error) {
// nb: Treating the beginning of "service starts" as the activate event for a normal
// non-maintenance mode boot. At this point, we'd expect the user to
// start interacting with the system for troubleshooting at least.
platform.FireEvent(
ctx,
r.State().Platform(),
platform.Event{
Type: platform.EventTypeActivate,
Message: "Talos is ready for user interaction.",
},
)
svcs := system.Services(r)
// load the kubelet service, but don't start it;
// KubeletServiceController will start it once it's ready.
svcs.Load(
&services.Kubelet{},
)
serviceList := []system.Service{
&services.CRI{},
}
switch t := r.Config().Machine().Type(); t {
case machine.TypeInit:
serviceList = append(
serviceList,
&services.Trustd{},
&services.Etcd{Bootstrap: true},
)
case machine.TypeControlPlane:
serviceList = append(
serviceList,
&services.Trustd{},
&services.Etcd{},
)
case machine.TypeWorker:
// nothing
case machine.TypeUnknown:
fallthrough
default:
panic(fmt.Sprintf("unexpected machine type %v", t))
}
svcs.LoadAndStart(serviceList...)
all := make([]conditions.Condition, 0, len(svcs.List()))
logger.Printf("waiting for %d services", len(svcs.List()))
for _, svc := range svcs.List() {
cond := system.WaitForService(system.StateEventUp, svc.AsProto().GetId())
all = append(all, cond)
}
ctx, cancel := context.WithTimeout(ctx, constants.BootTimeout)
defer cancel()
aggregateCondition := conditions.WaitForAll(all...)
errChan := make(chan error)
go func() {
errChan <- aggregateCondition.Wait(ctx)
}()
ticker := time.NewTicker(15 * time.Second)
defer ticker.Stop()
for {
logger.Printf("%s", aggregateCondition.String())
select {
case err := <-errChan:
return err
case <-ticker.C:
}
}
}, "startAllServices"
}
// StopServicesEphemeral represents the StopServicesEphemeral task.
func StopServicesEphemeral(runtime.Sequence, any) (runtime.TaskExecutionFunc, string) {
return func(ctx context.Context, logger *log.Logger, r runtime.Runtime) (err error) {
// stopping 'cri' service stops everything which depends on it (kubelet, etcd, ...)
return system.Services(nil).StopWithRevDepenencies(ctx, "cri", "trustd")
}, "stopServicesForUpgrade"
}
// StopAllServices represents the StopAllServices task.
func StopAllServices(runtime.Sequence, any) (runtime.TaskExecutionFunc, string) {
return func(ctx context.Context, logger *log.Logger, r runtime.Runtime) (err error) {
system.Services(nil).Shutdown(ctx)
return nil
}, "stopAllServices"
}
// SetupSharedFilesystems represents the SetupSharedFilesystems task.
func SetupSharedFilesystems(runtime.Sequence, any) (runtime.TaskExecutionFunc, string) {
return func(ctx context.Context, logger *log.Logger, r runtime.Runtime) (err error) {
targets := []string{"/", "/var", "/etc/cni", "/run"}
for _, t := range targets {
if err = unix.Mount("", t, "", unix.MS_SHARED|unix.MS_REC, ""); err != nil {
return err
}
}
return nil
}, "setupSharedFilesystems"
}
// MountUserDisks represents the MountUserDisks task.
func MountUserDisks(runtime.Sequence, any) (runtime.TaskExecutionFunc, string) {
return func(ctx context.Context, logger *log.Logger, r runtime.Runtime) error {
// wait for user disk config to be ready
_, err := r.State().V1Alpha2().Resources().WatchFor(
ctx,
blockres.NewUserDiskConfigStatus(blockres.NamespaceName, blockres.UserDiskConfigStatusID).Metadata(),
state.WithEventTypes(state.Created, state.Updated),
state.WithCondition(func(r resource.Resource) (bool, error) {
return r.(*blockres.UserDiskConfigStatus).TypedSpec().Ready, nil
}),
)
return err
}, "mountUserDisks"
}
// WriteUserFiles represents the WriteUserFiles task.
//
//nolint:gocyclo,cyclop
func WriteUserFiles(runtime.Sequence, any) (runtime.TaskExecutionFunc, string) {
return func(ctx context.Context, logger *log.Logger, r runtime.Runtime) (err error) {
var result *multierror.Error
files, err := r.Config().Machine().Files()
if err != nil {
return fmt.Errorf("error generating extra files: %w", err)
}
for _, f := range files {
content := f.Content()
switch f.Op() {
case "create":
// Allow create at all times.
case "overwrite":
if err = existsAndIsFile(f.Path()); err != nil {
result = multierror.Append(result, err)
continue
}
case "append":
if err = existsAndIsFile(f.Path()); err != nil {
result = multierror.Append(result, err)
continue
}
var existingFileContents []byte
existingFileContents, err = os.ReadFile(f.Path())
if err != nil {
result = multierror.Append(result, err)
continue
}
content = string(existingFileContents) + "\n" + f.Content()
default:
result = multierror.Append(result, fmt.Errorf("unknown operation for file %q: %q", f.Path(), f.Op()))
continue
}
if filepath.Dir(f.Path()) == constants.ManifestsDirectory {
if err = os.WriteFile(f.Path(), []byte(content), f.Permissions()); err != nil {
result = multierror.Append(result, err)
continue
}
if err = os.Chmod(f.Path(), f.Permissions()); err != nil {
result = multierror.Append(result, err)
continue
}
continue
}
// CRI configuration customization
if f.Path() == filepath.Join("/etc", constants.CRICustomizationConfigPart) {
if err = injectCRIConfigPatch(ctx, r.State().V1Alpha2().Resources(), []byte(f.Content())); err != nil {
result = multierror.Append(result, err)
}
continue
}
// Determine if supplied path is in /var or not.
// If not, we'll write it to /var anyways and bind mount below
p := f.Path()
inVar := true
parts := strings.Split(
strings.TrimLeft(f.Path(), "/"),
string(os.PathSeparator),
)
if parts[0] != "var" {
p = filepath.Join("/var", f.Path())
inVar = false
}
// We do not want to support creating new files anywhere outside of
// /var. If a valid use case comes up, we can reconsider then.
if !inVar && f.Op() == "create" {
return fmt.Errorf("create operation not allowed outside of /var: %q", f.Path())
}
if err = os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
result = multierror.Append(result, err)
continue
}
if err = os.WriteFile(p, []byte(content), f.Permissions()); err != nil {
result = multierror.Append(result, err)
continue
}
if err = os.Chmod(p, f.Permissions()); err != nil {
result = multierror.Append(result, err)
continue
}
if !inVar {
if err = unix.Mount(p, f.Path(), "", unix.MS_BIND|unix.MS_RDONLY, ""); err != nil {
result = multierror.Append(result, fmt.Errorf("failed to create bind mount for %s: %w", p, err))
}
}
}
return result.ErrorOrNil()
}, "writeUserFiles"
}
func injectCRIConfigPatch(ctx context.Context, st state.State, content []byte) error {
// limit overall waiting time
ctx, cancel := context.WithTimeout(ctx, time.Minute)
defer cancel()
etcFileSpec := resourcefiles.NewEtcFileSpec(resourcefiles.NamespaceName, constants.CRICustomizationConfigPart)
etcFileSpec.TypedSpec().Mode = 0o600
etcFileSpec.TypedSpec().Contents = content
etcFileSpec.TypedSpec().SelinuxLabel = constants.EtcSelinuxLabel
if err := st.Create(ctx, etcFileSpec); err != nil {
return err
}
checksumRaw := sha256.Sum256(content)
expectedChecksum := hex.EncodeToString(checksumRaw[:])
expectedAnnotation := resourcefiles.SourceFileAnnotation + ":" + filepath.Join("/etc", etcFileSpec.Metadata().ID())
fileSpec, err := st.WatchFor(ctx, resourcefiles.NewEtcFileSpec(resourcefiles.NamespaceName, constants.CRIConfig).Metadata(),
state.WithCondition(func(r resource.Resource) (bool, error) {
spec, ok := r.(*resourcefiles.EtcFileSpec)
if !ok {
return false, nil
}
value, ok := spec.Metadata().Annotations().Get(expectedAnnotation)
return ok && value == expectedChecksum, nil
}))
if err != nil {
return fmt.Errorf("error waiting for file %q to be updated: %w", constants.CRIConfig, err)
}
// wait for the file to be rendered
_, err = st.WatchFor(ctx, resourcefiles.NewEtcFileStatus(resourcefiles.NamespaceName, constants.CRIConfig).Metadata(), state.WithCondition(func(r resource.Resource) (bool, error) {
fileStatus, ok := r.(*resourcefiles.EtcFileStatus)
if !ok {
return false, nil
}
return fileStatus.TypedSpec().SpecVersion == fileSpec.Metadata().Version().String(), nil
}))
return err
}
func existsAndIsFile(p string) (err error) {
var info os.FileInfo
info, err = os.Stat(p)
if err != nil {
if !errors.Is(err, fs.ErrNotExist) {
return err
}
return fmt.Errorf("file must exist: %q", p)
}
if !info.Mode().IsRegular() {
return fmt.Errorf("invalid mode: %q", info.Mode().String())
}
return nil
}
// UnmountPodMounts represents the UnmountPodMounts task.
func UnmountPodMounts(runtime.Sequence, any) (runtime.TaskExecutionFunc, string) {
return func(ctx context.Context, logger *log.Logger, r runtime.Runtime) (err error) {
var b []byte
if b, err = os.ReadFile("/proc/self/mounts"); err != nil {
return err
}
rdr := bytes.NewReader(b)
scanner := bufio.NewScanner(rdr)
for scanner.Scan() {
fields := strings.Fields(scanner.Text())
if len(fields) < 2 {
continue
}
mountpoint := fields[1]
if strings.HasPrefix(mountpoint, constants.EphemeralMountPoint+"/") {
logger.Printf("unmounting %s\n", mountpoint)
if err = mountv3.SafeUnmount(ctx, logger.Printf, mountpoint, false, false); err != nil {
if errors.Is(err, syscall.EINVAL) {
log.Printf("ignoring unmount error %s: %v", mountpoint, err)
} else {
return fmt.Errorf("error unmounting %s: %w", mountpoint, err)
}
}
}
}
return scanner.Err()
}, "unmountPodMounts"
}
// UnmountSystemDiskBindMounts represents the UnmountSystemDiskBindMounts task.
//
//nolint:gocyclo
func UnmountSystemDiskBindMounts(runtime.Sequence, any) (runtime.TaskExecutionFunc, string) {
return func(ctx context.Context, logger *log.Logger, r runtime.Runtime) (err error) {
ephemeralStatus, err := safe.StateGetByID[*blockres.VolumeStatus](ctx, r.State().V1Alpha2().Resources(), constants.EphemeralPartitionLabel)
if err != nil && !state.IsNotFoundError(err) {
return err
}
if ephemeralStatus == nil {
return nil
}
devname := ephemeralStatus.TypedSpec().MountLocation
if devname == "" {
return nil
}
f, err := os.Open("/proc/mounts")
if err != nil {
return err
}
defer f.Close() //nolint:errcheck
scanner := bufio.NewScanner(f)
for scanner.Scan() {
fields := strings.Fields(scanner.Text())
if len(fields) < 2 {
continue
}
device, mountpoint := fields[0], fields[1]
if device != devname || mountpoint == constants.EphemeralMountPoint {
continue
}
logger.Printf("unmounting %s\n", mountpoint)
if err = mountv3.SafeUnmount(ctx, logger.Printf, mountpoint, false, false); err != nil {
if errors.Is(err, syscall.EINVAL) {
log.Printf("ignoring unmount error %s: %v", mountpoint, err)
} else {
return fmt.Errorf("error unmounting %s: %w", mountpoint, err)
}
}
}
return scanner.Err()
}, "unmountSystemDiskBindMounts"
}
// CordonAndDrainNode represents the task for stop all containerd tasks in the
// k8s.io namespace.
func CordonAndDrainNode(runtime.Sequence, any) (runtime.TaskExecutionFunc, string) {
return func(ctx context.Context, logger *log.Logger, r runtime.Runtime) (err error) {
// skip not exist error as it means that the node hasn't fully joined yet
if _, err = os.Stat("/var/lib/kubelet/pki/kubelet-client-current.pem"); err != nil {
if errors.Is(err, fs.ErrNotExist) {
return nil
}
return err
}
var nodename string
if nodename, err = r.NodeName(); err != nil {
return err
}
// controllers will automatically cordon the node when the node enters appropriate phase,
// so here we just wait for the node to be cordoned
if err = waitForNodeCordoned(ctx, logger, r, nodename); err != nil {
return err
}
var kubeHelper *kubernetes.Client
if kubeHelper, err = kubernetes.NewClientFromKubeletKubeconfig(); err != nil {
return err
}
defer kubeHelper.Close() //nolint:errcheck
return kubeHelper.Drain(ctx, nodename)
}, "cordonAndDrainNode"
}
func waitForNodeCordoned(ctx context.Context, logger *log.Logger, r runtime.Runtime, nodename string) error {
ctx, cancel := context.WithTimeout(ctx, time.Minute)
defer cancel()
logger.Print("waiting for node to be cordoned")
_, err := r.State().V1Alpha2().Resources().WatchFor(
ctx,
k8s.NewNodeStatus(k8s.NamespaceName, nodename).Metadata(),
state.WithCondition(func(r resource.Resource) (bool, error) {
if resource.IsTombstone(r) {
return false, nil
}
nodeStatus, ok := r.(*k8s.NodeStatus)
if !ok {
return false, nil
}
return nodeStatus.TypedSpec().Unschedulable, nil
}),
)
return err
}
// LeaveEtcd represents the task for removing a control plane node from etcd.
//
//nolint:gocyclo
func LeaveEtcd(runtime.Sequence, any) (runtime.TaskExecutionFunc, string) {
return func(ctx context.Context, logger *log.Logger, r runtime.Runtime) (err error) {
_, err = os.Stat(filepath.Join(constants.EtcdDataPath, "/member"))
if err != nil {
if errors.Is(err, fs.ErrNotExist) {
return nil
}
return err
}
etcdID := (&services.Etcd{}).ID(r)
services := system.Services(r).List()
shouldLeaveEtcd := false
for _, service := range services {
if service.AsProto().Id != etcdID {
continue
}
switch service.GetState() { //nolint:exhaustive
case events.StateRunning:
fallthrough
case events.StateStopping:
fallthrough
case events.StateFailed:
shouldLeaveEtcd = true
}
break
}
if !shouldLeaveEtcd {
return nil
}
client, err := etcd.NewClientFromControlPlaneIPs(ctx, r.State().V1Alpha2().Resources())
if err != nil {
return fmt.Errorf("failed to create etcd client: %w", err)
}
//nolint:errcheck
defer client.Close()
ctx = clientv3.WithRequireLeader(ctx)
if err = client.LeaveCluster(ctx, r.State().V1Alpha2().Resources()); err != nil {
return fmt.Errorf("failed to leave cluster: %w", err)
}
return nil
}, "leaveEtcd"
}
// RemoveAllPods represents the task for stopping and removing all pods.
func RemoveAllPods(runtime.Sequence, any) (runtime.TaskExecutionFunc, string) {
return stopAndRemoveAllPods(cri.StopAndRemove), "removeAllPods"
}
// StopAllPods represents the task for stopping all pods.
func StopAllPods(runtime.Sequence, any) (runtime.TaskExecutionFunc, string) {
return stopAndRemoveAllPods(cri.StopOnly), "stopAllPods"
}
func waitForKubeletLifecycleFinalizers(ctx context.Context, logger *log.Logger, r runtime.Runtime) error {
logger.Printf("waiting for kubelet lifecycle finalizers")
ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
defer cancel()
lifecycle := resource.NewMetadata(k8s.NamespaceName, k8s.KubeletLifecycleType, k8s.KubeletLifecycleID, resource.VersionUndefined)
for {
ok, err := r.State().V1Alpha2().Resources().Teardown(ctx, lifecycle)
if err != nil {
return err
}
if ok {
break
}
_, err = r.State().V1Alpha2().Resources().WatchFor(ctx, lifecycle, state.WithFinalizerEmpty())
if err != nil {
return err
}
}
return r.State().V1Alpha2().Resources().Destroy(ctx, lifecycle)
}
func stopAndRemoveAllPods(stopAction cri.StopAction) runtime.TaskExecutionFunc {
return func(ctx context.Context, logger *log.Logger, r runtime.Runtime) (err error) {
if err = waitForKubeletLifecycleFinalizers(ctx, logger, r); err != nil {