-
Notifications
You must be signed in to change notification settings - Fork 423
/
Copy pathhelpers.go
1413 lines (1243 loc) · 49.7 KB
/
helpers.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 common
import (
"bufio"
"bytes"
"compress/gzip"
"context"
"crypto/tls"
"encoding/base64"
"errors"
"fmt"
"io"
"io/fs"
"net/url"
"os"
"path/filepath"
"reflect"
"sort"
"strings"
"text/template"
"github.com/clarketm/json"
fcctbase "github.com/coreos/fcct/base/v0_1"
"github.com/coreos/ign-converter/translate/v23tov30"
"github.com/coreos/ign-converter/translate/v32tov22"
"github.com/coreos/ign-converter/translate/v32tov31"
"github.com/coreos/ign-converter/translate/v33tov32"
"github.com/coreos/ign-converter/translate/v34tov33"
ign2error "github.com/coreos/ignition/config/shared/errors"
ign2 "github.com/coreos/ignition/config/v2_2"
ign2types "github.com/coreos/ignition/config/v2_2/types"
ign2_3 "github.com/coreos/ignition/config/v2_3"
validate2 "github.com/coreos/ignition/config/validate"
ign3error "github.com/coreos/ignition/v2/config/shared/errors"
translate3_1 "github.com/coreos/ignition/v2/config/v3_1/translate"
ign3_1types "github.com/coreos/ignition/v2/config/v3_1/types"
translate3_2 "github.com/coreos/ignition/v2/config/v3_2/translate"
ign3_2types "github.com/coreos/ignition/v2/config/v3_2/types"
translate3_3 "github.com/coreos/ignition/v2/config/v3_3/translate"
ign3_3types "github.com/coreos/ignition/v2/config/v3_3/types"
ign3 "github.com/coreos/ignition/v2/config/v3_4"
ign3_4 "github.com/coreos/ignition/v2/config/v3_4"
translate3 "github.com/coreos/ignition/v2/config/v3_4/translate"
ign3types "github.com/coreos/ignition/v2/config/v3_4/types"
validate3 "github.com/coreos/ignition/v2/config/validate"
"github.com/ghodss/yaml"
"github.com/vincent-petithory/dataurl"
corev1 "k8s.io/api/core/v1"
kerr "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/client-go/tools/record"
"k8s.io/client-go/tools/reference"
k8sapiflag "k8s.io/component-base/cli/flag"
"k8s.io/klog/v2"
configv1 "github.com/openshift/api/config/v1"
mcfgv1 "github.com/openshift/api/machineconfiguration/v1"
opv1 "github.com/openshift/api/operator/v1"
mcfgclientset "github.com/openshift/client-go/machineconfiguration/clientset/versioned"
"github.com/openshift/client-go/machineconfiguration/clientset/versioned/scheme"
"github.com/openshift/library-go/pkg/crypto"
)
// strToPtr converts the input string to a pointer to itself
func strToPtr(s string) *string {
return &s
}
// bootToPtr converts the input boolean to a pointer to itself
func boolToPtr(b bool) *bool {
return &b
}
// MergeMachineConfigs combines multiple machineconfig objects into one object.
// It sorts all the configs in increasing order of their name.
// It uses the Ignition config from first object as base and appends all the rest.
// Kernel arguments are concatenated.
// It defaults to the OSImageURL provided by the CVO but allows a MC provided OSImageURL to take precedence.
func MergeMachineConfigs(configs []*mcfgv1.MachineConfig, cconfig *mcfgv1.ControllerConfig) (*mcfgv1.MachineConfig, error) {
if len(configs) == 0 {
return nil, nil
}
// Overall the sort is alphanumerical, but custom pool configuration should take priority.
// Generally speaking if a custom pool is created, the expectation is that custom pool configuration should override base
// worker configuration.
// This mostly aims to help with generated configs (e.g. kubelet or containerruntime configs) where the pool name is
// part of the MachineConfig name, which cannot be directly modified.
var workerConfigs, otherConfigs []*mcfgv1.MachineConfig
for _, config := range configs {
if config.ObjectMeta.Labels == nil {
// This shouldn't really be possible
return nil, fmt.Errorf("Cannot find label in MachineConfig %s", config.ObjectMeta.Name)
}
if config.ObjectMeta.Labels[MachineConfigRoleLabel] == MachineConfigPoolWorker {
workerConfigs = append(workerConfigs, config)
} else {
otherConfigs = append(otherConfigs, config)
}
}
sort.SliceStable(workerConfigs, func(i, j int) bool { return workerConfigs[i].Name < workerConfigs[j].Name })
sort.SliceStable(otherConfigs, func(i, j int) bool { return otherConfigs[i].Name < otherConfigs[j].Name })
configs = append(configs[:0], append(workerConfigs, otherConfigs...)...)
var fips bool
var kernelType string
var outIgn ign3types.Config
var err error
if configs[0].Spec.Config.Raw == nil {
outIgn = ign3types.Config{
Ignition: ign3types.Ignition{
Version: ign3types.MaxVersion.String(),
},
}
} else {
outIgn, err = ParseAndConvertConfig(configs[0].Spec.Config.Raw)
if err != nil {
return nil, err
}
}
for idx := 1; idx < len(configs); idx++ {
if configs[idx].Spec.Config.Raw != nil {
mergedIgn, err := ParseAndConvertConfig(configs[idx].Spec.Config.Raw)
if err != nil {
return nil, err
}
outIgn = ign3.Merge(outIgn, mergedIgn)
}
}
// For file entries without a default overwrite, set it to true
// The MCO will always overwrite any files, but Ignition will not,
// Causing a difference in behaviour and failures when scaling new nodes into the cluster.
// This was a default change from ign spec2->spec3 which users don't often specify.
for idx := range outIgn.Storage.Files {
if outIgn.Storage.Files[idx].Overwrite == nil {
outIgn.Storage.Files[idx].Overwrite = boolToPtr(true)
}
}
rawOutIgn, err := json.Marshal(outIgn)
if err != nil {
return nil, err
}
// Setting FIPS to true or kernelType to a non-default value in any MachineConfig takes priority in setting that field
for _, cfg := range configs {
if cfg.Spec.FIPS {
fips = true
}
if cfg.Spec.KernelType == KernelTypeRealtime || cfg.Spec.KernelType == KernelType64kPages {
kernelType = cfg.Spec.KernelType
}
}
// If no MC sets kernelType, then set it to 'default' since that's what it is using
if kernelType == "" {
kernelType = KernelTypeDefault
}
kargs := []string{}
for _, cfg := range configs {
kargs = append(kargs, cfg.Spec.KernelArguments...)
}
extensions := []string{}
for _, cfg := range configs {
extensions = append(extensions, cfg.Spec.Extensions...)
}
// Ensure that kernel-devel extension is applied only with default kernel.
if kernelType != KernelTypeDefault {
if InSlice("kernel-devel", extensions) {
return nil, fmt.Errorf("installing kernel-devel extension is not supported with kernelType: %s", kernelType)
}
}
// For layering, we want to let the user override OSImageURL again
// The template configs always match what's in controllerconfig because they get rendered from there,
// so the only way we get an override here is if the user adds something different
osImageURL := GetDefaultBaseImageContainer(&cconfig.Spec)
for _, cfg := range configs {
if cfg.Spec.OSImageURL != "" {
osImageURL = cfg.Spec.OSImageURL
}
}
// Allow overriding the extensions container
baseOSExtensionsContainerImage := cconfig.Spec.BaseOSExtensionsContainerImage
for _, cfg := range configs {
if cfg.Spec.BaseOSExtensionsContainerImage != "" {
baseOSExtensionsContainerImage = cfg.Spec.BaseOSExtensionsContainerImage
}
}
return &mcfgv1.MachineConfig{
Spec: mcfgv1.MachineConfigSpec{
OSImageURL: osImageURL,
BaseOSExtensionsContainerImage: baseOSExtensionsContainerImage,
KernelArguments: kargs,
Config: runtime.RawExtension{
Raw: rawOutIgn,
},
FIPS: fips,
KernelType: kernelType,
Extensions: extensions,
},
}, nil
}
// PointerConfig generates the stub ignition for the machine to boot properly
// NOTE: If you change this, you also need to change the pointer configuration in openshift/installer, see
// https://github.com/openshift/installer/blob/master/pkg/asset/ignition/machine/node.go#L20
func PointerConfig(ignitionHost string, rootCA []byte) (ign3types.Config, error) {
configSourceURL := &url.URL{
Scheme: "https",
Host: ignitionHost,
Path: "/config/{{.Role}}",
}
// we do decoding here as curly brackets are escaped to %7B and breaks golang's templates
ignitionHostTmpl, err := url.QueryUnescape(configSourceURL.String())
if err != nil {
return ign3types.Config{}, err
}
CASource := dataurl.EncodeBytes(rootCA)
return ign3types.Config{
Ignition: ign3types.Ignition{
Version: ign3types.MaxVersion.String(),
Config: ign3types.IgnitionConfig{
Merge: []ign3types.Resource{{
Source: &ignitionHostTmpl,
}},
},
Security: ign3types.Security{
TLS: ign3types.TLS{
CertificateAuthorities: []ign3types.Resource{{
Source: &CASource,
}},
},
},
},
}, nil
}
// NewIgnConfig returns an empty ignition config with version set as latest version
func NewIgnConfig() ign3types.Config {
return ign3types.Config{
Ignition: ign3types.Ignition{
Version: ign3types.MaxVersion.String(),
},
}
}
// WriteTerminationError writes to the Kubernetes termination log.
func WriteTerminationError(err error) {
msg := err.Error()
// Disable gosec here to avoid throwing
// G306: Expect WriteFile permissions to be 0600 or less
// #nosec
os.WriteFile("/dev/termination-log", []byte(msg), 0o644)
klog.Fatal(msg)
}
// ConvertRawExtIgnitionToV3 ensures that the Ignition config in
// the RawExtension is spec v3.2, or translates to it.
func ConvertRawExtIgnitionToV3_4(inRawExtIgn *runtime.RawExtension) (runtime.RawExtension, error) {
// Parse the raw extension to the MCO's current internal ignition version
ignCfgV3, err := IgnParseWrapper(inRawExtIgn.Raw)
if err != nil {
return runtime.RawExtension{}, err
}
// TODO(jkyros): we used to only re-marshal this if it was the wrong version, now we're
// re-marshaling every time
outIgnV3, err := json.Marshal(ignCfgV3)
if err != nil {
return runtime.RawExtension{}, fmt.Errorf("failed to marshal converted config: %w", err)
}
outRawExt := runtime.RawExtension{}
outRawExt.Raw = outIgnV3
return outRawExt, nil
}
// ConvertRawExtIgnitionToV3_3 ensures that the Ignition config in
// the RawExtension is spec v3.3, or translates to it.
func ConvertRawExtIgnitionToV3_3(inRawExtIgn *runtime.RawExtension) (runtime.RawExtension, error) {
rawExt, err := ConvertRawExtIgnitionToV3_4(inRawExtIgn)
if err != nil {
return runtime.RawExtension{}, err
}
ignCfgV3, rptV3, errV3 := ign3.Parse(rawExt.Raw)
if errV3 != nil || rptV3.IsFatal() {
return runtime.RawExtension{}, fmt.Errorf("parsing Ignition config failed with error: %w\nReport: %v", errV3, rptV3)
}
// TODO(jkyros): someday we should write a recursive chain-downconverter, but until then,
// we're going to do it the hard way
ignCfgV33, err := convertIgnition34to33(ignCfgV3)
if err != nil {
return runtime.RawExtension{}, err
}
outIgnV33, err := json.Marshal(ignCfgV33)
if err != nil {
return runtime.RawExtension{}, fmt.Errorf("failed to marshal converted config: %w", err)
}
outRawExt := runtime.RawExtension{}
outRawExt.Raw = outIgnV33
return outRawExt, nil
}
// ConvertRawExtIgnitionToV3_3 ensures that the Ignition config in
// the RawExtension is spec v3.3, or translates to it.
func ConvertRawExtIgnitionToV3_2(inRawExtIgn *runtime.RawExtension) (runtime.RawExtension, error) {
rawExt, err := ConvertRawExtIgnitionToV3_4(inRawExtIgn)
if err != nil {
return runtime.RawExtension{}, err
}
ignCfgV3, rptV3, errV3 := ign3.Parse(rawExt.Raw)
if errV3 != nil || rptV3.IsFatal() {
return runtime.RawExtension{}, fmt.Errorf("parsing Ignition config failed with error: %w\nReport: %v", errV3, rptV3)
}
// TODO(jkyros): someday we should write a recursive chain-downconverter, but until then,
// we're going to do it the hard way
ignCfgV33, err := convertIgnition34to33(ignCfgV3)
if err != nil {
return runtime.RawExtension{}, err
}
ignCfgV32, err := convertIgnition33to32(ignCfgV33)
if err != nil {
return runtime.RawExtension{}, err
}
outIgnV32, err := json.Marshal(ignCfgV32)
if err != nil {
return runtime.RawExtension{}, fmt.Errorf("failed to marshal converted config: %w", err)
}
outRawExt := runtime.RawExtension{}
outRawExt.Raw = outIgnV32
return outRawExt, nil
}
// ConvertRawExtIgnitionToV3_1 ensures that the Ignition config in
// the RawExtension is spec v3.1, or translates to it.
func ConvertRawExtIgnitionToV3_1(inRawExtIgn *runtime.RawExtension) (runtime.RawExtension, error) {
rawExt, err := ConvertRawExtIgnitionToV3_4(inRawExtIgn)
if err != nil {
return runtime.RawExtension{}, err
}
ignCfgV3, rptV3, errV3 := ign3.Parse(rawExt.Raw)
if errV3 != nil || rptV3.IsFatal() {
return runtime.RawExtension{}, fmt.Errorf("parsing Ignition config failed with error: %w\nReport: %v", errV3, rptV3)
}
// TODO(jkyros): someday we should write a recursive chain-downconverter, but until then,
// we're going to do it the hard way
ignCfgV33, err := convertIgnition34to33(ignCfgV3)
if err != nil {
return runtime.RawExtension{}, err
}
ignCfgV32, err := convertIgnition33to32(ignCfgV33)
if err != nil {
return runtime.RawExtension{}, err
}
ignCfgV31, err := convertIgnition32to31(ignCfgV32)
if err != nil {
return runtime.RawExtension{}, err
}
outIgnV31, err := json.Marshal(ignCfgV31)
if err != nil {
return runtime.RawExtension{}, fmt.Errorf("failed to marshal converted config: %w", err)
}
outRawExt := runtime.RawExtension{}
outRawExt.Raw = outIgnV31
return outRawExt, nil
}
// ConvertRawExtIgnitionToV2 ensures that the Ignition config in
// the RawExtension is spec v2.2, or translates to it.
func ConvertRawExtIgnitionToV2_2(inRawExtIgn *runtime.RawExtension) (runtime.RawExtension, error) {
ignCfg, rpt, err := ign3.Parse(inRawExtIgn.Raw)
if err != nil || rpt.IsFatal() {
return runtime.RawExtension{}, fmt.Errorf("parsing Ignition config spec v3.2 failed with error: %w\nReport: %v", err, rpt)
}
converted2, err := convertIgnition34to22(ignCfg)
if err != nil {
return runtime.RawExtension{}, fmt.Errorf("failed to convert config from spec v3.2 to v2.2: %w", err)
}
outIgnV2, err := json.Marshal(converted2)
if err != nil {
return runtime.RawExtension{}, fmt.Errorf("failed to marshal converted config: %w", err)
}
outRawExt := runtime.RawExtension{}
outRawExt.Raw = outIgnV2
return outRawExt, nil
}
// convertIgnition2to3 takes an ignition spec v2.2 config and returns a v3.2 config
func convertIgnition22to34(ign2config ign2types.Config) (ign3types.Config, error) {
// only support writing to root file system
fsMap := map[string]string{
"root": "/",
}
// Workaround to get v2.3 as input for converter
ign2_3config := ign2_3.Translate(ign2config)
ign3_0config, err := v23tov30.Translate(ign2_3config, fsMap)
if err != nil {
return ign3types.Config{}, fmt.Errorf("unable to convert Ignition spec v2 config to v3: %w", err)
}
// Workaround to get a v3.4 config as output
converted3 := translate3.Translate(translate3_3.Translate(translate3_2.Translate(translate3_1.Translate(ign3_0config))))
klog.V(4).Infof("Successfully translated Ignition spec v2 config to Ignition spec v3 config: %v", converted3)
return converted3, nil
}
// convertIgnition3to2 takes an ignition spec v3.2 config and returns a v2.2 config
func convertIgnition34to22(ign3config ign3types.Config) (ign2types.Config, error) {
// TODO(jkyros): that recursive down-converter is looking like a better idea all the time
converted33, err := convertIgnition34to33(ign3config)
if err != nil {
return ign2types.Config{}, fmt.Errorf("unable to convert Ignition spec v3 config to v2: %w", err)
}
converted32, err := convertIgnition33to32(converted33)
if err != nil {
return ign2types.Config{}, fmt.Errorf("unable to convert Ignition spec v3 config to v2: %w", err)
}
converted2, err := v32tov22.Translate(converted32)
if err != nil {
return ign2types.Config{}, fmt.Errorf("unable to convert Ignition spec v3 config to v2: %w", err)
}
klog.V(4).Infof("Successfully translated Ignition spec v3 config to Ignition spec v2 config: %v", converted2)
return converted2, nil
}
// convertIgnition34to33 takes an ignition spec v3.4config and returns a v3.3 config
func convertIgnition34to33(ign3config ign3types.Config) (ign3_3types.Config, error) {
converted33, err := v34tov33.Translate(ign3config)
if err != nil {
return ign3_3types.Config{}, fmt.Errorf("unable to convert Ignition spec v3_2 config to v3_1: %w", err)
}
klog.V(4).Infof("Successfully translated Ignition spec v3_2 config to Ignition spec v3_1 config: %v", converted33)
return converted33, nil
}
// convertIgnition33to32 takes an ignition spec v3.3config and returns a v3.2 config
func convertIgnition33to32(ign3config ign3_3types.Config) (ign3_2types.Config, error) {
converted32, err := v33tov32.Translate(ign3config)
if err != nil {
return ign3_2types.Config{}, fmt.Errorf("unable to convert Ignition spec v3_2 config to v3_1: %w", err)
}
klog.V(4).Infof("Successfully translated Ignition spec v3_2 config to Ignition spec v3_1 config: %v", converted32)
return converted32, nil
}
// convertIgnition32to31 takes an ignition spec v3.2 config and returns a v3.1 config
func convertIgnition32to31(ign3config ign3_2types.Config) (ign3_1types.Config, error) {
converted31, err := v32tov31.Translate(ign3config)
if err != nil {
return ign3_1types.Config{}, fmt.Errorf("unable to convert Ignition spec v3_2 config to v3_1: %w", err)
}
klog.V(4).Infof("Successfully translated Ignition spec v3_2 config to Ignition spec v3_1 config: %v", converted31)
return converted31, nil
}
// ValidateIgnition wraps the underlying Ignition V2/V3 validation, but explicitly supports
// a completely empty Ignition config as valid. This is because we
// want to allow MachineConfig objects which just have e.g. KernelArguments
// set, but no Ignition config.
// Returns nil if the config is valid (per above) or an error containing a Report otherwise.
func ValidateIgnition(ignconfig interface{}) error {
switch cfg := ignconfig.(type) {
case ign2types.Config:
if reflect.DeepEqual(ign2types.Config{}, cfg) {
return nil
}
if report := validate2.ValidateWithoutSource(reflect.ValueOf(cfg)); report.IsFatal() {
return fmt.Errorf("invalid ignition V2 config found: %v", report)
}
return validateIgn2FileModes(cfg)
case ign3types.Config:
if reflect.DeepEqual(ign3types.Config{}, cfg) {
return nil
}
if report := validate3.ValidateWithContext(cfg, nil); report.IsFatal() {
return fmt.Errorf("invalid ignition V3 config found: %v", report)
}
return validateIgn3FileModes(cfg)
default:
return fmt.Errorf("unrecognized ignition type")
}
}
// Validates that Ignition V2 file modes do not have special bits (sticky, setuid, setgid) set
// https://bugzilla.redhat.com/show_bug.cgi?id=2038240
func validateIgn2FileModes(cfg ign2types.Config) error {
for _, file := range cfg.Storage.Files {
if file.Mode != nil && os.FileMode(*file.Mode) > os.ModePerm { //nolint:gosec
return fmt.Errorf("invalid mode %#o for %s, cannot exceed %#o", *file.Mode, file.Path, os.ModePerm)
}
}
return nil
}
// Validates that Ignition V3 file modes do not have special bits (sticky, setuid, setgid) set
// https://bugzilla.redhat.com/show_bug.cgi?id=2038240
func validateIgn3FileModes(cfg ign3types.Config) error {
for _, file := range cfg.Storage.Files {
if file.Mode != nil && os.FileMode(*file.Mode) > os.ModePerm { //nolint:gosec
return fmt.Errorf("invalid mode %#o for %s, cannot exceed %#o", *file.Mode, file.Path, os.ModePerm)
}
}
return nil
}
// DecodeIgnitionFileContents returns uncompressed, decoded inline file contents.
// This function does not handle remote resources; it assumes they have already
// been fetched.
func DecodeIgnitionFileContents(source, compression *string) ([]byte, error) {
var contentsBytes []byte
// To allow writing of "empty" files we'll allow source to be nil
if source != nil {
source, err := dataurl.DecodeString(*source)
if err != nil {
return []byte{}, fmt.Errorf("could not decode file content string: %w", err)
}
if compression != nil {
switch *compression {
case "":
contentsBytes = source.Data
case "gzip":
reader, err := gzip.NewReader(bytes.NewReader(source.Data))
if err != nil {
return []byte{}, fmt.Errorf("could not create gzip reader: %w", err)
}
defer reader.Close()
contentsBytes, err = io.ReadAll(reader)
if err != nil {
return []byte{}, fmt.Errorf("failed decompressing: %w", err)
}
default:
return []byte{}, fmt.Errorf("unsupported compression type %q", *compression)
}
} else {
contentsBytes = source.Data
}
}
return contentsBytes, nil
}
// InSlice search for an element in slice and return true if found, otherwise return false
func InSlice(elem string, slice []string) bool {
for _, k := range slice {
if k == elem {
return true
}
}
return false
}
// ValidateMachineConfig validates that given MachineConfig Spec is valid.
func ValidateMachineConfig(cfg mcfgv1.MachineConfigSpec) error {
if !(cfg.KernelType == "" || cfg.KernelType == KernelTypeDefault || cfg.KernelType == KernelTypeRealtime || cfg.KernelType == KernelType64kPages) {
return fmt.Errorf("kernelType=%s is invalid", cfg.KernelType)
}
if cfg.Config.Raw != nil {
ignCfg, err := IgnParseWrapper(cfg.Config.Raw)
if err != nil {
return err
}
if err := ValidateIgnition(ignCfg); err != nil {
return err
}
// Validate MC extensions are in allowlist
if len(cfg.Extensions) > 0 {
if err := ValidateMachineConfigExtensions(cfg); err != nil {
return err
}
}
}
return nil
}
// Validates that a given MachineConfig's extensions are supported.
func ValidateMachineConfigExtensions(cfg mcfgv1.MachineConfigSpec) error {
return validateExtensions(cfg.Extensions)
}
func validateExtensions(exts []string) error {
supportedExtensions := SupportedExtensions()
invalidExts := []string{}
for _, ext := range exts {
if _, ok := supportedExtensions[ext]; !ok {
invalidExts = append(invalidExts, ext)
}
}
if len(invalidExts) != 0 {
return fmt.Errorf("invalid extensions found: %v", invalidExts)
}
return nil
}
// Resolves a list of supported extensions to the individual packages required
// for each of those extensions. Returns an error is any of the supplied
// extensions is invalid.
func GetPackagesForSupportedExtensions(exts []string) ([]string, error) {
if err := validateExtensions(exts); err != nil {
return nil, err
}
pkgs := []string{}
supported := SupportedExtensions()
for _, ext := range exts {
for _, pkg := range supported[ext] {
pkgs = append(pkgs, pkg)
}
}
return pkgs, nil
}
// Returns list of extensions possible to install on a CoreOS based system.
func SupportedExtensions() map[string][]string {
// In future when list of extensions grow, it will make
// more sense to populate it in a dynamic way.
// These are RHCOS supported extensions.
// Each extension keeps a list of packages required to get enabled on host.
return map[string][]string{
"two-node-ha": {"pacemaker", "pcs", "fence-agents-all"},
"wasm": {"crun-wasm"},
"ipsec": {"NetworkManager-libreswan", "libreswan"},
"usbguard": {"usbguard"},
"kerberos": {"krb5-workstation", "libkadm5"},
"kernel-devel": {"kernel-devel", "kernel-headers"},
"sandboxed-containers": {"kata-containers"},
"sysstat": {"sysstat"},
}
}
// IgnParseWrapper parses rawIgn for both V2 and V3 ignition configs and returns
// a V2 or V3 Config or an error. This wrapper is necessary since V2 and V3 use different parsers.
func IgnParseWrapper(rawIgn []byte) (interface{}, error) {
// ParseCompatibleVersion will parse any config <= N to version N
ignCfgV3, rptV3, errV3 := ign3_4.ParseCompatibleVersion(rawIgn)
if errV3 == nil && !rptV3.IsFatal() {
return ignCfgV3, nil
}
// ParseCompatibleVersion differentiates between ErrUnknownVersion ("I know what it is and we don't support it") and
// ErrInvalidVersion ("I can't parse it to find out what it is"), but our old 3.2 logic didn't, so this is here to make sure
// our error message for invalid version is still helpful.
if errV3.Error() == ign3error.ErrInvalidVersion.Error() {
return ign3types.Config{}, fmt.Errorf("parsing Ignition config failed: invalid version. Supported spec versions: 2.2, 3.0, 3.1, 3.2, 3.3, 3.4")
}
if errV3.Error() == ign3error.ErrUnknownVersion.Error() {
ignCfgV2, rptV2, errV2 := ign2.Parse(rawIgn)
if errV2 == nil && !rptV2.IsFatal() {
return ignCfgV2, nil
}
// If the error is still UnknownVersion it's not a 3.3/3.2/3.1/3.0 or 2.x config, thus unsupported
if errV2.Error() == ign2error.ErrUnknownVersion.Error() {
return ign3types.Config{}, fmt.Errorf("parsing Ignition config failed: unknown version. Supported spec versions: 2.2, 3.0, 3.1, 3.2, 3.3, 3.4")
}
return ign3types.Config{}, fmt.Errorf("parsing Ignition spec v2 failed with error: %v\nReport: %v", errV2, rptV2)
}
return ign3types.Config{}, fmt.Errorf("parsing Ignition config spec v3 failed with error: %v\nReport: %v", errV3, rptV3)
}
// ParseAndConvertConfig parses rawIgn for both V2 and V3 ignition configs and returns
// a V3 or an error.
func ParseAndConvertConfig(rawIgn []byte) (ign3types.Config, error) {
ignconfigi, err := IgnParseWrapper(rawIgn)
if err != nil {
return ign3types.Config{}, fmt.Errorf("failed to parse Ignition config: %w", err)
}
switch typedConfig := ignconfigi.(type) {
case ign3types.Config:
return ignconfigi.(ign3types.Config), nil
case ign2types.Config:
ignconfv2, err := removeIgnDuplicateFilesUnitsUsers(ignconfigi.(ign2types.Config))
if err != nil {
return ign3types.Config{}, err
}
convertedIgnV3, err := convertIgnition22to34(ignconfv2)
if err != nil {
return ign3types.Config{}, fmt.Errorf("failed to convert Ignition config spec v2 to v3: %w", err)
}
return convertedIgnV3, nil
default:
return ign3types.Config{}, fmt.Errorf("unexpected type for ignition config: %v", typedConfig)
}
}
// Internal error used for base64-decoding and gunzipping Ignition configs
var errConfigNotGzipped = fmt.Errorf("ignition config not gzipped")
// Decode, decompress, and deserialize an Ignition config file.
func ParseAndConvertGzippedConfig(rawIgn []byte) (ign3types.Config, error) {
// Try to decode and decompress our payload
out, err := DecodeAndDecompressPayload(bytes.NewReader(rawIgn))
if err == nil {
// Our payload was decoded and decompressed, so parse it as Ignition.
klog.V(2).Info("ignition config was base64-decoded and gunzipped successfully")
return ParseAndConvertConfig(out)
}
// Our Ignition config is not base64-encoded, which means it might only be gzipped:
// e.g.: $ gzip -9 ign_config.json
var base64Err base64.CorruptInputError
if errors.As(err, &base64Err) {
klog.V(2).Info("ignition config was not base64 encoded, trying to gunzip ignition config")
out, err = decompressPayload(bytes.NewReader(rawIgn))
if err == nil {
// We were able to decompress our payload, so let's try parsing it
klog.V(2).Info("ignition config was gunzipped successfully")
return ParseAndConvertConfig(out)
}
}
// Our Ignition config is not gzipped, so let's try to serialize the raw Ignition directly.
if errors.Is(err, errConfigNotGzipped) {
klog.V(2).Info("ignition config was not gzipped")
return ParseAndConvertConfig(rawIgn)
}
return ign3types.Config{}, fmt.Errorf("unable to read ignition config: %w", err)
}
// Attempts to base64-decode and/or decompresses a given byte array.
func DecodeAndDecompressPayload(r io.Reader) ([]byte, error) {
// Wrap the io.Reader in a base64 decoder (which implements io.Reader)
base64Dec := base64.NewDecoder(base64.StdEncoding, r)
out, err := decompressPayload(base64Dec)
if err == nil {
return out, nil
}
return nil, fmt.Errorf("unable to decode and decompress payload: %w", err)
}
// Checks if a given io.Reader contains known gzip headers and if so, gunzips
// the contents.
func decompressPayload(r io.Reader) ([]byte, error) {
// Wrap our io.Reader in a bufio.Reader. This allows us to peek ahead to
// determine if we have a valid gzip archive.
in := bufio.NewReader(r)
headerBytes, err := in.Peek(2)
if err != nil {
return nil, fmt.Errorf("could not peek: %w", err)
}
// gzipped files have a header in the first two bytes which contain a magic
// number that indicate they are gzipped. We check if these magic numbers are
// present as a quick and easy way to determine if our payload is gzipped.
//
// See: https://cs.opensource.google/go/go/+/refs/tags/go1.19:src/compress/gzip/gunzip.go;l=20-21
if headerBytes[0] != 0x1f && headerBytes[1] != 0x8b {
return nil, errConfigNotGzipped
}
gz, err := gzip.NewReader(in)
if err != nil {
return nil, fmt.Errorf("initialize gzip reader failed: %w", err)
}
defer gz.Close()
data, err := io.ReadAll(gz)
if err != nil {
return nil, fmt.Errorf("decompression failed: %w", err)
}
return data, nil
}
// Function to remove duplicated files/units/users from a V2 MC, since the translator
// (and ignition spec V3) does not allow for duplicated entries in one MC.
// This should really not change the actual final behaviour, since it keeps
// ordering into consideration and has contents from the highest alphanumeric
// MC's final version of a file.
// Note:
// Append is not considered since we do not allow for appending
// Units have one exception: dropins are concat'ed
func removeIgnDuplicateFilesUnitsUsers(ignConfig ign2types.Config) (ign2types.Config, error) {
files := ignConfig.Storage.Files
units := ignConfig.Systemd.Units
users := ignConfig.Passwd.Users
filePathMap := map[string]bool{}
var outFiles []ign2types.File
for i := len(files) - 1; i >= 0; i-- {
// We do not actually support to other filesystems so we make the assumption that there is only 1 here
path := files[i].Path
if _, isDup := filePathMap[path]; isDup {
continue
}
outFiles = append(outFiles, files[i])
filePathMap[path] = true
}
unitNameMap := map[string]bool{}
var outUnits []ign2types.Unit
for i := len(units) - 1; i >= 0; i-- {
unitName := units[i].Name
if _, isDup := unitNameMap[unitName]; isDup {
// this is a duplicated unit by name, so let's check for the dropins and append them
if len(units[i].Dropins) > 0 {
for j := range outUnits {
if outUnits[j].Name == unitName {
// outUnits[j] is the highest priority entry with this unit name
// now loop over the new unit's dropins and append it if the name
// isn't duplicated in the existing unit's dropins
for _, newDropin := range units[i].Dropins {
hasExistingDropin := false
for _, existingDropins := range outUnits[j].Dropins {
if existingDropins.Name == newDropin.Name {
hasExistingDropin = true
break
}
}
if !hasExistingDropin {
outUnits[j].Dropins = append(outUnits[j].Dropins, newDropin)
}
}
continue
}
}
klog.V(2).Infof("Found duplicate unit %v, appending dropin section", unitName)
}
continue
}
outUnits = append(outUnits, units[i])
unitNameMap[unitName] = true
}
// Concat sshkey sections into the newest passwdUser in the list
// We make the assumption that there is only one user: core
// since that is the only supported user by design.
// It's technically possible, though, to have created another user
// during install time configs, since we only check the validity of
// the passwd section if it was changed. Explicitly error in that case.
if len(users) > 0 {
outUser := users[len(users)-1]
if outUser.Name != "core" {
return ignConfig, fmt.Errorf("unexpected user with name: %v. Only core user is supported", outUser.Name)
}
for i := len(users) - 2; i >= 0; i-- {
if users[i].Name != "core" {
return ignConfig, fmt.Errorf("unexpected user with name: %v. Only core user is supported", users[i].Name)
}
for j := range users[i].SSHAuthorizedKeys {
outUser.SSHAuthorizedKeys = append(outUser.SSHAuthorizedKeys, users[i].SSHAuthorizedKeys[j])
}
}
// Ensure SSH key uniqueness
ignConfig.Passwd.Users = []ign2types.PasswdUser{dedupePasswdUserSSHKeys(outUser)}
}
// outFiles and outUnits should now have all duplication removed
ignConfig.Storage.Files = outFiles
ignConfig.Systemd.Units = outUnits
return ignConfig, nil
}
// TranspileCoreOSConfigToIgn transpiles Fedora CoreOS config to ignition
// internally it transpiles to Ign spec v3 config
func TranspileCoreOSConfigToIgn(files, units []string) (*ign3types.Config, error) {
overwrite := true
outConfig := ign3types.Config{}
// Convert data to Ignition resources
for _, contents := range files {
f := new(fcctbase.File)
if err := yaml.Unmarshal([]byte(contents), f); err != nil {
return nil, fmt.Errorf("failed to unmarshal %q into struct: %w", contents, err)
}
f.Overwrite = &overwrite
// Add the file to the config
var ctCfg fcctbase.Config
ctCfg.Storage.Files = append(ctCfg.Storage.Files, *f)
ign3_0config, tSet, err := ctCfg.ToIgn3_0()
if err != nil {
return nil, fmt.Errorf("failed to transpile config to Ignition config %w\nTranslation set: %v", err, tSet)
}
// TODO(jkyros): do we keep just...adding translations forever as we add more versions? :)
ign3_2config := translate3.Translate(translate3_3.Translate(translate3_2.Translate(translate3_1.Translate(ign3_0config))))
outConfig = ign3.Merge(outConfig, ign3_2config)
}
for _, contents := range units {
u := new(fcctbase.Unit)
if err := yaml.Unmarshal([]byte(contents), u); err != nil {
return nil, fmt.Errorf("failed to unmarshal systemd unit into struct: %w", err)
}
// Add the unit to the config
var ctCfg fcctbase.Config
ctCfg.Systemd.Units = append(ctCfg.Systemd.Units, *u)
ign3_0config, tSet, err := ctCfg.ToIgn3_0()
if err != nil {
return nil, fmt.Errorf("failed to transpile config to Ignition config %w\nTranslation set: %v", err, tSet)
}
ign3_2config := translate3.Translate(translate3_3.Translate(translate3_2.Translate(translate3_1.Translate(ign3_0config))))
outConfig = ign3.Merge(outConfig, ign3_2config)
}
return &outConfig, nil
}
// MachineConfigFromIgnConfig creates a MachineConfig with the provided Ignition config
func MachineConfigFromIgnConfig(role, name string, ignCfg interface{}) (*mcfgv1.MachineConfig, error) {
rawIgnCfg, err := json.Marshal(ignCfg)
if err != nil {
return nil, fmt.Errorf("error marshalling Ignition config: %w", err)
}
return MachineConfigFromRawIgnConfig(role, name, rawIgnCfg)
}
// MachineConfigFromRawIgnConfig creates a MachineConfig with the provided raw Ignition config
func MachineConfigFromRawIgnConfig(role, name string, rawIgnCfg []byte) (*mcfgv1.MachineConfig, error) {
labels := map[string]string{
mcfgv1.MachineConfigRoleLabelKey: role,
}
return &mcfgv1.MachineConfig{
ObjectMeta: metav1.ObjectMeta{
Labels: labels,
Name: name,
},
Spec: mcfgv1.MachineConfigSpec{
OSImageURL: "",
Config: runtime.RawExtension{
Raw: rawIgnCfg,
},
},
}, nil
}
// GetManagedKey returns the managed key for sub-controllers, handling any migration needed
func GetManagedKey(pool *mcfgv1.MachineConfigPool, client mcfgclientset.Interface, prefix, suffix, deprecatedKey string) (string, error) {
managedKey := fmt.Sprintf("%s-%s-generated-%s", prefix, pool.Name, suffix)
// if we don't have a client, we're installing brand new, and we don't need to adjust for backward compatibility
if client == nil {
return managedKey, nil
}
if _, err := client.MachineconfigurationV1().MachineConfigs().Get(context.TODO(), managedKey, metav1.GetOptions{}); err == nil {
return managedKey, nil
}
old, err := client.MachineconfigurationV1().MachineConfigs().Get(context.TODO(), deprecatedKey, metav1.GetOptions{})
if err != nil && !kerr.IsNotFound(err) {
return "", fmt.Errorf("could not get MachineConfig %q: %w", deprecatedKey, err)
}
// this means no previous CR config were here, so we can start fresh