forked from openshift/machine-config-operator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdaemon.go
3043 lines (2663 loc) · 106 KB
/
daemon.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 daemon
import (
"bufio"
"context"
"crypto/tls"
"encoding/json"
"errors"
"fmt"
"io"
"io/fs"
"net/http"
"os"
"os/exec"
"os/signal"
"path/filepath"
"slices"
"strings"
"sync"
"syscall"
"time"
mcfgclientset "github.com/openshift/client-go/machineconfiguration/clientset/versioned"
mcopclientset "github.com/openshift/client-go/operator/clientset/versioned"
"github.com/openshift/library-go/pkg/operator/configobserver/featuregates"
ign3types "github.com/coreos/ignition/v2/config/v3_4/types"
"github.com/google/go-cmp/cmp"
"github.com/google/renameio"
"golang.org/x/time/rate"
corev1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
"k8s.io/apimachinery/pkg/util/wait"
coreinformersv1 "k8s.io/client-go/informers/core/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/klog/v2"
corev1lister "k8s.io/client-go/listers/core/v1"
"k8s.io/client-go/tools/cache"
"k8s.io/client-go/util/workqueue"
configv1 "github.com/openshift/api/config/v1"
mcfgv1 "github.com/openshift/api/machineconfiguration/v1"
mcfgalphav1 "github.com/openshift/api/machineconfiguration/v1alpha1"
mcfginformersv1 "github.com/openshift/client-go/machineconfiguration/informers/externalversions/machineconfiguration/v1"
mcfglistersv1 "github.com/openshift/client-go/machineconfiguration/listers/machineconfiguration/v1"
mcoResourceRead "github.com/openshift/machine-config-operator/lib/resourceread"
ctrlcommon "github.com/openshift/machine-config-operator/pkg/controller/common"
"github.com/openshift/machine-config-operator/pkg/daemon/constants"
"github.com/openshift/machine-config-operator/pkg/daemon/osrelease"
"github.com/openshift/machine-config-operator/pkg/helpers"
"github.com/openshift/machine-config-operator/pkg/upgrademonitor"
)
// Daemon is the dispatch point for the functions of the agent on the
// machine. it keeps track of connections and the current state of the update
// process.
type Daemon struct {
// name is the node name.
name string
// os the operating system the MCD is running on
os osrelease.OperatingSystem
// mock is set if we're running as non-root, probably under unit tests
mock bool
// NodeUpdaterClient wraps rpm-ostree and will eventually be removed with a direct rpmostreeclient value
NodeUpdaterClient *RpmOstreeClient
// bootID is a unique value per boot (generated by the kernel)
bootID string
// bootedOSImageURL is the currently booted URL of the operating system
bootedOSImageURL string
// bootedOScommit is the commit hash of the currently booted operating system
bootedOSCommit string
// previousFinalizationFailure caches a failure of ostree-finalize-staged.service
// we may have seen from the previous boot.
previousFinalizationFailure string
// kubeClient allows interaction with Kubernetes, including the node we are running on.
kubeClient kubernetes.Interface
mcfgClient mcfgclientset.Interface
// mcopClient allows interaction with Openshift operator level objects, such as MachineConfiguration
mcopClient mcopclientset.Interface
// nodeLister is used to watch for updates via the informer
nodeLister corev1lister.NodeLister
nodeListerSynced cache.InformerSynced
mcLister mcfglistersv1.MachineConfigLister
mcListerSynced cache.InformerSynced
mcpLister mcfglistersv1.MachineConfigPoolLister
mcpListerSynced cache.InformerSynced
ccLister mcfglistersv1.ControllerConfigLister
ccListerSynced cache.InformerSynced
// skipReboot skips the reboot after a sync, only valid with onceFrom != ""
skipReboot bool
kubeletHealthzEnabled bool
kubeletHealthzEndpoint string
updateActive bool
updateActiveLock sync.Mutex
nodeWriter NodeWriter
featureGatesAccessor featuregates.FeatureGateAccess
// channel used by callbacks to signal Run() of an error
exitCh chan<- error
// channel used to ensure all spawned goroutines exit when we exit.
stopCh <-chan struct{}
// node is the current instance of the node being processed through handleNodeEvent
// or the very first instance grabbed when the daemon starts
node *corev1.Node
queue workqueue.TypedRateLimitingInterface[string]
ccQueue workqueue.TypedRateLimitingInterface[string]
cmQueue workqueue.TypedRateLimitingInterface[string]
enqueueNode func(*corev1.Node)
syncHandler func(node string) error
// isControlPlane is true if this node is a control plane (master).
// The machine may also be a worker (with schedulable masters).
isControlPlane bool
// nodeInitialized is true when we've performed one-time initialization
// after having updated the node object
nodeInitialized bool
// booting is true when all initial synchronization to the target
// machineconfig is done
booting bool
// rebootQueued is true when the node is waiting for graceful shutdown
rebootQueued bool
currentConfigPath string
currentImagePath string
// Config Drift Monitor
configDriftMonitor ConfigDriftMonitor
// Used for Hypershift
hypershiftConfigMap string
initializeHealthServer bool
deferKubeletRestart bool
// Ensures that only a single syncOSImagePullSecrets call can run at a time.
osImageMux *sync.Mutex
}
// CoreOSDaemon protects the methods that should only be called on CoreOS variants
// Ideally New() would return a Daemon interface that could either be a base Daemon or a
// CoreOSDaemon. Besides adding some type-checking and clarity, that would allow moving fields like
// bootedOSImageURL or functions like checkOS() to CoreOSDaemon. Both Daemon and CoreOSDaemon,
// however, have to share the update() method, and update() requires access to many fields from
// Daemon. That eliminates the possibility of update() being defined on an interface. So we have to
// cast Daemon to CoreOSDaemon manually in update()
type CoreOSDaemon struct {
*Daemon
}
var ErrAuxiliary = errors.New("Error from auxiliary packages")
const (
// pathSystemd is the path systemd modifiable units, services, etc.. reside
pathSystemd = "/etc/systemd/system"
// pathDevNull is the systems path to and endless blackhole
pathDevNull = "/dev/null"
// currentConfigPath is where we store the current config on disk to validate
// against annotations changes
currentConfigPath = "/etc/machine-config-daemon/currentconfig"
// bootstrapConfigDiffPath is where we store the current config on disk to validate
// against annotations changes
bootstrapConfigDiffPath = "/etc/machine-config-daemon/bootstrapconfigdiff"
// currentImagePath is where we store the current image on disk to validate
// against annotation changes.
currentImagePath = "/etc/machine-config-daemon/currentimage"
// originalContainerBin is the path at which we've stashed the MCD container's /usr/bin
// in the host namespace. We use this for executing any extra binaries we have in our
// container image.
originalContainerBin = "/run/machine-config-daemon-bin"
kubeletHealthzPollingInterval = 30 * time.Second
kubeletHealthzTimeout = 30 * time.Second
// updateDelay is the baseline speed at which we react to changes. We don't
// need to react in milliseconds as any change would involve rebooting the node.
// Having this be relatively high limits the number of times we retry before
// the MCC/MCO will time out. We don't want to spam our logs with the same
// error.
updateDelay = 5 * time.Second
// maxUpdateBackoff is the maximum time to react to a change as we back off
// in the face of errors.
maxUpdateBackoff = 60 * time.Second
// used for Hypershift daemon
mcsServedConfigPath = "/etc/mcs-machine-config-content.json"
hypershiftCurrentConfigPath = "/etc/mcd-currentconfig.json"
configMapConfigKey = "config"
configMapHashKey = "hash"
imageCAFilePath = "/etc/docker/certs.d"
// used for certificate syncing
caBundleFilePath = "/etc/kubernetes/kubelet-ca.crt"
cloudCABundleFilePath = "/etc/kubernetes/static-pod-resources/configmaps/cloud-config/ca-bundle.pem"
userCABundleFilePath = "/etc/pki/ca-trust/source/anchors/openshift-config-user-ca-bundle.crt"
kubeConfigPath = "/etc/kubernetes/kubeconfig"
// Where nmstate writes the link files if it persisted ifnames.
// https://github.com/nmstate/nmstate/blob/03c7b03bd4c9b0067d3811dbbf72635201519356/rust/src/cli/persist_nic.rs#L32-L36
systemdNetworkDir = "etc/systemd/network"
)
type onceFromOrigin int
const (
onceFromUnknownConfig onceFromOrigin = iota
onceFromLocalConfig
onceFromRemoteConfig
)
var (
defaultRebootTimeout = 24 * time.Hour
)
// Create a custom error type to hold the missing MachineConfig name.
type ErrMissingMachineConfig struct {
missingMC string
}
// Optional constructor for the error type.
func newErrMissingMachineConfig(missingMC string) error {
return &ErrMissingMachineConfig{
missingMC: missingMC,
}
}
// This implements the error interface within Go.
func (e *ErrMissingMachineConfig) Error() string {
return fmt.Sprintf("missing MachineConfig %s", e.missingMC)
}
// This is an optional accessor to get the missing MachineConfig. useful when trying to increment the metric in one line.
func (e *ErrMissingMachineConfig) MissingMachineConfig() string {
return e.missingMC
}
// rebootCommand creates a new transient systemd unit to reboot the system.
// With the upstream implementation of kubelet graceful shutdown feature,
// we don't explicitly stop the kubelet so that kubelet can gracefully shutdown
// pods when `GracefulNodeShutdown` feature gate is enabled.
// kubelet uses systemd inhibitor locks to delay node shutdown to terminate pods.
// https://kubernetes.io/docs/concepts/architecture/nodes/#graceful-node-shutdown
func rebootCommand(rationale string) *exec.Cmd {
return exec.Command("systemd-run", "--unit", "machine-config-daemon-reboot",
"--description", fmt.Sprintf("machine-config-daemon: %s", rationale), "/bin/sh", "-c", "systemctl reboot")
}
// getBootID loads the unique "boot id" which is generated by the Linux kernel.
func getBootID() (string, error) {
currentBootIDBytes, err := os.ReadFile("/proc/sys/kernel/random/boot_id")
if err != nil {
return "", err
}
return strings.TrimSpace(string(currentBootIDBytes)), nil
}
// New sets up the systemd and kubernetes connections needed to update the
// machine.
func New(
exitCh chan<- error,
) (*Daemon, error) {
mock := false
if os.Getuid() != 0 {
mock = true
}
var (
osImageURL string
osVersion string
osCommit string
err error
)
hostos := osrelease.OperatingSystem{}
if !mock {
hostos, err = osrelease.GetHostRunningOS()
if err != nil {
hostOS.WithLabelValues("unsupported", "").Set(1)
return nil, fmt.Errorf("checking operating system: %w", err)
}
}
var nodeUpdaterClient *RpmOstreeClient
// Only pull the osImageURL from OSTree when we are on RHCOS or FCOS
if hostos.IsCoreOSVariant() {
nodeUpdaterClientVal := NewNodeUpdaterClient()
nodeUpdaterClient = &nodeUpdaterClientVal
err := nodeUpdaterClient.Initialize()
if err != nil {
return nil, fmt.Errorf("error initializing rpm-ostree: %w", err)
}
osImageURL, osVersion, osCommit, err = nodeUpdaterClient.GetBootedOSImageURL()
if err != nil {
return nil, fmt.Errorf("error reading osImageURL from rpm-ostree: %w", err)
}
klog.Infof("Booted osImageURL: %s (%s) %s", osImageURL, osVersion, osCommit)
}
bootID := ""
if !mock {
bootID, err = getBootID()
if err != nil {
return nil, fmt.Errorf("failed to read boot ID: %w", err)
}
}
// report OS & version (if RHCOS or FCOS) to prometheus
hostOS.WithLabelValues(hostos.ToPrometheusLabel(), osVersion).Set(1)
return &Daemon{
mock: mock,
booting: true,
initializeHealthServer: true,
rebootQueued: false,
os: hostos,
NodeUpdaterClient: nodeUpdaterClient,
bootedOSImageURL: osImageURL,
bootedOSCommit: osCommit,
bootID: bootID,
exitCh: exitCh,
currentConfigPath: currentConfigPath,
currentImagePath: currentImagePath,
configDriftMonitor: NewConfigDriftMonitor(),
osImageMux: &sync.Mutex{},
}, nil
}
// ClusterConnect sets up the systemd and kubernetes connections needed to update the
// machine.
func (dn *Daemon) ClusterConnect(
name string,
kubeClient kubernetes.Interface,
mcfgClient mcfgclientset.Interface,
mcInformer mcfginformersv1.MachineConfigInformer,
nodeInformer coreinformersv1.NodeInformer,
ccInformer mcfginformersv1.ControllerConfigInformer,
mcpInformer mcfginformersv1.MachineConfigPoolInformer,
mcopClient mcopclientset.Interface,
kubeletHealthzEnabled bool,
kubeletHealthzEndpoint string,
featureGatesAccessor featuregates.FeatureGateAccess,
) error {
dn.name = name
dn.kubeClient = kubeClient
dn.mcfgClient = mcfgClient
dn.mcopClient = mcopClient
// Other controllers start out with the default controller limiter which retries
// in milliseconds; since any change here will involve rebooting the node
// we don't need to react in milliseconds. See also updateDelay above.
dn.queue = workqueue.NewTypedRateLimitingQueueWithConfig[string](workqueue.NewTypedMaxOfRateLimiter[string](
&workqueue.TypedBucketRateLimiter[string]{Limiter: rate.NewLimiter(rate.Limit(updateDelay), 1)},
workqueue.NewTypedItemExponentialFailureRateLimiter[string](1*time.Second, maxUpdateBackoff)),
workqueue.TypedRateLimitingQueueConfig[string]{Name: "machineconfigdaemon"})
nodeInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{
AddFunc: dn.handleNodeEvent,
UpdateFunc: func(_, newObj interface{}) { dn.handleNodeEvent(newObj) },
})
dn.nodeLister = nodeInformer.Lister()
dn.nodeListerSynced = nodeInformer.Informer().HasSynced
dn.mcLister = mcInformer.Lister()
dn.mcListerSynced = mcInformer.Informer().HasSynced
dn.ccQueue = workqueue.NewTypedRateLimitingQueue(workqueue.DefaultTypedControllerRateLimiter[string]())
ccInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{
AddFunc: dn.handleControllerConfigEvent,
UpdateFunc: func(_, newObj interface{}) { dn.handleControllerConfigEvent(newObj) },
// In theory the configmap we care about shouldn't get deleted
DeleteFunc: dn.handleControllerConfigEvent,
})
dn.ccLister = ccInformer.Lister()
dn.ccListerSynced = ccInformer.Informer().HasSynced
dn.mcpLister = mcpInformer.Lister()
dn.mcpListerSynced = mcpInformer.Informer().HasSynced
nw, err := newNodeWriter(dn.name, dn.stopCh)
if err != nil {
return err
}
dn.nodeWriter = nw
go dn.nodeWriter.Run(dn.stopCh)
dn.enqueueNode = dn.enqueueDefault
dn.syncHandler = dn.syncNode
dn.kubeletHealthzEnabled = kubeletHealthzEnabled
dn.kubeletHealthzEndpoint = kubeletHealthzEndpoint
dn.featureGatesAccessor = featureGatesAccessor
return nil
}
// HypershiftConnect sets up a simplified daemon for Hypershift updates
func (dn *Daemon) HypershiftConnect(
name string,
kubeClient kubernetes.Interface,
nodeInformer coreinformersv1.NodeInformer,
configMap string,
) error {
dn.name = name
dn.kubeClient = kubeClient
dn.hypershiftConfigMap = configMap
node, err := dn.kubeClient.CoreV1().Nodes().Get(context.TODO(), name, metav1.GetOptions{})
if err != nil {
klog.Fatalf("Cannot fetch node object: %v", err)
}
dn.node = node
nodeInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{
AddFunc: dn.handleNodeEvent,
UpdateFunc: func(_, newObj interface{}) { dn.handleNodeEvent(newObj) },
})
dn.queue = workqueue.NewTypedRateLimitingQueueWithConfig[string](workqueue.NewTypedMaxOfRateLimiter[string](
&workqueue.TypedBucketRateLimiter[string]{Limiter: rate.NewLimiter(rate.Limit(updateDelay), 1)},
workqueue.NewTypedItemExponentialFailureRateLimiter[string](1*time.Second, maxUpdateBackoff)),
workqueue.TypedRateLimitingQueueConfig[string]{Name: "machineconfigdaemon"})
dn.enqueueNode = dn.enqueueDefault
dn.syncHandler = dn.syncNodeHypershift
nw, err := newNodeWriter(dn.name, dn.stopCh)
if err != nil {
return err
}
dn.nodeWriter = nw
go dn.nodeWriter.Run(dn.stopCh)
return nil
}
// PrepareNamespace is invoked before chrooting into the target root
func PrepareNamespace(target string) error {
// With ReexecuteForTargetRoot, we have already chroot into rootfs.
// So, we should already have necessary MCD pod content mounted inside the host.
// This also avoids overriding previously mounted content.
if target == "/" {
return nil
}
// This contains the /run/secrets/kubernetes.io service account tokens that we still need
secretsMount := "/run/secrets"
targetSecrets := filepath.Join(target, secretsMount)
if err := os.MkdirAll(targetSecrets, 0o755); err != nil {
return err
}
// This will only affect our mount namespace, not the host
if err := runCmdSync("mount", "--rbind", secretsMount, targetSecrets); err != nil {
return fmt.Errorf("failed to mount %s to %s: %w", secretsMount, targetSecrets, err)
}
targetSavedBin := filepath.Join(target, originalContainerBin)
if err := os.MkdirAll(targetSavedBin, 0o755); err != nil {
return fmt.Errorf("failed to create %s: %w", targetSavedBin, err)
}
usrbin := "/usr/bin"
if err := runCmdSync("mount", "--rbind", usrbin, targetSavedBin); err != nil {
return fmt.Errorf("failed to mount %s to %s: %w", usrbin, targetSavedBin, err)
}
return nil
}
// ReexecuteForTargetRoot detects the OS in the host root filesystem, then
// copies the appropriate binary into `/run/bin/` there, then does a `chroot`
// and re-executes the new binary.
func ReexecuteForTargetRoot(target string) error {
// Nothing to do in this case
if target == "/" {
return nil
}
// Extra check to avoid recursion
reexecEnv := "_MCD_DID_REEXEC"
if _, ok := os.LookupEnv(reexecEnv); ok {
return nil
}
sourceOsVersion, err := osrelease.GetHostRunningOSFromRoot("/")
if err != nil {
return fmt.Errorf("failed to get source OS: %w", err)
}
targetOsVersion, err := osrelease.GetHostRunningOSFromRoot(target)
if err != nil {
return fmt.Errorf("failed to get target OS: %w", err)
}
var sourceBinarySuffix string
if sourceOsVersion.IsLikeRHEL() && targetOsVersion.IsLikeRHEL() {
sourceMajor := sourceOsVersion.BaseVersionMajor()
targetMajor := targetOsVersion.BaseVersionMajor()
if sourceMajor == "9" && targetMajor == "8" {
sourceBinarySuffix = ".rhel8"
klog.Info("container is rhel9, target is rhel8")
} else {
klog.Infof("using appropriate binary for source=rhel-%s target=rhel-%s", sourceMajor, targetMajor)
}
} else {
klog.Info("assuming we can use container binary chroot() to host")
}
sourceBinary := "/usr/bin/machine-config-daemon" + sourceBinarySuffix
src, err := os.Open(sourceBinary)
if err != nil {
return fmt.Errorf("opening %s: %w", sourceBinary, err)
}
defer src.Close()
targetBinBase := "run/bin/machine-config-daemon"
targetBin := filepath.Join(target, targetBinBase)
targetBinDir := filepath.Dir(targetBin)
if err := os.MkdirAll(targetBinDir, 0o755); err != nil {
return fmt.Errorf("mkdir %s: %w", targetBinDir, err)
}
f, err := renameio.TempFile(targetBinDir, targetBin)
if err != nil {
return fmt.Errorf("writing %s: %w", targetBin, err)
}
defer f.Cleanup()
if _, err := io.Copy(f, src); err != nil {
f.Close()
return fmt.Errorf("writing %s: %w", targetBin, err)
}
if err := f.Chmod(0o755); err != nil {
return err
}
// Must close our writable fd
if err := f.CloseAtomicallyReplace(); err != nil {
return err
}
if err := syscall.Chroot(target); err != nil {
return fmt.Errorf("failed to chroot to %s: %w", target, err)
}
if err := os.Chdir("/"); err != nil {
return fmt.Errorf("failed to change directory to /: %w", err)
}
// Now we will see the binary in the target root
targetBin = "/" + targetBinBase
// We have a "belt and suspenders" approach for detecting the case where
// we're running in the target root. First we inject --root-mount=/, and
// we also set an environment variable to be really sure.
newArgv := []string{targetBin}
newArgv = append(newArgv, os.Args[1:]...)
newArgv = append(newArgv, "--root-mount=/")
newEnv := append(os.Environ(), fmt.Sprintf("%s=1", reexecEnv))
klog.Infof("Invoking re-exec %s", targetBin)
return syscall.Exec(targetBin, newArgv, newEnv)
}
// worker runs a worker thread that just dequeues items, processes them, and marks them done.
// It enforces that the syncHandler is never invoked concurrently with the same key.
func (dn *Daemon) worker() {
for dn.processNextWorkItem() {
}
}
func (dn *Daemon) processNextWorkItem() bool {
key, quit := dn.queue.Get()
if quit {
return false
}
defer dn.queue.Done(key)
err := dn.syncHandler(key)
dn.handleErr(err, key)
return true
}
func (dn *Daemon) handleErr(err error, key string) {
if err == nil {
dn.queue.Forget(key)
return
}
// Exit if nodewriter is not initialized, used for Hypershift
if dn.nodeWriter == nil {
dn.updateErrorStateHypershift(err)
klog.Fatalf("Error handling node sync: %v", err)
}
if err := dn.updateErrorState(err); err != nil {
klog.Errorf("Could not update annotation: %v", err)
}
// This is at V(2) since the updateErrorState() call above ends up logging too
klog.V(2).Infof("Error syncing node %v (retries %d): %v", key, dn.queue.NumRequeues(key), err)
dn.queue.AddRateLimited(key)
}
type unreconcilableErr struct {
error
}
func (dn *Daemon) updateErrorState(err error) error {
var uErr *unreconcilableErr
if errors.As(err, &uErr) {
dn.nodeWriter.SetUnreconcilable(err)
} else {
if err := dn.nodeWriter.SetDegraded(err); err != nil {
return err
}
}
return nil
}
func (dn *Daemon) updateErrorStateHypershift(err error) {
// truncatedErr caps error message at a reasonable length to limit the risk of hitting the total
// annotation size limit (256 kb) at any point
truncatedErr := fmt.Sprintf("%.2000s", err.Error())
annos := map[string]string{
constants.MachineConfigDaemonStateAnnotationKey: constants.MachineConfigDaemonStateDegraded,
constants.MachineConfigDaemonReasonAnnotationKey: truncatedErr,
}
if _, annoErr := dn.nodeWriter.SetAnnotations(annos); annoErr != nil {
klog.Fatalf("Error setting degraded annotation %v, original error %v", annoErr, err)
}
}
// initializeNode is called the first time we get our node object; however to
// ensure we handle failures: everything called from here should be idempotent.
func (dn *Daemon) initializeNode() error {
if dn.nodeInitialized {
return nil
}
// Some parts of the MCO dispatch on whether or not we're managing a control plane node
if _, isControlPlane := dn.node.Labels[ctrlcommon.MasterLabel]; isControlPlane {
klog.Infof("Node %s is part of the control plane", dn.node.Name)
if err := dn.initializeControlPlane(); err != nil {
return err
}
dn.isControlPlane = true
} else {
klog.Infof("Node %s is not labeled %s", dn.node.Name, ctrlcommon.MasterLabel)
}
dn.nodeInitialized = true
return nil
}
//nolint:gocyclo
func (dn *Daemon) syncNode(key string) error {
startTime := time.Now()
klog.V(4).Infof("Started syncing node %q (%v)", key, startTime)
defer func() {
klog.V(4).Infof("Finished syncing node %q (%v)", key, time.Since(startTime))
}()
_, name, err := cache.SplitMetaNamespaceKey(key)
if err != nil {
return err
}
// If this isn't our node, nothing to do. The node controller
// handles other nodes.
if name != dn.name {
return nil
}
node, err := dn.nodeLister.Get(name)
if apierrors.IsNotFound(err) {
klog.V(2).Infof("node %v has been deleted", key)
return nil
}
if err != nil {
return err
}
// Check for Deleted Node
if node.DeletionTimestamp != nil {
klog.Infof("Node %s was deleted!", node.Name)
return nil
}
// Check for queued reboot. If we attempt to sync while waiting for a reboot,
// it will cause the update to start again, so we skip the sync.
if dn.rebootQueued {
klog.Infof("Node %s is queued for a reboot, skipping sync.", node.Name)
return nil
}
// Get MCP associated with node
pool, err := helpers.GetPrimaryPoolNameForMCN(dn.mcpLister, node)
if err != nil {
return err
}
if node.Annotations[constants.MachineConfigDaemonPostConfigAction] == constants.MachineConfigDaemonStateRebooting {
klog.Info("Detected Rebooting Annotation, applying MCN.")
err := upgrademonitor.GenerateAndApplyMachineConfigNodes(
&upgrademonitor.Condition{State: mcfgalphav1.MachineConfigNodeUpdatePostActionComplete, Reason: string(mcfgalphav1.MachineConfigNodeUpdateRebooted), Message: "Node has rebooted"},
&upgrademonitor.Condition{State: mcfgalphav1.MachineConfigNodeUpdateRebooted, Reason: fmt.Sprintf("%s%s", string(mcfgalphav1.MachineConfigNodeUpdatePostActionComplete), string(mcfgalphav1.MachineConfigNodeUpdateRebooted)), Message: "Upgrade required a reboot. Completed this as the post update action."},
metav1.ConditionTrue,
metav1.ConditionTrue,
node,
dn.mcfgClient,
dn.featureGatesAccessor,
pool,
)
if err != nil {
klog.Errorf("Error making MCN for Rebooted: %v", err)
}
removeRebooting := make(map[string]string)
removeRebooting[constants.MachineConfigDaemonPostConfigAction] = ""
_, err = dn.nodeWriter.SetAnnotations(removeRebooting)
if err != nil {
klog.Errorf("Could not unset rebooting Anno: %v", err)
}
}
// Deep-copy otherwise we are mutating our cache.
node = node.DeepCopy()
if dn.node == nil {
dn.node = node
if err := dn.initializeNode(); err != nil {
return err
}
} else {
// Log state transitions here
oldState := dn.node.Annotations[constants.MachineConfigDaemonStateAnnotationKey]
newState := node.Annotations[constants.MachineConfigDaemonStateAnnotationKey]
oldReason := dn.node.Annotations[constants.MachineConfigDaemonReasonAnnotationKey]
newReason := node.Annotations[constants.MachineConfigDaemonReasonAnnotationKey]
if oldState != newState {
klog.Infof("Transitioned from state: %v -> %v", oldState, newState)
}
if oldReason != newReason {
klog.Infof("Transitioned from degraded/unreconcilable reason %v -> %v", oldReason, newReason)
}
dn.node = node
}
// Sync our OS image pull secrets here. This will account for any changes to
// the ControllerConfig.
//
// I'm not sure if this needs to be done right here or as frequently as this,
// but it shouldn't cause too much impact.
if err := dn.syncInternalRegistryPullSecrets(nil); err != nil {
return err
}
// Take care of the very first sync of the MCD on a node.
// This loads the node annotation from the bootstrap (if we're really bootstrapping)
// and then proceeds to check the state of the node, which includes
// finalizing an update and/or reconciling the current and desired machine configs.
if dn.booting {
// Be sure only the MCD is running now, disable -firstboot.service
if err := upgradeHackFor44AndBelow(); err != nil {
return err
}
if err := removeIgnitionArtifacts(); err != nil {
return err
}
if err := PersistNetworkInterfaces("/"); err != nil {
return err
}
if err := dn.checkStateOnFirstRun(); err != nil {
return err
}
// finished syncing node for the first time;
// currently we return immediately here, although
// I think we should change this to continue.
dn.booting = false
err = upgrademonitor.GenerateAndApplyMachineConfigNodes(
&upgrademonitor.Condition{State: mcfgalphav1.MachineConfigNodeResumed, Reason: string(mcfgalphav1.MachineConfigNodeResumed), Message: fmt.Sprintf("In desired config %s. Resumed normal operations.", node.Annotations[constants.CurrentMachineConfigAnnotationKey])},
nil,
metav1.ConditionTrue,
metav1.ConditionFalse,
node,
dn.mcfgClient,
dn.featureGatesAccessor,
pool,
)
if err != nil {
klog.Errorf("Error making MCN for Resumed true: %v", err)
}
removeRebooting := make(map[string]string)
removeRebooting[constants.MachineConfigDaemonReasonAnnotationKey] = ""
node.SetAnnotations(removeRebooting)
// Start the Config Drift Monitor since we're booted up.
dn.startConfigDriftMonitor()
return nil
}
// Check if a previous drain caused us to degrade. If the drain
// has yet to complete and we are in a degrade state, continue
// to stay in this state
if dn.node.Annotations[constants.DesiredDrainerAnnotationKey] != "" &&
dn.node.Annotations[constants.DesiredDrainerAnnotationKey] != dn.node.Annotations[constants.LastAppliedDrainerAnnotationKey] {
klog.Infof("A previously requested drain has not yet completed. Waiting for machine-config-controller to finish draining node.")
return nil
}
// Pass to the shared update prep method
ufc, err := dn.prepUpdateFromCluster()
if err != nil {
maybeReportOnMissingMC(err)
return err
}
if ufc != nil {
err = upgrademonitor.GenerateAndApplyMachineConfigNodes(
&upgrademonitor.Condition{State: mcfgalphav1.MachineConfigNodeUpdated, Reason: string(mcfgalphav1.MachineConfigNodeUpdated), Message: fmt.Sprintf("Node %s needs an update", dn.node.GetName())},
nil,
metav1.ConditionFalse,
metav1.ConditionFalse,
dn.node,
dn.mcfgClient,
dn.featureGatesAccessor,
pool,
)
if err != nil {
klog.Errorf("Error making MCN for Updated false: %v", err)
}
// Only check for config drift if we need to update.
if err := dn.runPreflightConfigDriftCheck(); err != nil {
return err
}
if err := dn.triggerUpdate(ufc.currentConfig, ufc.desiredConfig, ufc.currentImage, ufc.desiredImage); err != nil {
// if MC was not found, let user know where they can find more info on this.
maybeReportOnMissingMC(err)
return err
}
} else {
err = upgrademonitor.GenerateAndApplyMachineConfigNodes(
&upgrademonitor.Condition{State: mcfgalphav1.MachineConfigNodeUpdated, Reason: string(mcfgalphav1.MachineConfigNodeUpdated), Message: fmt.Sprintf("Node %s Updated", dn.node.GetName())},
nil,
metav1.ConditionTrue,
metav1.ConditionFalse,
dn.node,
dn.mcfgClient,
dn.featureGatesAccessor,
pool,
)
if err != nil {
klog.Errorf("Error making MCN for Updated: %v", err)
}
}
klog.V(2).Infof("Node %s is already synced", node.Name)
if !dn.booting && dn.initializeHealthServer {
// we want to wait until we are done booting AND we only want to do this once
// we also want to give ourselves a little extra buffer. The corner case here is sometimes we get thru the first sync, and then the errors
// begin ~1 minute later. So, list some api items until then. if we get to here, then we must be safe.
if err := wait.PollUntilContextTimeout(context.TODO(), 10*time.Second, 1*time.Minute, false, func(_ context.Context) (bool, error) {
_, err := dn.ccLister.List(labels.Everything())
if err != nil {
return false, err
}
return false, nil
}); err != nil {
if !wait.Interrupted(err) {
return fmt.Errorf("could not list API items: %v", err)
}
}
go func() {
klog.Infof("Starting health listener on 127.0.0.1:8798")
mux := http.NewServeMux()
mux.Handle("/health", &healthHandler{})
s := http.Server{
TLSConfig: &tls.Config{
MinVersion: tls.VersionTLS12,
NextProtos: []string{"http/1.1"},
CipherSuites: cipherOrder(),
},
TLSNextProto: make(map[string]func(*http.Server, *tls.Conn, http.Handler)),
Addr: "127.0.0.1:8798",
Handler: mux}
go func() {
if err := s.ListenAndServe(); err != nil && err != http.ErrServerClosed {
klog.Errorf("health listener exited with error: %v", err)
}
}()
<-dn.stopCh
if err := s.Shutdown(context.Background()); err != nil {
if err != http.ErrServerClosed {
klog.Errorf("error stopping health listener: %v", err)
}
} else {
klog.Infof("health listener successfully stopped")
}
}()
dn.initializeHealthServer = false
}
return nil
}
// Validates that the on-disk state matches the currently applied machineconfig
// before an update occurs.
func (dn *Daemon) runPreflightConfigDriftCheck() error {
// This allows skip behavior based upon the presence of
// the forcefile: /run/machine-config-daemon-force.
if forceFileExists() {
klog.Infof("Skipping preflight config drift check; %s present", constants.MachineConfigDaemonForceFile)
return nil
}
currentOnDisk, err := dn.getCurrentConfigOnDisk()
if err != nil && !os.IsNotExist(err) {
return err
}
if currentOnDisk == nil {
currentOnDisk, err = dn.getCurrentConfigFromNode()
if err != nil {
return err
}
}
start := time.Now()
if err := dn.validateOnDiskStateOrImage(currentOnDisk.currentConfig, currentOnDisk.currentImage); err != nil {
dn.nodeWriter.Eventf(corev1.EventTypeWarning, "PreflightConfigDriftCheckFailed", err.Error())
klog.Errorf("Preflight config drift check failed: %v", err)
return &configDriftErr{err}
}
klog.Infof("Preflight config drift check successful (took %s)", time.Since(start))
return nil
}
// enqueueDefault calls a default enqueue function
func (dn *Daemon) enqueueDefault(node *corev1.Node) {
key, err := cache.DeletionHandlingMetaNamespaceKeyFunc(node)
if err != nil {
utilruntime.HandleError(fmt.Errorf("couldn't get key for object %#v: %w", node, err))
return
}
dn.queue.AddRateLimited(key)
}
// RunHypershift is the entry point for the simplified Hypershift mode daemon
func (dn *Daemon) RunHypershift(stopCh <-chan struct{}, exitCh <-chan error) error {
klog.Info("Starting MachineConfigDaemon - Hypershift")
signaled := make(chan struct{})
dn.InstallSignalHandler(signaled)
defer utilruntime.HandleCrash()
defer dn.queue.ShutDown()
go wait.Until(dn.worker, time.Second, stopCh)
for {
select {
case <-stopCh:
return nil
case <-signaled:
return nil
case err := <-exitCh:
// This channel gets errors from auxiliary goroutines like kubehealth
// TODO we really shouldn't have any for hypershift
klog.Warningf("Got an error from auxiliary tools: %v", err)
}
}
}
//nolint:gocyclo
func (dn *Daemon) syncNodeHypershift(key string) error {
// First, get the current and desired configurations for the node
// current configuration will be read from on-disk state, either