-
Notifications
You must be signed in to change notification settings - Fork 410
/
update.go
1906 lines (1692 loc) · 66.7 KB
/
update.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"
"fmt"
"io/ioutil"
"os"
"os/exec"
"os/user"
"path/filepath"
"reflect"
"strconv"
"strings"
"syscall"
"time"
"github.com/clarketm/json"
ign3types "github.com/coreos/ignition/v2/config/v3_2/types"
"github.com/golang/glog"
"github.com/google/renameio"
errors "github.com/pkg/errors"
"github.com/vincent-petithory/dataurl"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/util/uuid"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/kubectl/pkg/drain"
mcfgv1 "github.com/openshift/machine-config-operator/pkg/apis/machineconfiguration.openshift.io/v1"
ctrlcommon "github.com/openshift/machine-config-operator/pkg/controller/common"
"github.com/openshift/machine-config-operator/pkg/daemon/constants"
pivottypes "github.com/openshift/machine-config-operator/pkg/daemon/pivot/types"
pivotutils "github.com/openshift/machine-config-operator/pkg/daemon/pivot/utils"
)
const (
// defaultDirectoryPermissions houses the default mode to use when no directory permissions are provided
defaultDirectoryPermissions os.FileMode = 0755
// defaultFilePermissions houses the default mode to use when no file permissions are provided
defaultFilePermissions os.FileMode = 0644
// coreUser is "core" and currently the only permissible user name
coreUserName = "core"
// SSH Keys for user "core" will only be written at /home/core/.ssh
coreUserSSHPath = "/home/core/.ssh/"
// fipsFile is the file to check if FIPS is enabled
fipsFile = "/proc/sys/crypto/fips_enabled"
extensionsRepo = "/etc/yum.repos.d/coreos-extensions.repo"
osImageContentBaseDir = "/run/mco-machine-os-content/"
// These are the actions for a node to take after applying config changes. (e.g. a new machineconfig is applied)
// "None" means no special action needs to be taken. A drain will still happen.
// This currently happens when ssh keys or pull secret (/var/lib/kubelet/config.json) is changed
postConfigChangeActionNone = "none"
// Rebooting is still the default scenario for any other change
postConfigChangeActionReboot = "reboot"
// Crio reload will happen when /etc/containers/registries.conf is changed. This will cause
// a "systemctl reload crio"
postConfigChangeActionReloadCrio = "reload crio"
)
func writeFileAtomicallyWithDefaults(fpath string, b []byte) error {
return writeFileAtomically(fpath, b, defaultDirectoryPermissions, defaultFilePermissions, -1, -1)
}
// writeFileAtomically uses the renameio package to provide atomic file writing, we can't use renameio.WriteFile
// directly since we need to 1) Chown 2) go through a buffer since files provided can be big
func writeFileAtomically(fpath string, b []byte, dirMode, fileMode os.FileMode, uid, gid int) error {
dir := filepath.Dir(fpath)
if err := os.MkdirAll(dir, dirMode); err != nil {
return fmt.Errorf("failed to create directory %q: %v", filepath.Dir(fpath), err)
}
t, err := renameio.TempFile(dir, fpath)
if err != nil {
return err
}
defer t.Cleanup()
// Set permissions before writing data, in case the data is sensitive.
if err := t.Chmod(fileMode); err != nil {
return err
}
w := bufio.NewWriter(t)
if _, err := w.Write(b); err != nil {
return err
}
if err := w.Flush(); err != nil {
return err
}
if uid != -1 && gid != -1 {
if err := t.Chown(uid, gid); err != nil {
return err
}
}
return t.CloseAtomicallyReplace()
}
func getNodeRef(node *corev1.Node) *corev1.ObjectReference {
return &corev1.ObjectReference{
Kind: "Node",
Name: node.GetName(),
UID: node.GetUID(),
}
}
func reloadService(name string) error {
_, err := runGetOut("systemctl", "reload", name)
return err
}
// performPostConfigChangeAction takes action based on what postConfigChangeAction has been asked.
// For non-reboot action, it applies configuration, updates node's config and state.
// In the end uncordon node to schedule workload.
// If at any point an error occurs, we reboot the node so that node has correct configuration.
func (dn *Daemon) performPostConfigChangeAction(postConfigChangeActions []string, configName string) error {
if ctrlcommon.InSlice(postConfigChangeActionReboot, postConfigChangeActions) {
dn.logSystem("Rebooting node")
return dn.reboot(fmt.Sprintf("Node will reboot into config %s", configName))
}
if ctrlcommon.InSlice(postConfigChangeActionNone, postConfigChangeActions) {
if dn.recorder != nil {
dn.recorder.Eventf(getNodeRef(dn.node), corev1.EventTypeNormal, "SkipReboot", "Config changes do not require reboot.")
}
dn.logSystem("Node has Desired Config %s, skipping reboot", configName)
}
if ctrlcommon.InSlice(postConfigChangeActionReloadCrio, postConfigChangeActions) {
serviceName := "crio"
if err := reloadService(serviceName); err != nil {
if dn.recorder != nil {
dn.recorder.Eventf(getNodeRef(dn.node), corev1.EventTypeWarning, "FailedServiceReload", fmt.Sprintf("Reloading %s service failed. Error: %v", serviceName, err))
}
dn.logSystem("Reloading %s configuration failed, node will reboot instead. Error: %v", serviceName, err)
dn.reboot(fmt.Sprintf("Node will reboot into config %s", configName))
}
if dn.recorder != nil {
dn.recorder.Eventf(getNodeRef(dn.node), corev1.EventTypeNormal, "SkipReboot", "Config changes do not require reboot. Service %s was reloaded.", serviceName)
}
dn.logSystem("%s config reloaded successfully! Desired config %s has been applied, skipping reboot", serviceName, configName)
}
// We are here, which means reboot was not needed to apply the configuration.
// Get current state of node, in case of an error reboot
state, err := dn.getStateAndConfigs(configName)
if err != nil {
glog.Errorf("Error processing state and configs, node will reboot instead. Error: %v", err)
return dn.reboot(fmt.Sprintf("Node will reboot into config %s", configName))
}
var inDesiredConfig bool
if inDesiredConfig, err = dn.updateConfigAndState(state); err != nil {
glog.Errorf("Setting node's state to Done failed, node will reboot instead. Error: %v", err)
return dn.reboot(fmt.Sprintf("Node will reboot into config %s", configName))
}
if inDesiredConfig {
return nil
}
// currentConfig != desiredConfig, kick off an update
return dn.triggerUpdateWithMachineConfig(state.currentConfig, state.desiredConfig)
}
// finalizeBeforeReboot is the last step in an update() and then we take appropriate postConfigChangeAction.
// It can also be called as a special case for the "bootstrap pivot".
func (dn *Daemon) finalizeBeforeReboot(newConfig *mcfgv1.MachineConfig) (retErr error) {
if out, err := dn.storePendingState(newConfig, 1); err != nil {
return errors.Wrapf(err, "failed to log pending config: %s", string(out))
}
defer func() {
if retErr != nil {
if dn.recorder != nil {
dn.recorder.Eventf(getNodeRef(dn.node), corev1.EventTypeNormal, "PendingConfigRollBack", fmt.Sprintf("Rolling back pending config %s: %v", newConfig.GetName(), retErr))
}
if out, err := dn.storePendingState(newConfig, 0); err != nil {
retErr = errors.Wrapf(retErr, "error rolling back pending config %v: %s", err, string(out))
return
}
}
}()
if dn.recorder != nil {
dn.recorder.Eventf(getNodeRef(dn.node), corev1.EventTypeNormal, "PendingConfig", fmt.Sprintf("Written pending config %s", newConfig.GetName()))
}
return nil
}
func (dn *Daemon) drain() error {
// Skip draining of the node when we're not cluster driven
if dn.kubeClient == nil {
return nil
}
MCDDrainErr.WithLabelValues(dn.node.Name, "").Set(0)
dn.logSystem("Update prepared; beginning drain")
startTime := time.Now()
dn.recorder.Eventf(getNodeRef(dn.node), corev1.EventTypeNormal, "Drain", "Draining node to update config.")
backoff := wait.Backoff{
Steps: 5,
Duration: 10 * time.Second,
Factor: 2,
}
var lastErr error
if err := wait.ExponentialBackoff(backoff, func() (bool, error) {
err := drain.RunCordonOrUncordon(dn.drainer, dn.node, true)
if err != nil {
lastErr = err
glog.Infof("Cordon failed with: %v, retrying", err)
return false, nil
}
err = drain.RunNodeDrain(dn.drainer, dn.node.Name)
if err == nil {
return true, nil
}
lastErr = err
glog.Infof("Draining failed with: %v, retrying", err)
return false, nil
}); err != nil {
if err == wait.ErrWaitTimeout {
failMsg := fmt.Sprintf("%d tries: %v", backoff.Steps, lastErr)
MCDDrainErr.WithLabelValues(dn.node.Name, "WaitTimeout").Set(float64(backoff.Steps))
dn.recorder.Eventf(getNodeRef(dn.node), corev1.EventTypeWarning, "FailedToDrain", failMsg)
return errors.Wrapf(lastErr, "failed to drain node (%d tries): %v", backoff.Steps, err)
}
MCDDrainErr.WithLabelValues(dn.node.Name, "UnknownError").Set(float64(backoff.Steps))
dn.recorder.Eventf(getNodeRef(dn.node), corev1.EventTypeWarning, "FailedToDrain", err.Error())
return errors.Wrap(err, "failed to drain node")
}
dn.logSystem("drain complete")
t := time.Since(startTime).Seconds()
glog.Infof("Successful drain took %v seconds", t)
MCDDrainErr.WithLabelValues(dn.node.Name, "").Set(0)
return nil
}
var errUnreconcilable = errors.New("unreconcilable")
func canonicalizeEmptyMC(config *mcfgv1.MachineConfig) *mcfgv1.MachineConfig {
if config != nil {
return config
}
newIgnCfg := ctrlcommon.NewIgnConfig()
rawNewIgnCfg, err := json.Marshal(newIgnCfg)
if err != nil {
// This should never happen
panic(err)
}
return &mcfgv1.MachineConfig{
ObjectMeta: metav1.ObjectMeta{Name: "mco-empty-mc"},
Spec: mcfgv1.MachineConfigSpec{
Config: runtime.RawExtension{
Raw: rawNewIgnCfg,
},
},
}
}
// return true if the machineConfigDiff is not empty
func (dn *Daemon) compareMachineConfig(oldConfig, newConfig *mcfgv1.MachineConfig) (bool, error) {
oldConfig = canonicalizeEmptyMC(oldConfig)
oldConfigName := oldConfig.GetName()
newConfigName := newConfig.GetName()
mcDiff, err := newMachineConfigDiff(oldConfig, newConfig)
if err != nil {
return true, errors.Wrapf(err, "error creating machineConfigDiff for comparison")
}
if mcDiff.isEmpty() {
glog.Infof("No changes from %s to %s", oldConfigName, newConfigName)
return false, nil
}
return true, nil
}
// addExtensionsRepo adds a repo into /etc/yum.repos.d/ which we use later to
// install extensions and rt-kernel
func addExtensionsRepo(osImageContentDir string) error {
repoContent := "[coreos-extensions]\nenabled=1\nmetadata_expire=1m\nbaseurl=" + osImageContentDir + "/extensions/\ngpgcheck=0\nskip_if_unavailable=False\n"
if err := writeFileAtomicallyWithDefaults(extensionsRepo, []byte(repoContent)); err != nil {
return err
}
return nil
}
// podmanRemove kills and removes a container
func podmanRemove(cid string) {
// Ignore errors here
exec.Command("podman", "kill", cid).Run()
exec.Command("podman", "rm", "-f", cid).Run()
}
func podmanCopy(imgURL, osImageContentDir string) (err error) {
// make sure that osImageContentDir doesn't exist
os.RemoveAll(osImageContentDir)
// Pull the container image
var authArgs []string
if _, err := os.Stat(kubeletAuthFile); err == nil {
authArgs = append(authArgs, "--authfile", kubeletAuthFile)
}
args := []string{"pull", "-q"}
args = append(args, authArgs...)
args = append(args, imgURL)
_, err = pivotutils.RunExtBackground(numRetriesNetCommands, "podman", args...)
if err != nil {
return
}
// create a container
var cidBuf []byte
containerName := pivottypes.PivotNamePrefix + string(uuid.NewUUID())
cidBuf, err = runGetOut("podman", "create", "--net=none", "--annotation=org.openshift.machineconfigoperator.pivot=true", "--name", containerName, imgURL)
if err != nil {
return
}
// only delete created container, we will delete container image later as we may need it for podmanInspect()
defer podmanRemove(containerName)
// copy the content from create container locally into a temp directory under /run/machine-os-content/
cid := strings.TrimSpace(string(cidBuf))
args = []string{"cp", fmt.Sprintf("%s:/", cid), osImageContentDir}
_, err = pivotutils.RunExtBackground(numRetriesNetCommands, "podman", args...)
// Set selinux context to var_run_t to avoid selinux denial
args = []string{"-R", "-t", "var_run_t", osImageContentDir}
_, err = runGetOut("chcon", args...)
if err != nil {
glog.Infof("Error changing selinux context on path %s %v", osImageContentDir, err)
return
}
return
}
// ExtractOSImage extracts OS image content in a temporary directory under /run/machine-os-content/
// and returns the path on successful extraction.
// Note that since we do this in the MCD container, cluster proxy configuration must also be injected
// into the container. See the MCD daemonset.
func ExtractOSImage(imgURL string) (osImageContentDir string, err error) {
var registryConfig []string
if _, err := os.Stat(kubeletAuthFile); err == nil {
registryConfig = append(registryConfig, "--registry-config", kubeletAuthFile)
}
if err = os.MkdirAll(osImageContentBaseDir, 0755); err != nil {
err = fmt.Errorf("error creating directory %s: %v", osImageContentBaseDir, err)
return
}
if osImageContentDir, err = ioutil.TempDir(osImageContentBaseDir, "os-content-"); err != nil {
return
}
if err = os.MkdirAll(osImageContentDir, 0755); err != nil {
err = fmt.Errorf("error creating directory %s: %v", osImageContentDir, err)
return
}
// Extract the image
args := []string{"image", "extract", "--path", "/:" + osImageContentDir}
args = append(args, registryConfig...)
args = append(args, imgURL)
if _, err = pivotutils.RunExtBackground(cmdRetriesCount, "oc", args...); err != nil {
// Workaround fixes for the environment where oc image extract fails.
// See https://bugzilla.redhat.com/show_bug.cgi?id=1862979
glog.Infof("Falling back to using podman cp to fetch OS image content")
if err = podmanCopy(imgURL, osImageContentDir); err != nil {
return
}
}
return
}
// Remove pending deployment on OSTree based system
func removePendingDeployment() error {
args := []string{"cleanup", "-p"}
_, err := runGetOut("rpm-ostree", args...)
return err
}
func (dn *Daemon) applyOSChanges(oldConfig, newConfig *mcfgv1.MachineConfig) (retErr error) {
// Extract image and add coreos-extensions repo if we have either OS update or package layering to perform
mcDiff, err := newMachineConfigDiff(oldConfig, newConfig)
if err != nil {
return err
}
if dn.recorder != nil {
dn.recorder.Eventf(getNodeRef(dn.node), corev1.EventTypeNormal, "OSUpdateStarted", mcDiff.osChangesString())
}
var osImageContentDir string
if mcDiff.osUpdate || mcDiff.extensions || mcDiff.kernelType {
// When we're going to apply an OS update, switch the block
// scheduler to BFQ to apply more fairness between etcd
// and the OS update.
if err := setRootDeviceSchedulerBFQ(); err != nil {
return err
}
// We emitted this event before, so keep it
if dn.recorder != nil {
dn.recorder.Eventf(getNodeRef(dn.node), corev1.EventTypeNormal, "InClusterUpgrade", fmt.Sprintf("Updating from oscontainer %s", newConfig.Spec.OSImageURL))
}
if osImageContentDir, err = ExtractOSImage(newConfig.Spec.OSImageURL); err != nil {
return err
}
// Delete extracted OS image once we are done.
defer os.RemoveAll(osImageContentDir)
if dn.os.IsCoreOSVariant() {
if err := addExtensionsRepo(osImageContentDir); err != nil {
return err
}
defer os.Remove(extensionsRepo)
}
}
// Update OS
if err := dn.updateOS(newConfig, osImageContentDir); err != nil {
MCDPivotErr.WithLabelValues(dn.node.Name, newConfig.Spec.OSImageURL, err.Error()).SetToCurrentTime()
return err
}
defer func() {
// Operations performed by rpm-ostree on the booted system are available
// as staged deployment. It gets applied only when we reboot the system.
// In case of an error during any rpm-ostree transaction, removing pending deployment
// should be sufficient to discard any applied changes.
if retErr != nil {
// Print out the error now so that if we fail to cleanup -p, we don't lose it.
glog.Infof("Rolling back applied changes to OS due to error: %v", retErr)
if err := removePendingDeployment(); err != nil {
retErr = errors.Wrapf(retErr, "error removing staged deployment: %v", err)
return
}
}
}()
// Apply kargs
if err := dn.updateKernelArguments(oldConfig, newConfig); err != nil {
return err
}
// Switch to real time kernel
if err := dn.switchKernel(oldConfig, newConfig); err != nil {
return err
}
// Apply extensions
if err := dn.applyExtensions(oldConfig, newConfig); err != nil {
return err
}
if dn.recorder != nil {
dn.recorder.Eventf(getNodeRef(dn.node), corev1.EventTypeNormal, "OSUpdateStaged", "Changes to OS staged")
}
return nil
}
func calculatePostConfigChangeActionFromFileDiffs(oldIgnConfig, newIgnConfig ign3types.Config) (actions []string) {
filesPostConfigChangeActionNone := []string{
"/var/lib/kubelet/config.json",
}
filesPostConfigChangeActionReloadCrio := []string{
"/etc/containers/registries.conf",
}
oldFileSet := make(map[string]ign3types.File)
for _, f := range oldIgnConfig.Storage.Files {
oldFileSet[f.Path] = f
}
newFileSet := make(map[string]ign3types.File)
for _, f := range newIgnConfig.Storage.Files {
newFileSet[f.Path] = f
}
diffFileSet := []string{}
// First check if any files were removed
for path := range oldFileSet {
_, ok := newFileSet[path]
if !ok {
// debug: remove
glog.Infof("File diff: %v was deleted", path)
diffFileSet = append(diffFileSet, path)
}
}
// Now check if any files were added/changed
for path, newFile := range newFileSet {
oldFile, ok := oldFileSet[path]
if !ok {
// debug: remove
glog.Infof("File diff: %v was added", path)
diffFileSet = append(diffFileSet, path)
} else if !reflect.DeepEqual(oldFile, newFile) {
// debug: remove
glog.Infof("File diff: detected change to %v", newFile.Path)
diffFileSet = append(diffFileSet, path)
}
}
// Now calculate action
for _, k := range diffFileSet {
if ctrlcommon.InSlice(k, filesPostConfigChangeActionNone) {
continue
} else if ctrlcommon.InSlice(k, filesPostConfigChangeActionReloadCrio) {
actions = []string{postConfigChangeActionReloadCrio}
continue
} else {
actions = []string{postConfigChangeActionReboot}
break
}
}
if len(actions) == 0 {
actions = []string{postConfigChangeActionNone}
}
return
}
func calculatePostConfigChangeAction(oldConfig, newConfig *mcfgv1.MachineConfig) ([]string, error) {
// If a machine-config-daemon-force file is present, it means the user wants to
// move to desired state without additional validation. We will reboot the node in
// this case regardless of what MachineConfig diff is.
if _, err := os.Stat(constants.MachineConfigDaemonForceFile); err == nil {
if err := os.Remove(constants.MachineConfigDaemonForceFile); err != nil {
return []string{}, errors.Wrap(err, "failed to remove force validation file")
}
glog.Infof("Setting post config change action to postConfigChangeActionReboot; %s present", constants.MachineConfigDaemonForceFile)
return []string{postConfigChangeActionReboot}, nil
}
diff, err := newMachineConfigDiff(oldConfig, newConfig)
if err != nil {
return []string{}, err
}
if diff.osUpdate || diff.kargs || diff.fips || diff.units || diff.kernelType || diff.extensions {
// must reboot
return []string{postConfigChangeActionReboot}, nil
}
oldIgnConfig, err := ctrlcommon.ParseAndConvertConfig(oldConfig.Spec.Config.Raw)
if err != nil {
return []string{}, err
}
newIgnConfig, err := ctrlcommon.ParseAndConvertConfig(newConfig.Spec.Config.Raw)
if err != nil {
return []string{}, err
}
// We don't actually have to consider ssh keys changes, which is the only section of passwd that is allowed to change
return calculatePostConfigChangeActionFromFileDiffs(oldIgnConfig, newIgnConfig), nil
}
// update the node to the provided node configuration.
func (dn *Daemon) update(oldConfig, newConfig *mcfgv1.MachineConfig) (retErr error) {
oldConfig = canonicalizeEmptyMC(oldConfig)
if dn.nodeWriter != nil {
state, err := getNodeAnnotationExt(dn.node, constants.MachineConfigDaemonStateAnnotationKey, true)
if err != nil {
return err
}
if state != constants.MachineConfigDaemonStateDegraded && state != constants.MachineConfigDaemonStateUnreconcilable {
if err := dn.nodeWriter.SetWorking(dn.kubeClient.CoreV1().Nodes(), dn.nodeLister, dn.name); err != nil {
return errors.Wrap(err, "error setting node's state to Working")
}
}
}
dn.catchIgnoreSIGTERM()
defer func() {
if retErr != nil {
dn.cancelSIGTERM()
}
}()
oldConfigName := oldConfig.GetName()
newConfigName := newConfig.GetName()
glog.Infof("Checking Reconcilable for config %v to %v", oldConfigName, newConfigName)
// make sure we can actually reconcile this state
diff, reconcilableError := reconcilable(oldConfig, newConfig)
if reconcilableError != nil {
wrappedErr := fmt.Errorf("can't reconcile config %s with %s: %v", oldConfigName, newConfigName, reconcilableError)
if dn.recorder != nil {
mcRef := &corev1.ObjectReference{
Kind: "MachineConfig",
Name: newConfig.GetName(),
UID: newConfig.GetUID(),
}
dn.recorder.Eventf(mcRef, corev1.EventTypeWarning, "FailedToReconcile", wrappedErr.Error())
}
return errors.Wrapf(errUnreconcilable, "%v", wrappedErr)
}
dn.logSystem("Starting update from %s to %s: %+v", oldConfigName, newConfigName, diff)
actions, err := calculatePostConfigChangeAction(oldConfig, newConfig)
if err != nil {
return err
}
if err := dn.drain(); err != nil {
return err
}
// update files on disk that need updating
if err := dn.updateFiles(oldConfig, newConfig); err != nil {
return err
}
defer func() {
if retErr != nil {
if err := dn.updateFiles(newConfig, oldConfig); err != nil {
retErr = errors.Wrapf(retErr, "error rolling back files writes %v", err)
return
}
}
}()
oldIgnConfig, err := ctrlcommon.ParseAndConvertConfig(oldConfig.Spec.Config.Raw)
if err != nil {
return fmt.Errorf("parsing old Ignition config failed with error: %v", err)
}
newIgnConfig, err := ctrlcommon.ParseAndConvertConfig(newConfig.Spec.Config.Raw)
if err != nil {
return fmt.Errorf("parsing new Ignition config failed with error: %v", err)
}
if err := dn.updateSSHKeys(newIgnConfig.Passwd.Users); err != nil {
return err
}
defer func() {
if retErr != nil {
if err := dn.updateSSHKeys(oldIgnConfig.Passwd.Users); err != nil {
retErr = errors.Wrapf(retErr, "error rolling back SSH keys updates %v", err)
return
}
}
}()
if err := dn.storeCurrentConfigOnDisk(newConfig); err != nil {
return err
}
defer func() {
if retErr != nil {
if err := dn.storeCurrentConfigOnDisk(oldConfig); err != nil {
retErr = errors.Wrapf(retErr, "error rolling back current config on disk %v", err)
return
}
}
}()
if err := dn.applyOSChanges(oldConfig, newConfig); err != nil {
return err
}
defer func() {
if retErr != nil {
if err := dn.applyOSChanges(newConfig, oldConfig); err != nil {
retErr = errors.Wrapf(retErr, "error rolling back changes to OS %v", err)
return
}
}
}()
// Ideally we would want to update kernelArguments only via MachineConfigs.
// We are keeping this to maintain compatibility and OKD requirement.
tuningChanged, err := UpdateTuningArgs(KernelTuningFile, CmdLineFile)
if err != nil {
return err
}
if tuningChanged {
glog.Info("Updated kernel tuning arguments")
}
if err := dn.finalizeBeforeReboot(newConfig); err != nil {
return err
}
return dn.performPostConfigChangeAction(actions, newConfig.GetName())
}
// removeRollback removes the rpm-ostree rollback deployment. It
// takes up space, and we don't generally expect administrators to
// use this versus e.g. removing broken configuration. We only
// remove the rollback once the MCD pod has landed on a node, so
// we know kubelet is working.
func (dn *Daemon) removeRollback() error {
if !dn.os.IsCoreOSVariant() {
// do not attempt to rollback on non-RHCOS/FCOS machines
return nil
}
_, err := runGetOut("rpm-ostree", "cleanup", "-r")
return err
}
// machineConfigDiff represents an ad-hoc difference between two MachineConfig objects.
// At some point this may change into holding just the files/units that changed
// and the MCO would just operate on that. For now we're just doing this to get
// improved logging.
type machineConfigDiff struct {
osUpdate bool
kargs bool
fips bool
passwd bool
files bool
units bool
kernelType bool
extensions bool
}
// isEmpty returns true if the machineConfigDiff has no changes, or
// in other words if the two MachineConfig objects are equivalent from
// the MCD's point of view. This is mainly relevant if e.g. two MC
// objects happen to have different Ignition versions but are otherwise
// the same. (Probably a better way would be to canonicalize)
func (mcDiff *machineConfigDiff) isEmpty() bool {
emptyDiff := machineConfigDiff{}
return reflect.DeepEqual(mcDiff, &emptyDiff)
}
// osChangesString generates a human-readable set of changes from the diff
func (mcDiff *machineConfigDiff) osChangesString() string {
changes := []string{}
if mcDiff.osUpdate {
changes = append(changes, "Upgrading OS")
}
if mcDiff.extensions {
changes = append(changes, "Installing extensions")
}
if mcDiff.kernelType {
changes = append(changes, "Changing kernel type")
}
return strings.Join(changes, "; ")
}
// canonicalizeKernelType returns a valid kernelType. We consider empty("") and default kernelType as same
func canonicalizeKernelType(kernelType string) string {
if kernelType == ctrlcommon.KernelTypeRealtime {
return ctrlcommon.KernelTypeRealtime
}
return ctrlcommon.KernelTypeDefault
}
// newMachineConfigDiff compares two MachineConfig objects.
func newMachineConfigDiff(oldConfig, newConfig *mcfgv1.MachineConfig) (*machineConfigDiff, error) {
oldIgn, err := ctrlcommon.ParseAndConvertConfig(oldConfig.Spec.Config.Raw)
if err != nil {
return nil, fmt.Errorf("parsing old Ignition config failed with error: %v", err)
}
newIgn, err := ctrlcommon.ParseAndConvertConfig(newConfig.Spec.Config.Raw)
if err != nil {
return nil, fmt.Errorf("parsing new Ignition config failed with error: %v", err)
}
// Both nil and empty slices are of zero length,
// consider them as equal while comparing KernelArguments in both MachineConfigs
kargsEmpty := len(oldConfig.Spec.KernelArguments) == 0 && len(newConfig.Spec.KernelArguments) == 0
extensionsEmpty := len(oldConfig.Spec.Extensions) == 0 && len(newConfig.Spec.Extensions) == 0
return &machineConfigDiff{
osUpdate: oldConfig.Spec.OSImageURL != newConfig.Spec.OSImageURL,
kargs: !(kargsEmpty || reflect.DeepEqual(oldConfig.Spec.KernelArguments, newConfig.Spec.KernelArguments)),
fips: oldConfig.Spec.FIPS != newConfig.Spec.FIPS,
passwd: !reflect.DeepEqual(oldIgn.Passwd, newIgn.Passwd),
files: !reflect.DeepEqual(oldIgn.Storage.Files, newIgn.Storage.Files),
units: !reflect.DeepEqual(oldIgn.Systemd.Units, newIgn.Systemd.Units),
kernelType: canonicalizeKernelType(oldConfig.Spec.KernelType) != canonicalizeKernelType(newConfig.Spec.KernelType),
extensions: !(extensionsEmpty || reflect.DeepEqual(oldConfig.Spec.Extensions, newConfig.Spec.Extensions)),
}, nil
}
// reconcilable checks the configs to make sure that the only changes requested
// are ones we know how to do in-place. If we can reconcile, (nil, nil) is returned.
// Otherwise, if we can't do it in place, the node is marked as degraded;
// the returned string value includes the rationale.
//
// we can only update machine configs that have changes to the files,
// directories, links, and systemd units sections of the included ignition
// config currently.
func reconcilable(oldConfig, newConfig *mcfgv1.MachineConfig) (*machineConfigDiff, error) {
// The parser will try to translate versions less than maxVersion to maxVersion, or output an err.
// The ignition output in case of success will always have maxVersion
oldIgn, err := ctrlcommon.ParseAndConvertConfig(oldConfig.Spec.Config.Raw)
if err != nil {
return nil, fmt.Errorf("parsing old Ignition config failed with error: %v", err)
}
newIgn, err := ctrlcommon.ParseAndConvertConfig(newConfig.Spec.Config.Raw)
if err != nil {
return nil, fmt.Errorf("parsing new Ignition config failed with error: %v", err)
}
// Check if this is a generally valid Ignition Config
if err := ctrlcommon.ValidateIgnition(newIgn); err != nil {
return nil, err
}
// Passwd section
// we don't currently configure Groups in place. we don't configure Users except
// for setting/updating SSHAuthorizedKeys for the only allowed user "core".
// otherwise we can't fix it if something changed here.
passwdChanged := !reflect.DeepEqual(oldIgn.Passwd, newIgn.Passwd)
if passwdChanged {
if !reflect.DeepEqual(oldIgn.Passwd.Groups, newIgn.Passwd.Groups) {
return nil, errors.New("ignition Passwd Groups section contains changes")
}
if !reflect.DeepEqual(oldIgn.Passwd.Users, newIgn.Passwd.Users) {
// check if the prior config is empty and that this is the first time running.
// if so, the SSHKey from the cluster config and user "core" must be added to machine config.
if len(oldIgn.Passwd.Users) > 0 && len(newIgn.Passwd.Users) >= 1 {
// there is an update to Users, we must verify that it is ONLY making an acceptable
// change to the SSHAuthorizedKeys for the user "core"
for _, user := range newIgn.Passwd.Users {
if user.Name != coreUserName {
return nil, errors.New("ignition passwd user section contains unsupported changes: non-core user")
}
}
glog.Infof("user data to be verified before ssh update: %v", newIgn.Passwd.Users[len(newIgn.Passwd.Users)-1])
if err := verifyUserFields(newIgn.Passwd.Users[len(newIgn.Passwd.Users)-1]); err != nil {
return nil, err
}
}
}
}
// Storage section
// we can only reconcile files right now. make sure the sections we can't
// fix aren't changed.
if !reflect.DeepEqual(oldIgn.Storage.Disks, newIgn.Storage.Disks) {
return nil, errors.New("ignition disks section contains changes")
}
if !reflect.DeepEqual(oldIgn.Storage.Filesystems, newIgn.Storage.Filesystems) {
return nil, errors.New("ignition filesystems section contains changes")
}
if !reflect.DeepEqual(oldIgn.Storage.Raid, newIgn.Storage.Raid) {
return nil, errors.New("ignition raid section contains changes")
}
if !reflect.DeepEqual(oldIgn.Storage.Directories, newIgn.Storage.Directories) {
return nil, errors.New("ignition directories section contains changes")
}
if !reflect.DeepEqual(oldIgn.Storage.Links, newIgn.Storage.Links) {
// This means links have been added, as opposed as being removed as it happened with
// https://bugzilla.redhat.com/show_bug.cgi?id=1677198. This doesn't really change behavior
// since we still don't support links but we allow old MC to remove links when upgrading.
if len(newIgn.Storage.Links) != 0 {
return nil, errors.New("ignition links section contains changes")
}
}
// Special case files append: if the new config wants us to append, then we
// have to force a reprovision since it's not idempotent
for _, f := range newIgn.Storage.Files {
if len(f.Append) > 0 {
return nil, fmt.Errorf("ignition file %v includes append", f.Path)
}
}
// Systemd section
// we can reconcile any state changes in the systemd section.
// FIPS section
// We do not allow update to FIPS for a running cluster, so any changes here will be an error
if err := checkFIPS(oldConfig, newConfig); err != nil {
return nil, err
}
// we made it through all the checks. reconcile away!
glog.V(2).Info("Configs are reconcilable")
mcDiff, err := newMachineConfigDiff(oldConfig, newConfig)
if err != nil {
return nil, errors.Wrapf(err, "error creating machineConfigDiff")
}
return mcDiff, nil
}
// verifyUserFields returns nil if the user Name = "core", if 1 or more SSHKeys exist for
// this user and if all other fields in User are empty.
// Otherwise, an error will be returned and the proposed config will not be reconcilable.
// At this time we do not support non-"core" users or any changes to the "core" user
// outside of SSHAuthorizedKeys.
func verifyUserFields(pwdUser ign3types.PasswdUser) error {
emptyUser := ign3types.PasswdUser{}
tempUser := pwdUser
if tempUser.Name == coreUserName && len(tempUser.SSHAuthorizedKeys) >= 1 {
tempUser.Name = ""
tempUser.SSHAuthorizedKeys = nil
if !reflect.DeepEqual(emptyUser, tempUser) {
return errors.New("ignition passwd user section contains unsupported changes: non-sshKey changes")
}
glog.Info("SSH Keys reconcilable")
} else {
return errors.New("ignition passwd user section contains unsupported changes: user must be core and have 1 or more sshKeys")
}
return nil
}
// checkFIPS verifies the state of FIPS on the system before an update.
// Our new thought around this is that really FIPS should be a "day 1"
// operation, and we don't want to make it editable after the fact.
// See also https://github.com/openshift/installer/pull/2594
// Anyone who wants to force this can change the MC flag, then
// `oc debug node` and run the disable command by hand, then reboot.
// If we detect that FIPS has been changed, we reject the update.
func checkFIPS(current, desired *mcfgv1.MachineConfig) error {
content, err := ioutil.ReadFile(fipsFile)
if err != nil {
if os.IsNotExist(err) {
// we just exit cleanly if we're not even on linux
glog.Infof("no %s on this system, skipping FIPS check", fipsFile)
return nil
}
return errors.Wrapf(err, "Error reading FIPS file at %s: %s", fipsFile, string(content))
}
nodeFIPS, err := strconv.ParseBool(strings.TrimSuffix(string(content), "\n"))
if err != nil {
return errors.Wrapf(err, "Error parsing FIPS file at %s", fipsFile)
}
if desired.Spec.FIPS == nodeFIPS {
if desired.Spec.FIPS {
glog.Infof("FIPS is configured and enabled")
}
// Check if FIPS on the system is at the desired setting
current.Spec.FIPS = nodeFIPS
return nil
}
return errors.New("detected change to FIPS flag; refusing to modify FIPS on a running cluster")
}
// checks for white-space characters in "C" and "POSIX" locales.
func isSpace(b byte) bool {
return b == ' ' || b == '\f' || b == '\n' || b == '\r' || b == '\t' || b == '\v'
}
// You can use " around spaces, but can't escape ". See next_arg() in kernel code /lib/cmdline.c
// Gives the start and stop index for the next arg in the string, beyond the provided `begin` index
func nextArg(args string, begin int) (int, int) {
var (
start, stop int
inQuote bool
)
// Skip leading spaces
for start = begin; start < len(args) && isSpace(args[start]); start++ {
}
stop = start
for ; stop < len(args); stop++ {
if isSpace(args[stop]) && !inQuote {
break
}
if args[stop] == '"' {
inQuote = !inQuote
}
}
return start, stop
}
func splitKernelArguments(args string) []string {
var (
start, stop int
split []string
)
for stop < len(args) {
start, stop = nextArg(args, stop)
if start != stop {
split = append(split, args[start:stop])
}
}
return split
}
// parseKernelArguments separates out kargs from each entry and returns it as a map for
// easy comparison
func parseKernelArguments(kargs []string) []string {
parsed := []string{}
for _, k := range kargs {
for _, arg := range splitKernelArguments(k) {
parsed = append(parsed, strings.TrimSpace(arg))
}
}
return parsed
}
// generateKargsCommand performs a diff between the old/new MC kernelArguments,
// and generates the command line arguments suitable for `rpm-ostree kargs`.