forked from openshift/machine-config-operator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
daemon.go
1695 lines (1510 loc) · 55.3 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"
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
"os/exec"
"os/signal"
"path/filepath"
"strings"
"sync"
"syscall"
"time"
ign2types "github.com/coreos/ignition/config/v2_2/types"
ign3types "github.com/coreos/ignition/v2/config/v3_2/types"
"github.com/golang/glog"
"github.com/google/go-cmp/cmp"
"github.com/pkg/errors"
"github.com/vincent-petithory/dataurl"
"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/types"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
"k8s.io/apimachinery/pkg/util/strategicpatch"
"k8s.io/apimachinery/pkg/util/wait"
coreinformersv1 "k8s.io/client-go/informers/core/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/kubernetes/scheme"
corev1client "k8s.io/client-go/kubernetes/typed/core/v1"
corev1lister "k8s.io/client-go/listers/core/v1"
"k8s.io/client-go/tools/cache"
"k8s.io/client-go/tools/record"
clientretry "k8s.io/client-go/util/retry"
"k8s.io/client-go/util/workqueue"
"k8s.io/kubectl/pkg/drain"
configv1 "github.com/openshift/api/config/v1"
"github.com/openshift/machine-config-operator/lib/resourceread"
mcfgv1 "github.com/openshift/machine-config-operator/pkg/apis/machineconfiguration.openshift.io/v1"
commonconstants "github.com/openshift/machine-config-operator/pkg/constants"
ctrlcommon "github.com/openshift/machine-config-operator/pkg/controller/common"
"github.com/openshift/machine-config-operator/pkg/daemon/constants"
mcfginformersv1 "github.com/openshift/machine-config-operator/pkg/generated/informers/externalversions/machineconfiguration.openshift.io/v1"
mcfglistersv1 "github.com/openshift/machine-config-operator/pkg/generated/listers/machineconfiguration.openshift.io/v1"
)
// 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 OperatingSystem
// mock is set if we're running as non-root, probably under unit tests
mock bool
// NodeUpdaterClient an instance of the client which interfaces with host content deployments
NodeUpdaterClient NodeUpdaterClient
// 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
// kubeClient allows interaction with Kubernetes, including the node we are running on.
kubeClient kubernetes.Interface
// recorder sends events to the apiserver
recorder record.EventRecorder
// nodeLister is used to watch for updates via the informer
nodeLister corev1lister.NodeLister
nodeListerSynced cache.InformerSynced
mcLister mcfglistersv1.MachineConfigLister
mcListerSynced 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
// 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.RateLimitingInterface
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
currentConfigPath string
loggerSupportsJournal bool
drainer *drain.Helper
}
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"
// pendingStateMessageID is the id we store the pending state in journal. We use it to
// also retrieve the pending config after a reboot
pendingStateMessageID = "machine-config-daemon-pending-state"
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
)
type onceFromOrigin int
const (
onceFromUnknownConfig onceFromOrigin = iota
onceFromLocalConfig
onceFromRemoteConfig
)
var (
defaultRebootTimeout = 24 * time.Hour
)
// rebootCommand creates a new transient systemd unit to reboot the system.
// We explicitly try to stop kubelet.service first, before anything else; this
// way we ensure the rest of system stays running, because kubelet may need
// to do "graceful" shutdown by e.g. de-registering with a load balancer.
// However note we use `;` instead of `&&` so we keep rebooting even
// if kubelet failed to shutdown - that way the machine will still eventually reboot
// as systemd will time out the stop invocation.
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 stop kubelet.service; systemctl reboot")
}
// getBootID loads the unique "boot id" which is generated by the Linux kernel.
func getBootID() (string, error) {
currentBootIDBytes, err := ioutil.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(
nodeUpdaterClient NodeUpdaterClient,
exitCh chan<- error,
) (*Daemon, error) {
mock := false
if os.Getuid() != 0 {
mock = true
}
var (
osImageURL string
osVersion string
err error
)
hostos := OperatingSystem{}
if !mock {
hostos, err = GetHostRunningOS()
if err != nil {
HostOS.WithLabelValues("unsupported", "").Set(1)
return nil, errors.Wrapf(err, "checking operating system")
}
}
// Only pull the osImageURL from OSTree when we are on RHCOS or FCOS
if hostos.IsCoreOSVariant() {
err := nodeUpdaterClient.Initialize()
if err != nil {
return nil, fmt.Errorf("error initializing rpm-ostree: %v", err)
}
osImageURL, osVersion, err = nodeUpdaterClient.GetBootedOSImageURL()
if err != nil {
return nil, fmt.Errorf("error reading osImageURL from rpm-ostree: %v", err)
}
glog.Infof("Booted osImageURL: %s (%s)", osImageURL, osVersion)
}
bootID := ""
if !mock {
bootID, err = getBootID()
if err != nil {
return nil, errors.Wrapf(err, "failed to read boot ID")
}
}
// RHEL 7.6/Centos 7 logger (util-linux) doesn't have the --journald flag
loggerSupportsJournal := true
if !mock {
if hostos.IsLikeTraditionalRHEL7() {
loggerOutput, err := exec.Command("logger", "--help").CombinedOutput()
if err != nil {
return nil, errors.Wrapf(err, "running logger --help")
}
loggerSupportsJournal = strings.Contains(string(loggerOutput), "--journald")
}
}
// report OS & version (if RHCOS or FCOS) to prometheus
HostOS.WithLabelValues(hostos.ToPrometheusLabel(), osVersion).Set(1)
return &Daemon{
mock: mock,
booting: true,
os: hostos,
NodeUpdaterClient: nodeUpdaterClient,
bootedOSImageURL: osImageURL,
bootID: bootID,
exitCh: exitCh,
currentConfigPath: currentConfigPath,
loggerSupportsJournal: loggerSupportsJournal,
}, nil
}
// ClusterConnect sets up the systemd and kubernetes connections needed to update the
// machine.
func (dn *Daemon) ClusterConnect(
name string,
kubeClient kubernetes.Interface,
mcInformer mcfginformersv1.MachineConfigInformer,
nodeInformer coreinformersv1.NodeInformer,
kubeletHealthzEnabled bool,
kubeletHealthzEndpoint string,
) {
dn.name = name
dn.kubeClient = kubeClient
dn.nodeWriter = newNodeWriter()
go dn.nodeWriter.Run(dn.stopCh)
// 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.NewNamedRateLimitingQueue(workqueue.NewMaxOfRateLimiter(
&workqueue.BucketRateLimiter{Limiter: rate.NewLimiter(rate.Limit(updateDelay), 1)},
workqueue.NewItemExponentialFailureRateLimiter(1*time.Second, maxUpdateBackoff)), "machineconfigdaemon")
eventBroadcaster := record.NewBroadcaster()
eventBroadcaster.StartLogging(glog.V(2).Infof)
eventBroadcaster.StartRecordingToSink(&corev1client.EventSinkImpl{Interface: dn.kubeClient.CoreV1().Events("")})
dn.recorder = eventBroadcaster.NewRecorder(scheme.Scheme, corev1.EventSource{Component: "machineconfigdaemon", Host: dn.name})
go dn.runLoginMonitor(dn.stopCh, dn.exitCh)
nodeInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{
AddFunc: dn.handleNodeEvent,
UpdateFunc: func(oldObj, newObj interface{}) { dn.handleNodeEvent(newObj) },
})
dn.nodeLister = nodeInformer.Lister()
dn.nodeListerSynced = nodeInformer.Informer().HasSynced
dn.mcLister = mcInformer.Lister()
dn.mcListerSynced = mcInformer.Informer().HasSynced
dn.enqueueNode = dn.enqueueDefault
dn.syncHandler = dn.syncNode
dn.kubeletHealthzEnabled = kubeletHealthzEnabled
dn.kubeletHealthzEndpoint = kubeletHealthzEndpoint
dn.drainer = &drain.Helper{
Client: dn.kubeClient,
Force: true,
IgnoreAllDaemonSets: true,
DeleteEmptyDirData: true,
GracePeriodSeconds: -1,
Timeout: 90 * time.Second,
OnPodDeletedOrEvicted: func(pod *corev1.Pod, usingEviction bool) {
verbStr := "Deleted"
if usingEviction {
verbStr = "Evicted"
}
glog.Infof("%s pod %s/%s", verbStr, pod.Namespace, pod.Name)
},
Out: writer{glog.Info},
ErrOut: writer{glog.Error},
Ctx: context.TODO(),
}
}
// writer implements io.Writer interface as a pass-through for klog.
type writer struct {
logFunc func(args ...interface{})
}
// Write passes string(p) into writer's logFunc and always returns len(p)
func (w writer) Write(p []byte) (n int, err error) {
w.logFunc(string(p))
return len(p), nil
}
// 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.(string))
dn.handleErr(err, key)
return true
}
func (dn *Daemon) handleErr(err error, key interface{}) {
if err == nil {
dn.queue.Forget(key)
return
}
dn.updateErrorState(err)
// This is at V(2) since the updateErrorState() call above ends up logging too
glog.V(2).Infof("Error syncing node %v (retries %d): %v", key, dn.queue.NumRequeues(key), err)
dn.queue.AddRateLimited(key)
}
func (dn *Daemon) updateErrorState(err error) {
switch errors.Cause(err) {
case errUnreconcilable:
dn.nodeWriter.SetUnreconcilable(err, dn.kubeClient.CoreV1().Nodes(), dn.nodeLister, dn.name)
default:
dn.nodeWriter.SetDegraded(err, dn.kubeClient.CoreV1().Nodes(), dn.nodeLister, dn.name)
}
}
// 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 {
glog.Infof("Node %s is part of the control plane", dn.node.Name)
if err := dn.initializeControlPlane(); err != nil {
return err
}
dn.isControlPlane = true
} else {
glog.Infof("Node %s is not labeled %s", dn.node.Name, ctrlcommon.MasterLabel)
}
dn.nodeInitialized = true
return nil
}
func (dn *Daemon) syncNode(key string) error {
startTime := time.Now()
glog.V(4).Infof("Started syncing node %q (%v)", key, startTime)
defer func() {
glog.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) {
glog.V(2).Infof("node %v has been deleted", key)
return nil
}
if err != nil {
return err
}
// Check for Deleted Node
if node.DeletionTimestamp != nil {
glog.Infof("Node %s was deleted!", node.Name)
return nil
}
// 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 {
dn.node = node
}
// 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 := 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
return nil
}
// Pass to the shared update prep method
current, desired, err := dn.prepUpdateFromCluster()
if err != nil {
return errors.Wrapf(err, "prepping update")
}
if current != nil || desired != nil {
if err := dn.triggerUpdateWithMachineConfig(current, desired); err != nil {
return err
}
}
glog.V(2).Infof("Node %s is already synced", node.Name)
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: %v", node, err))
return
}
dn.queue.AddRateLimited(key)
}
const (
logindUnit = "systemd-logind.service"
// IDs are taken from https://cgit.freedesktop.org/systemd/systemd/plain/src/systemd/sd-messages.h
sdMessageSessionStart = "8d45620c1a4348dbb17410da57c60c66"
)
// detectEarlySSHAccessesFromBoot annotates the node if we find a login before the daemon started up.
func (dn *Daemon) detectEarlySSHAccessesFromBoot() error {
journalOutput, err := exec.Command("journalctl", "-b", "-o", "cat", "-u", logindUnit, "MESSAGE_ID="+sdMessageSessionStart).CombinedOutput()
if err != nil {
return err
}
if len(journalOutput) > 0 {
glog.Info("Detected a login session before the daemon took over on first boot")
glog.Infof("Applying annotation: %v", machineConfigDaemonSSHAccessAnnotationKey)
if err := dn.applySSHAccessedAnnotation(); err != nil {
return err
}
}
return nil
}
// RunOnceFrom is the primary entrypoint for the non-cluster case
func (dn *Daemon) RunOnceFrom(onceFrom string, skipReboot bool) error {
dn.skipReboot = skipReboot
configi, contentFrom, err := dn.senseAndLoadOnceFrom(onceFrom)
if err != nil {
glog.Warningf("Unable to decipher onceFrom config type: %s", err)
return err
}
switch c := configi.(type) {
case ign3types.Config:
glog.V(2).Info("Daemon running directly from Ignition")
return dn.runOnceFromIgnition(c)
case mcfgv1.MachineConfig:
glog.V(2).Info("Daemon running directly from MachineConfig")
return dn.runOnceFromMachineConfig(c, contentFrom)
}
return errors.New("unsupported onceFrom type provided")
}
// RunFirstbootCompleteMachineconfig is run via systemd on the first boot
// to complete processing of the target MachineConfig.
func (dn *Daemon) RunFirstbootCompleteMachineconfig() error {
data, err := ioutil.ReadFile(constants.MachineConfigEncapsulatedPath)
if err != nil {
return err
}
var mc mcfgv1.MachineConfig
err = json.Unmarshal(data, &mc)
if err != nil {
return errors.Wrapf(err, "failed to parse MachineConfig")
}
// Start with an empty config, then add our *booted* osImageURL to
// it, reflecting the current machine state.
oldConfig := canonicalizeEmptyMC(nil)
oldConfig.Spec.OSImageURL = dn.bootedOSImageURL
// Currently, we generally expect the bootimage to be older, but in the special
// case of having bootimage == machine-os-content, and no kernel arguments
// specified, then we don't need to do anything here.
mcDiffNotEmpty, err := dn.compareMachineConfig(oldConfig, &mc)
if err != nil {
return errors.Wrapf(err, "failed to compare MachineConfig")
}
if !mcDiffNotEmpty {
// Removing this file signals completion of the initial MC processing.
if err := os.Remove(constants.MachineConfigEncapsulatedPath); err != nil {
return errors.Wrapf(err, "failed to remove %s", constants.MachineConfigEncapsulatedPath)
}
return nil
}
dn.skipReboot = true
err = dn.update(nil, &mc)
if err != nil {
return err
}
// Removing this file signals completion of the initial MC processing.
if err := os.Rename(constants.MachineConfigEncapsulatedPath, constants.MachineConfigEncapsulatedBakPath); err != nil {
return errors.Wrap(err, "failed to rename encapsulated MachineConfig after processing on firstboot")
}
dn.skipReboot = false
return dn.reboot(fmt.Sprintf("Completing firstboot provisioning to %s", mc.GetName()))
}
// InstallSignalHandler installs the handler for the signals the daemon should act on
func (dn *Daemon) InstallSignalHandler(signaled chan struct{}) {
termChan := make(chan os.Signal, 2048)
signal.Notify(termChan, syscall.SIGTERM)
// Catch SIGTERM - if we're actively updating, we should avoid
// having the process be killed.
// https://github.com/openshift/machine-config-operator/issues/407
go func() {
for sig := range termChan {
//nolint:gocritic
switch sig {
case syscall.SIGTERM:
dn.updateActiveLock.Lock()
updateActive := dn.updateActive
dn.updateActiveLock.Unlock()
if updateActive {
glog.Info("Got SIGTERM, but actively updating")
} else {
close(signaled)
return
}
}
}
}()
}
// Run finishes informer setup and then blocks, and the informer will be
// responsible for triggering callbacks to handle updates. Successful
// updates shouldn't return, and should just reboot the node.
func (dn *Daemon) Run(stopCh <-chan struct{}, exitCh <-chan error) error {
dn.logSystem("Starting to manage node: %s", dn.name)
dn.LogSystemData()
glog.Info("Starting MachineConfigDaemon")
defer glog.Info("Shutting down MachineConfigDaemon")
signaled := make(chan struct{})
dn.InstallSignalHandler(signaled)
if dn.kubeletHealthzEnabled {
glog.Info("Enabling Kubelet Healthz Monitor")
go dn.runKubeletHealthzMonitor(stopCh, dn.exitCh)
}
defer utilruntime.HandleCrash()
defer dn.queue.ShutDown()
if !cache.WaitForCacheSync(stopCh, dn.nodeListerSynced, dn.mcListerSynced) {
return errors.New("failed to sync initial listers cache")
}
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 loginmonitor and kubehealth
glog.Warningf("Got an error from auxiliary tools: %v", err)
}
}
}
func (dn *Daemon) runLoginMonitor(stopCh <-chan struct{}, exitCh chan<- error) {
cmd := exec.Command("journalctl", "-b", "-f", "-o", "cat", "-u", logindUnit, "MESSAGE_ID="+sdMessageSessionStart)
stdout, err := cmd.StdoutPipe()
if err != nil {
exitCh <- err
return
}
if err := cmd.Start(); err != nil {
exitCh <- err
return
}
worker := make(chan struct{})
go func() {
for {
select {
case <-worker:
return
default:
buf := make([]byte, 1024)
l, err := stdout.Read(buf)
if err != nil {
if err == io.EOF {
return
}
exitCh <- err
return
}
if l > 0 {
line := strings.Split(string(buf), "\n")[0]
glog.Infof("Detected a new login session: %s", line)
glog.Infof("Login access is discouraged! Applying annotation: %v", machineConfigDaemonSSHAccessAnnotationKey)
if err := dn.applySSHAccessedAnnotation(); err != nil {
exitCh <- err
}
}
}
}
}()
<-stopCh
close(worker)
cmd.Process.Kill()
}
func (dn *Daemon) applySSHAccessedAnnotation() error {
if err := dn.nodeWriter.SetSSHAccessed(dn.kubeClient.CoreV1().Nodes(), dn.nodeLister, dn.name); err != nil {
return fmt.Errorf("error: cannot apply annotation for SSH access due to: %v", err)
}
return nil
}
func (dn *Daemon) runKubeletHealthzMonitor(stopCh <-chan struct{}, exitCh chan<- error) {
failureCount := 0
KubeletHealthState.Set(float64(failureCount))
for {
select {
case <-stopCh:
return
case <-time.After(kubeletHealthzPollingInterval):
err := dn.getHealth()
if err != nil {
failureCount++
exitCh <- fmt.Errorf("kubelet health check has failed %d times: %v", failureCount, err)
} else {
// reset failure count on success
failureCount = 0
}
KubeletHealthState.Set(float64(failureCount))
}
}
}
func (dn *Daemon) getHealth() error {
glog.V(2).Info("Kubelet health running")
ctx, cancel := context.WithTimeout(context.Background(), kubeletHealthzTimeout)
defer cancel()
req, err := http.NewRequest("GET", dn.kubeletHealthzEndpoint, nil)
if err != nil {
return err
}
req = req.WithContext(ctx)
client := http.Client{}
resp, err := client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
respData, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
if string(respData) != "ok" {
glog.Warningf("Kubelet Healthz Endpoint returned: %s", string(respData))
return nil
}
glog.V(2).Info("Kubelet health ok")
return nil
}
// stateAndConfigs is the "state" node annotation plus parsed machine configs
// referenced by the currentConfig and desiredConfig annotations. If we have
// a "pending" config (we're coming up after a reboot attempting to apply a config),
// we'll load that as well - otherwise it will be nil.
//
// If any of the object names are the same, they will be pointer-equal.
type stateAndConfigs struct {
bootstrapping bool
state string
currentConfig *mcfgv1.MachineConfig
pendingConfig *mcfgv1.MachineConfig
desiredConfig *mcfgv1.MachineConfig
}
func (dn *Daemon) getStateAndConfigs(pendingConfigName string) (*stateAndConfigs, error) {
_, err := os.Lstat(constants.InitialNodeAnnotationsFilePath)
var bootstrapping bool
if err != nil {
if !os.IsNotExist(err) {
return nil, err
}
// The node annotation file (laid down by the MCS)
// doesn't exist, we must not be bootstrapping
} else {
bootstrapping = true
glog.Info("In bootstrap mode")
}
currentConfigName, err := getNodeAnnotation(dn.node, constants.CurrentMachineConfigAnnotationKey)
if err != nil {
return nil, err
}
desiredConfigName, err := getNodeAnnotation(dn.node, constants.DesiredMachineConfigAnnotationKey)
if err != nil {
return nil, err
}
currentConfig, err := dn.mcLister.Get(currentConfigName)
if err != nil {
return nil, err
}
state, err := getNodeAnnotationExt(dn.node, constants.MachineConfigDaemonStateAnnotationKey, true)
if err != nil {
return nil, err
}
// Temporary hack: the MCS used to not write the state=done annotation
// key. If it's unset, let's write it now.
if state == "" {
state = constants.MachineConfigDaemonStateDone
}
var desiredConfig *mcfgv1.MachineConfig
if currentConfigName == desiredConfigName {
desiredConfig = currentConfig
glog.Infof("Current+desired config: %s", currentConfigName)
} else {
desiredConfig, err = dn.mcLister.Get(desiredConfigName)
if err != nil {
return nil, err
}
glog.Infof("Current config: %s", currentConfigName)
glog.Infof("Desired config: %s", desiredConfigName)
}
var pendingConfig *mcfgv1.MachineConfig
// We usually expect that if current != desired, pending == desired; however,
// it can happen that desiredConfig changed while we were rebooting.
if pendingConfigName == desiredConfigName {
pendingConfig = desiredConfig
} else if pendingConfigName != "" {
pendingConfig, err = dn.mcLister.Get(pendingConfigName)
if err != nil {
return nil, err
}
glog.Infof("Pending config: %s", pendingConfigName)
}
var degradedReason string
if state == constants.MachineConfigDaemonStateDegraded {
degradedReason, err = getNodeAnnotation(dn.node, constants.MachineConfigDaemonReasonAnnotationKey)
if err != nil {
glog.Errorf("Could not retrieve degraded reason. err: %v", err)
}
}
MCDState.WithLabelValues(state, degradedReason).SetToCurrentTime()
return &stateAndConfigs{
bootstrapping: bootstrapping,
currentConfig: currentConfig,
pendingConfig: pendingConfig,
desiredConfig: desiredConfig,
state: state,
}, nil
}
// LogSystemData gathers data from the OS and adds it to our stdout; should only
// be called once on MCD startup to log things which generally shouldn't change
// dynamically after a reboot.
func (dn *Daemon) LogSystemData() {
// Print status if available
if dn.os.IsCoreOSVariant() {
status, err := dn.NodeUpdaterClient.GetStatus()
if err != nil {
glog.Fatalf("unable to get rpm-ostree status: %s", err)
}
glog.Info(status)
}
boots, err := runGetOut("journalctl", "--list-boots")
if err != nil {
glog.Errorf("Listing boots: %v", err)
}
glog.Infof("journalctl --list-boots:\n" + string(boots))
// Since nothing in the cluster today watches systemd units, let's
// at least capture them in our logs to start. See also
// https://github.com/openshift/machine-config-operator/issues/1365
// This only captures units that started *before* the MCD, we need
// to also watch dynamically of course.
//
// also xref https://github.com/coreos/console-login-helper-messages/blob/e8a849f4c23910e7c556c10719911cc59873fc23/usr/share/console-login-helper-messages/profile.sh
failedServices, err := runGetOut("systemctl", "list-units", "--state=failed", "--no-legend")
if err != nil {
glog.Errorf("Listing failed systemd services: %v", err)
} else if len(failedServices) > 0 {
glog.Infof("systemctl --failed:\n" + string(failedServices))
} else {
glog.Info("systemd service state: OK")
}
}
const (
pendingConfigPath = "/etc/machine-config-daemon/state.json"
)
type pendingConfigState struct {
PendingConfig string `json:"pendingConfig,omitempty"`
BootID string `json:"bootID,omitempty"`
}
// XXX: drop this
func (dn *Daemon) writePendingConfig(desiredConfig *mcfgv1.MachineConfig) error {
t := &pendingConfigState{
PendingConfig: desiredConfig.GetName(),
BootID: dn.bootID,
}
b, err := json.Marshal(t)
if err != nil {
return err
}
return writeFileAtomicallyWithDefaults(pendingConfigPath, b)
}
// XXX: drop this
// we need this compatibility layer for now
func (dn *Daemon) getPendingConfig() (*pendingConfigState, error) {
s, err := ioutil.ReadFile("/etc/machine-config-daemon/state.json")
if err != nil {
if !os.IsNotExist(err) {
return nil, errors.Wrapf(err, "loading transient state")
}
return nil, nil
}
var p pendingConfigState
if err := json.Unmarshal(s, &p); err != nil {
return nil, errors.Wrapf(err, "parsing transient state")
}
return &p, nil
}
func (dn *Daemon) getCurrentConfigOnDisk() (*mcfgv1.MachineConfig, error) {
mcJSON, err := os.Open(dn.currentConfigPath)
if err != nil {
return nil, err
}
defer mcJSON.Close()
currentOnDisk := &mcfgv1.MachineConfig{}
if err := json.NewDecoder(bufio.NewReader(mcJSON)).Decode(currentOnDisk); err != nil {
return nil, err
}
return currentOnDisk, nil
}
func (dn *Daemon) storeCurrentConfigOnDisk(current *mcfgv1.MachineConfig) error {
mcJSON, err := json.Marshal(current)
if err != nil {
return err
}
return writeFileAtomicallyWithDefaults(dn.currentConfigPath, mcJSON)
}
// https://bugzilla.redhat.com/show_bug.cgi?id=1842906
// If we didn't successfully complete -firstboot.service, because
// 4.5 and newer removed the BindsTo=, the service may start downgrading
// things. At this point we should have already applied all target
// changes, so just rename the file to .bak the same as the -firstboot
// path does.
func upgradeHackFor44AndBelow() error {
_, err := os.Stat(constants.MachineConfigEncapsulatedPath)
if err == nil {
glog.Warningf("Failed to complete machine-config-daemon-firstboot before joining cluster!")
// Removing this file signals completion of the initial MC processing.
if err := os.Rename(constants.MachineConfigEncapsulatedPath, constants.MachineConfigEncapsulatedBakPath); err != nil {
return errors.Wrap(err, "failed to rename encapsulated MachineConfig after processing on firstboot")
}
}
return nil
}
// Remove artifacts used by ignition, that the MCO should no longer
// use since the machine is up.
// Currently removes the systemd preset file written by Ignition.
func removeIgnitionArtifacts() error {
if err := os.Remove(constants.IgnitionSystemdPresetFile); err != nil && !os.IsNotExist(err) {
return errors.Wrap(err, "failed to remove Ignition-written systemd preset file")
}
return nil
}
// checkStateOnFirstRun is a core entrypoint for our state machine.
// It determines whether we're in our desired state, or if we're
// transitioning between states, and whether or not we need to update
// to a new state. It also checks if someone jumped on a node before
// the daemon took over.
//
// Some more background in this PR: https://github.com/openshift/machine-config-operator/pull/245
//nolint:gocyclo
func (dn *Daemon) checkStateOnFirstRun() error {
node, err := dn.loadNodeAnnotations(dn.node)
if err != nil {
return err
}
// Update our cached copy
dn.node = node
pendingState, err := dn.getPendingState()
if err != nil {
return err
}
var pendingConfigName, bootID string
if pendingState != nil {
pendingConfigName = pendingState.Message
bootID = pendingState.BootID
}
// XXX: drop this
// we need this compatibility layer for now
if pendingState == nil {