forked from openshift/assisted-service
/
ignition.go
1883 lines (1674 loc) · 62.3 KB
/
ignition.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 ignition
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"net"
"net/url"
"os"
"os/exec"
"path/filepath"
"sort"
"strconv"
"strings"
"text/template"
"time"
"github.com/coreos/ignition/v2/config/merge"
config_31 "github.com/coreos/ignition/v2/config/v3_1"
config_latest "github.com/coreos/ignition/v2/config/v3_2"
config_latest_trans "github.com/coreos/ignition/v2/config/v3_2/translate"
config_latest_types "github.com/coreos/ignition/v2/config/v3_2/types"
"github.com/coreos/vcontext/report"
"github.com/go-openapi/strfmt"
"github.com/go-openapi/swag"
bmh_v1alpha1 "github.com/metal3-io/baremetal-operator/apis/metal3.io/v1alpha1"
clusterPkg "github.com/openshift/assisted-service/internal/cluster"
"github.com/openshift/assisted-service/internal/common"
"github.com/openshift/assisted-service/internal/constants"
"github.com/openshift/assisted-service/internal/host/hostutil"
"github.com/openshift/assisted-service/internal/installercache"
"github.com/openshift/assisted-service/internal/manifests"
"github.com/openshift/assisted-service/internal/network"
"github.com/openshift/assisted-service/internal/oc"
"github.com/openshift/assisted-service/internal/operators"
"github.com/openshift/assisted-service/internal/provider/registry"
"github.com/openshift/assisted-service/internal/versions"
"github.com/openshift/assisted-service/models"
"github.com/openshift/assisted-service/pkg/auth"
"github.com/openshift/assisted-service/pkg/executer"
logutil "github.com/openshift/assisted-service/pkg/log"
"github.com/openshift/assisted-service/pkg/mirrorregistries"
"github.com/openshift/assisted-service/pkg/s3wrapper"
"github.com/openshift/assisted-service/pkg/staticnetworkconfig"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"github.com/thoas/go-funk"
"github.com/vincent-petithory/dataurl"
"golang.org/x/sync/errgroup"
"gopkg.in/yaml.v2"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
k8sjson "k8s.io/apimachinery/pkg/runtime/serializer/json"
"k8s.io/client-go/kubernetes/scheme"
)
const (
masterIgn = "master.ign"
workerIgn = "worker.ign"
)
// Names of some relevant templates:
const (
discoveryIgnTemplateName = "discovery.ign"
nodeIgnTemplateName = "node.ign"
)
const agentMessageOfTheDay = `
** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** **
This is a host being installed by the OpenShift Assisted Installer.
It will be installed from scratch during the installation.
The primary service is agent.service. To watch its status, run:
sudo journalctl -u agent.service
To view the agent log, run:
sudo journalctl TAG=agent
** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** **
`
const RedhatRootCA = `
-----BEGIN CERTIFICATE-----
MIIENDCCAxygAwIBAgIJANunI0D662cnMA0GCSqGSIb3DQEBCwUAMIGlMQswCQYD
VQQGEwJVUzEXMBUGA1UECAwOTm9ydGggQ2Fyb2xpbmExEDAOBgNVBAcMB1JhbGVp
Z2gxFjAUBgNVBAoMDVJlZCBIYXQsIEluYy4xEzARBgNVBAsMClJlZCBIYXQgSVQx
GzAZBgNVBAMMElJlZCBIYXQgSVQgUm9vdCBDQTEhMB8GCSqGSIb3DQEJARYSaW5m
b3NlY0ByZWRoYXQuY29tMCAXDTE1MDcwNjE3MzgxMVoYDzIwNTUwNjI2MTczODEx
WjCBpTELMAkGA1UEBhMCVVMxFzAVBgNVBAgMDk5vcnRoIENhcm9saW5hMRAwDgYD
VQQHDAdSYWxlaWdoMRYwFAYDVQQKDA1SZWQgSGF0LCBJbmMuMRMwEQYDVQQLDApS
ZWQgSGF0IElUMRswGQYDVQQDDBJSZWQgSGF0IElUIFJvb3QgQ0ExITAfBgkqhkiG
9w0BCQEWEmluZm9zZWNAcmVkaGF0LmNvbTCCASIwDQYJKoZIhvcNAQEBBQADggEP
ADCCAQoCggEBALQt9OJQh6GC5LT1g80qNh0u50BQ4sZ/yZ8aETxt+5lnPVX6MHKz
bfwI6nO1aMG6j9bSw+6UUyPBHP796+FT/pTS+K0wsDV7c9XvHoxJBJJU38cdLkI2
c/i7lDqTfTcfLL2nyUBd2fQDk1B0fxrskhGIIZ3ifP1Ps4ltTkv8hRSob3VtNqSo
GxkKfvD2PKjTPxDPWYyruy9irLZioMffi3i/gCut0ZWtAyO3MVH5qWF/enKwgPES
X9po+TdCvRB/RUObBaM761EcrLSM1GqHNueSfqnho3AjLQ6dBnPWlo638Zm1VebK
BELyhkLWMSFkKwDmne0jQ02Y4g075vCKvCsCAwEAAaNjMGEwHQYDVR0OBBYEFH7R
4yC+UehIIPeuL8Zqw3PzbgcZMB8GA1UdIwQYMBaAFH7R4yC+UehIIPeuL8Zqw3Pz
bgcZMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgGGMA0GCSqGSIb3DQEB
CwUAA4IBAQBDNvD2Vm9sA5A9AlOJR8+en5Xz9hXcxJB5phxcZQ8jFoG04Vshvd0e
LEnUrMcfFgIZ4njMKTQCM4ZFUPAieyLx4f52HuDopp3e5JyIMfW+KFcNIpKwCsak
oSoKtIUOsUJK7qBVZxcrIyeQV2qcYOeZhtS5wBqIwOAhFwlCET7Ze58QHmS48slj
S9K0JAcps2xdnGu0fkzhSQxY8GPQNFTlr6rYld5+ID/hHeS76gq0YG3q6RLWRkHf
4eTkRjivAlExrFzKcljC4axKQlnOvVAzz+Gm32U0xPBF4ByePVxCJUHw1TsyTmel
RxNEp7yHoXcwn+fXna+t5JWh1gxUZty3
-----END CERTIFICATE-----`
const selinuxPolicy = `
module assisted 1.0;
require {
type chronyd_t;
type container_file_t;
type spc_t;
class unix_dgram_socket sendto;
class dir search;
class sock_file write;
}
#============= chronyd_t ==============
allow chronyd_t container_file_t:dir search;
allow chronyd_t container_file_t:sock_file write;
allow chronyd_t spc_t:unix_dgram_socket sendto;
`
const agentFixBZ1964591 = `#!/usr/bin/sh
# This script is a workaround for bugzilla 1964591 where symlinks inside /var/lib/containers/ get
# corrupted under some circumstances.
#
# In order to let agent.service start correctly we are checking here whether the requested
# container image exists and in case "podman images" returns an error we try removing the faulty
# image.
#
# In such a scenario agent.service will detect the image is not present and pull it again. In case
# the image is present and can be detected correctly, no any action is required.
IMAGE=$(echo $1 | sed 's/[@:].*//')
podman images | grep $IMAGE || podman rmi --force $1 || true
`
const okdBinariesOverlayTemplate = `#!/bin/env bash
set -eux
# Fetch an image with OKD rpms
RPMS_IMAGE="%s"
while ! podman pull --quiet "${RPMS_IMAGE}"
do
echo "Pull failed. Retrying ${RPMS_IMAGE}..."
sleep 5
done
mnt=$(podman image mount "${RPMS_IMAGE}")
# Install RPMs in overlayed FS
mkdir /tmp/rpms
cp -rvf ${mnt}/rpms/* /tmp/rpms
# If RPMs image contants manifests these need to be copied as well
mkdir -p /opt/openshift/openshift
cp -rvf ${mnt}/manifests/* /opt/openshift/openshift || true
tmpd=$(mktemp -d)
mkdir ${tmpd}/{upper,work}
mount -t overlay -o lowerdir=/usr,upperdir=${tmpd}/upper,workdir=${tmpd}/work overlay /usr
rpm -Uvh /tmp/rpms/*
podman rmi -f "${RPMS_IMAGE}"
# Symlink kubelet pull secret
mkdir -p /var/lib/kubelet
ln -s /root/.docker/config.json /var/lib/kubelet/config.json
# Expand /var to 6G if necessary
if (( $(stat -c%%s /run/ephemeral.xfsloop) > 6*1024*1024*1024 )); then
exit 0
fi
/bin/truncate -s 6G /run/ephemeral.xfsloop
losetup -c /dev/loop0
xfs_growfs /var
mount -o remount,size=6G /run
`
const okdHoldAgentUntilBinariesLanded = `[Unit]
Wants=okd-overlay.service
After=okd-overlay.service
`
const okdHoldPivot = `[Unit]
ConditionPathExists=/enoent
`
const highlyAvailableInfrastructureTopologyPatch = `---
- op: replace
path: /status/infrastructureTopology
value: HighlyAvailable
`
const tempNMConnectionsDir = "/etc/assisted/network"
var fileNames = [...]string{
"bootstrap.ign",
masterIgn,
"metadata.json",
workerIgn,
"kubeconfig-noingress",
"kubeadmin-password",
"install-config.yaml",
}
// Generator can generate ignition files and upload them to an S3-like service
type Generator interface {
Generate(ctx context.Context, installConfig []byte, authType auth.AuthType) error
UploadToS3(ctx context.Context) error
UpdateEtcHosts(string) error
}
// IgnitionBuilder defines the ignition formatting methods for the various images
//
//go:generate mockgen -source=ignition.go -package=ignition -destination=mock_ignition.go
type IgnitionBuilder interface {
FormatDiscoveryIgnitionFile(ctx context.Context, infraEnv *common.InfraEnv, cfg IgnitionConfig, safeForLogs bool, authType auth.AuthType, overrideDiscoveryISOType string) (string, error)
FormatSecondDayWorkerIgnitionFile(url string, caCert *string, bearerToken string, host *models.Host) ([]byte, error)
}
type installerGenerator struct {
log logrus.FieldLogger
serviceBaseURL string
workDir string
cluster *common.Cluster
releaseImage string
releaseImageMirror string
installerDir string
serviceCACert string
encodedDhcpFileContents string
s3Client s3wrapper.API
enableMetal3Provisioning bool
operatorsApi operators.API
installInvoker string
providerRegistry registry.ProviderRegistry
installerReleaseImageOverride string
clusterTLSCertOverrideDir string
installerCache *installercache.Installers
}
// IgnitionConfig contains the attributes required to build the discovery ignition file
type IgnitionConfig struct {
AgentDockerImg string `envconfig:"AGENT_DOCKER_IMAGE" default:"quay.io/edge-infrastructure/assisted-installer-agent:latest"`
AgentTimeoutStart time.Duration `envconfig:"AGENT_TIMEOUT_START" default:"10m"`
InstallRHCa bool `envconfig:"INSTALL_RH_CA" default:"false"`
ServiceBaseURL string `envconfig:"SERVICE_BASE_URL"`
ServiceCACertPath string `envconfig:"SERVICE_CA_CERT_PATH" default:""`
ServiceIPs string `envconfig:"SERVICE_IPS" default:""`
SkipCertVerification bool `envconfig:"SKIP_CERT_VERIFICATION" default:"false"`
OKDRPMsImage string `envconfig:"OKD_RPMS_IMAGE" default:""`
}
type ignitionBuilder struct {
log logrus.FieldLogger
templates *template.Template
staticNetworkConfig staticnetworkconfig.StaticNetworkConfig
mirrorRegistriesBuilder mirrorregistries.MirrorRegistriesConfigBuilder
ocRelease oc.Release
versionHandler versions.Handler
}
func NewBuilder(log logrus.FieldLogger, staticNetworkConfig staticnetworkconfig.StaticNetworkConfig,
mirrorRegistriesBuilder mirrorregistries.MirrorRegistriesConfigBuilder, ocRelease oc.Release, versionHandler versions.Handler) (result IgnitionBuilder, err error) {
// Parse the templates file system:
templates, err := loadTemplates()
if err != nil {
return
}
// Create and populate the object:
result = &ignitionBuilder{
log: log,
templates: templates,
staticNetworkConfig: staticNetworkConfig,
mirrorRegistriesBuilder: mirrorRegistriesBuilder,
ocRelease: ocRelease,
versionHandler: versionHandler,
}
return
}
// NewGenerator returns a generator that can generate ignition files
func NewGenerator(serviceBaseURL string, workDir string, installerDir string, cluster *common.Cluster, releaseImage string, releaseImageMirror string,
serviceCACert string, installInvoker string, s3Client s3wrapper.API, log logrus.FieldLogger, operatorsApi operators.API,
providerRegistry registry.ProviderRegistry, installerReleaseImageOverride, clusterTLSCertOverrideDir string, storageCapacityLimit int64) Generator {
return &installerGenerator{
cluster: cluster,
log: log,
serviceBaseURL: serviceBaseURL,
releaseImage: releaseImage,
releaseImageMirror: releaseImageMirror,
workDir: workDir,
installerDir: installerDir,
serviceCACert: serviceCACert,
s3Client: s3Client,
enableMetal3Provisioning: true,
operatorsApi: operatorsApi,
installInvoker: installInvoker,
providerRegistry: providerRegistry,
installerReleaseImageOverride: installerReleaseImageOverride,
clusterTLSCertOverrideDir: clusterTLSCertOverrideDir,
installerCache: installercache.New(installerDir, storageCapacityLimit, log),
}
}
// UploadToS3 uploads generated ignition and related files to the configured
// S3-compatible storage
func (g *installerGenerator) UploadToS3(ctx context.Context) error {
return uploadToS3(ctx, g.workDir, g.cluster, g.s3Client, g.log)
}
// Generate generates ignition files and applies modifications.
func (g *installerGenerator) Generate(ctx context.Context, installConfig []byte, authType auth.AuthType) error {
var err error
log := logutil.FromContext(ctx, g.log)
defer func() {
if err != nil {
os.Remove(filepath.Join(g.workDir, "manifests"))
os.Remove(filepath.Join(g.workDir, "openshift"))
}
}()
// In case we don't want to override image for extracting installer use release one
if g.installerReleaseImageOverride == "" {
g.installerReleaseImageOverride = g.releaseImage
}
mirrorRegistriesBuilder := mirrorregistries.New()
ocRelease := oc.NewRelease(&executer.CommonExecuter{}, oc.Config{
MaxTries: oc.DefaultTries, RetryDelay: oc.DefaltRetryDelay}, mirrorRegistriesBuilder)
release, err := g.installerCache.Get(g.installerReleaseImageOverride, g.releaseImageMirror,
g.cluster.PullSecret, ocRelease)
if err != nil {
return errors.Wrap(err, "failed to get installer path")
}
//cleanup resources at the end
defer release.Release()
installerPath := release.Path
installConfigPath := filepath.Join(g.workDir, "install-config.yaml")
g.enableMetal3Provisioning, err = common.VersionGreaterOrEqual(g.cluster.Cluster.OpenshiftVersion, "4.7")
if err != nil {
return err
}
g.encodedDhcpFileContents, err = network.GetEncodedDhcpParamFileContents(g.cluster)
if err != nil {
wrapped := errors.Wrapf(err, "Could not create DHCP encoded file")
log.WithError(wrapped).Errorf("GenerateInstallConfig")
return wrapped
}
envVars := append(os.Environ(),
"OPENSHIFT_INSTALL_RELEASE_IMAGE_OVERRIDE="+g.releaseImage,
"OPENSHIFT_INSTALL_INVOKER="+g.installInvoker,
)
if g.clusterTLSCertOverrideDir != "" {
envVars = append(envVars, "OPENSHIFT_INSTALL_LOAD_CLUSTER_CERTS=true")
}
if envVars, err = g.addBootstrapKubeletIpIfRequired(log, envVars); err != nil {
return err
}
// write installConfig to install-config.yaml so openshift-install can read it
err = os.WriteFile(installConfigPath, installConfig, 0600)
if err != nil {
log.Errorf("failed to write file %s", installConfigPath)
return err
}
manifestFiles, err := manifests.GetClusterManifests(ctx, g.cluster.ID, g.s3Client)
if err != nil {
log.WithError(err).Errorf("failed to check if cluster %s has manifests", g.cluster.ID)
return err
}
err = g.providerRegistry.PreCreateManifestsHook(g.cluster, &envVars, g.workDir)
if err != nil {
log.WithError(err).Errorf("failed to run pre manifests creation hook '%s'", common.PlatformTypeValue(g.cluster.Platform.Type))
return err
}
err = g.importClusterTLSCerts(ctx)
if err != nil {
log.WithError(err).Error("Failed to import cluster TLS certs")
return err
}
err = g.runCreateCommand(ctx, installerPath, "manifests", envVars)
if err != nil {
return err
}
err = g.providerRegistry.PostCreateManifestsHook(g.cluster, &envVars, g.workDir)
if err != nil {
log.WithError(err).Errorf("failed to run post manifests creation hook '%s'", common.PlatformTypeValue(g.cluster.Platform.Type))
return err
}
// download manifests files to working directory
for _, manifest := range manifestFiles {
log.Infof("adding manifest %s to working dir for cluster %s", manifest, g.cluster.ID)
err = g.downloadManifest(ctx, manifest)
if err != nil {
log.WithError(err).Errorf("Failed to download manifest %s to working dir for cluster %s", manifest, g.cluster.ID)
return err
}
}
err = g.applyManifestPatches(ctx)
if err != nil {
log.WithError(err).Errorf("failed to apply manifests' patches for cluster '%s'", g.cluster.ID)
return err
}
err = g.applyInfrastructureCRPatch(ctx)
if err != nil {
log.WithError(err).Errorf("failed to patch the infrastructure CR manifest '%s'", common.PlatformTypeValue(g.cluster.Platform.Type))
return err
}
if swag.StringValue(g.cluster.HighAvailabilityMode) == models.ClusterHighAvailabilityModeNone {
err = g.bootstrapInPlaceIgnitionsCreate(ctx, installerPath, envVars)
} else {
err = g.runCreateCommand(ctx, installerPath, "ignition-configs", envVars)
}
if err != nil {
log.Error(err)
return err
}
// parse ignition and update BareMetalHosts
bootstrapPath := filepath.Join(g.workDir, "bootstrap.ign")
err = g.updateBootstrap(ctx, bootstrapPath)
if err != nil {
return err
}
err = g.updateIgnitions()
if err != nil {
log.Error(err)
return err
}
err = g.createHostIgnitions(g.serviceBaseURL, authType)
if err != nil {
log.Error(err)
return err
}
// move all files into the working directory
err = os.Rename(filepath.Join(g.workDir, "auth/kubeadmin-password"), filepath.Join(g.workDir, "kubeadmin-password"))
if err != nil {
return err
}
// after installation completes, a new kubeconfig will be created and made
// available that includes ingress details, so we rename this one
err = os.Rename(filepath.Join(g.workDir, "auth/kubeconfig"), filepath.Join(g.workDir, "kubeconfig-noingress"))
if err != nil {
return err
}
// We want to save install-config.yaml
// Installer deletes it so we need to write it one more time
err = os.WriteFile(installConfigPath, installConfig, 0600)
if err != nil {
log.Errorf("Failed to write file %s", installConfigPath)
return err
}
err = os.Remove(filepath.Join(g.workDir, "auth"))
if err != nil {
return err
}
return nil
}
func (g *installerGenerator) addBootstrapKubeletIpIfRequired(log logrus.FieldLogger, envVars []string) ([]string, error) {
// setting bootstrap kubelet node ip
// We don't want to set bootstrap ip in None platform as user can't set machine cidr
//and we can choose the wrong one
log.Debugf("Adding bootstrap ip to env vars")
if !swag.BoolValue(g.cluster.UserManagedNetworking) || common.IsSingleNodeCluster(g.cluster) {
bootstrapIp, err := network.GetPrimaryMachineCIDRIP(common.GetBootstrapHost(g.cluster), g.cluster)
if err != nil {
log.WithError(err).Warn("Failed to get bootstrap primary ip for kubelet service update.")
return envVars, err
}
envVars = append(envVars, "OPENSHIFT_INSTALL_BOOTSTRAP_NODE_IP="+bootstrapIp)
}
return envVars, nil
}
func (g *installerGenerator) applyManifestPatches(ctx context.Context) error {
log := logutil.FromContext(ctx, g.log)
manifestsOpenShiftDir := filepath.Join(g.workDir, "openshift")
// File path walks the directory in lexical order, which means it's possible to have some control on
// how files are being walked through by using a numeric prefix for the patch extension. For example:
// - cluster-scheduler-02-config.yml.patch_01_set_schedulable_masters
// - cluster-scheduler-02-config.yml.patch_02_something_else
err := filepath.Walk(manifestsOpenShiftDir, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
// We allow files that have the following extension .y(a)ml.patch(_something).
// This allows to pushing multuple patches for the same Manifest.
extension := filepath.Ext(info.Name())
if !strings.HasPrefix(extension, ".patch") {
return nil
}
// This is the path to the patch
manifestPatchPath := filepath.Join(manifestsOpenShiftDir, info.Name())
log.Debugf("Applying the following patch: %s", manifestPatchPath)
manifestPatch, err := os.ReadFile(manifestPatchPath)
if err != nil {
return errors.Wrapf(err, "failed to read manifest patch %s", manifestPatchPath)
}
log.Debugf("read the manifest at %s", manifestPatchPath)
// Let's look for the actual manifest. Code first looks in the `openshift` directory and
// fallsback to the `manifests` directory if no patch was found in the former.
manifestPath := filepath.Join(manifestsOpenShiftDir, strings.TrimSuffix(info.Name(), extension))
if _, err = os.Stat(manifestPath); errors.Is(err, os.ErrNotExist) {
log.Debugf("Manifest %s does not exist. Trying with the openshift dir next")
manifestPath = filepath.Join(g.workDir, "manifests", strings.TrimSuffix(info.Name(), extension))
}
data, err := os.ReadFile(manifestPath)
if err != nil {
return errors.Wrapf(err, "failed to read manifest %s", manifestPath)
}
log.Debugf("read the manifest at %s", manifestPath)
// Let's apply the patch now since both files have been read
data, err = common.ApplyYamlPatch(data, manifestPatch)
if err != nil {
return errors.Wrapf(err, "failed to patch manifest \"%s\"", manifestPath)
}
log.Debugf("applied the yaml patch to the manifest at %s: \n %s", manifestPath, string(data[:]))
err = os.WriteFile(manifestPath, data, 0600)
if err != nil {
return errors.Wrapf(err, "failed to write manifest \"%s\"", manifestPath)
}
log.Debugf("wrote the resulting manifest at %s", manifestPath)
err = os.Remove(manifestPatchPath)
if err != nil {
return errors.Wrapf(err, "failed to remove patch %s", manifestPatchPath)
}
return nil
})
if err != nil {
return errors.Wrapf(err, "failed to apply patches")
}
return nil
}
func (g *installerGenerator) applyInfrastructureCRPatch(ctx context.Context) error {
log := logutil.FromContext(ctx, g.log)
// We are only patching the InfrastructureCR if the hosts count is 4
// and the three masters are schedulable.
if len(g.cluster.Hosts) != 4 {
log.Debugf("number of hosts is different than 4, no need to patch the Infrastructure CR %d", len(g.cluster.Hosts))
return nil
}
log.Infof("Patching Infrastructure CR: Number of hosts: %d", len(g.cluster.Hosts))
infraManifest := filepath.Join(g.workDir, "manifests", "cluster-infrastructure-02-config.yml")
data, err := os.ReadFile(infraManifest)
if err != nil {
return errors.Wrapf(err, "failed to read Infrastructure Manifest \"%s\"", infraManifest)
}
log.Debugf("read the infrastructure manifest at %s", infraManifest)
data, err = common.ApplyYamlPatch(data, []byte(highlyAvailableInfrastructureTopologyPatch))
if err != nil {
return errors.Wrapf(err, "failed to patch Infrastructure Manifest \"%s\"", infraManifest)
}
log.Debugf("applied the yaml patch to the infrastructure manifest at %s: \n %s", infraManifest, string(data[:]))
err = os.WriteFile(infraManifest, data, 0600)
if err != nil {
return errors.Wrapf(err, "failed to write Infrastructure Manifest \"%s\"", infraManifest)
}
log.Debugf("wrote the resulting infrastructure manifest at %s", infraManifest)
return nil
}
func (g *installerGenerator) importClusterTLSCerts(ctx context.Context) error {
if g.clusterTLSCertOverrideDir == "" {
return nil
}
log := logutil.FromContext(ctx, g.log).WithField("inputDir", g.clusterTLSCertOverrideDir)
log.Debug("Checking for cluster TLS certs dir")
entries, err := os.ReadDir(g.clusterTLSCertOverrideDir)
if err != nil && !os.IsNotExist(err) {
return errors.Wrapf(err, "failed to read cluster TLS certs dir \"%s\"", g.clusterTLSCertOverrideDir)
}
log.Info("Found cluster TLS certs dir")
outDir := filepath.Join(g.workDir, "tls")
log = log.WithField("outputDir", outDir).WithField("cluster", g.cluster.ID)
if err := os.Mkdir(outDir, 0755); err != nil {
return errors.Wrapf(err, "failed to create cluster TLS certs output dir \"%s\"", outDir)
}
log.Info("Created cluster TLS certs dir")
tlsFS := os.DirFS(g.clusterTLSCertOverrideDir)
copyFile := func(filename string) error {
log.WithField("filename", filename).Info("Copying cluster TLS cert file")
f, err := tlsFS.Open(filename)
if err != nil {
return errors.Wrapf(err, "failed to open cluster TLS cert file \"%s\"", filename)
}
defer f.Close()
c, err := io.ReadAll(f)
if err != nil {
return errors.Wrapf(err, "failed to read cluster TLS cert file \"%s\"", filename)
}
err = os.WriteFile(filepath.Join(outDir, filename), c, 0600)
if err != nil {
return errors.Wrapf(err, "failed to write cluster TLS cert file \"%s\"", filename)
}
return nil
}
for _, e := range entries {
if !e.Type().IsRegular() {
continue
}
if err := copyFile(e.Name()); err != nil {
return err
}
}
return nil
}
func (g *installerGenerator) bootstrapInPlaceIgnitionsCreate(ctx context.Context, installerPath string, envVars []string) error {
err := g.runCreateCommand(ctx, installerPath, "single-node-ignition-config", envVars)
if err != nil {
return errors.Wrapf(err, "Failed to create single node ignitions")
}
bootstrapPath := filepath.Join(g.workDir, "bootstrap.ign")
// In case of single node rename bootstrap Ignition file
err = os.Rename(filepath.Join(g.workDir, "bootstrap-in-place-for-live-iso.ign"), bootstrapPath)
if err != nil {
return errors.Wrapf(err, "Failed to rename bootstrap-in-place-for-live-iso.ign")
}
bootstrapConfig, err := parseIgnitionFile(bootstrapPath)
if err != nil {
return err
}
//Although BIP works with 4.8 and above we want to support early 4.8 CI images
// To that end we set the dummy master ignition version to the same version as the bootstrap ignition
config := config_latest_types.Config{Ignition: config_latest_types.Ignition{Version: bootstrapConfig.Ignition.Version}}
for _, file := range []string{masterIgn, workerIgn} {
err = writeIgnitionFile(filepath.Join(g.workDir, file), &config)
if err != nil {
return errors.Wrapf(err, "Failed to create %s", file)
}
}
return nil
}
func getHostnames(hosts []*models.Host) []string {
ret := make([]string, 0)
for _, h := range hosts {
ret = append(ret, hostutil.GetHostnameForMsg(h))
}
return ret
}
func bmhIsMaster(bmh *bmh_v1alpha1.BareMetalHost, masterHostnames, workerHostnames []string) bool {
if funk.ContainsString(masterHostnames, bmh.Name) {
return true
}
if funk.ContainsString(workerHostnames, bmh.Name) {
return false
}
// For backward compatibility in case the name is not in the (masterHostnames, workerHostnames)
return strings.Contains(bmh.Name, "-master-")
}
type clusterVersion struct {
APIVersion string `yaml:"apiVersion"`
Metadata struct {
Namespace string `yaml:"namespace"`
Name string `yaml:"name"`
} `yaml:"metadata"`
Spec struct {
Upstream string `yaml:"upstream"`
Channel string `yaml:"channel"`
ClusterID string `yaml:"clusterID"`
} `yaml:"spec"`
}
// ExtractClusterID gets a local path of a "bootstrap.ign" file and extracts the OpenShift cluster ID
func ExtractClusterID(reader io.ReadCloser) (string, error) {
bs, err := io.ReadAll(reader)
if err != nil {
return "", err
}
config, err := ParseToLatest(bs)
if err != nil {
return "", err
}
for _, f := range config.Storage.Files {
if f.Node.Path != "/opt/openshift/manifests/cvo-overrides.yaml" {
continue
}
source := f.FileEmbedded1.Contents.Key()
dataURL, err := dataurl.DecodeString(source)
if err != nil {
return "", err
}
cv := clusterVersion{}
err = yaml.Unmarshal(dataURL.Data, &cv)
if err != nil {
return "", err
}
if cv.Spec.ClusterID == "" {
return "", errors.New("no ClusterID field in cvo-overrides file")
}
return cv.Spec.ClusterID, nil
}
return "", errors.New("could not find cvo-overrides file")
}
// updateBootstrap adds a status annotation to each BareMetalHost defined in the
// bootstrap ignition file
func (g *installerGenerator) updateBootstrap(ctx context.Context, bootstrapPath string) error {
log := logutil.FromContext(ctx, g.log)
//nolint:shadow
config, err := parseIgnitionFile(bootstrapPath)
if err != nil {
g.log.Error(err)
return err
}
newFiles := []config_latest_types.File{}
masters, workers := sortHosts(g.cluster.Hosts)
for i, file := range config.Storage.Files {
switch {
case isBaremetalProvisioningConfig(&config.Storage.Files[i]):
if !g.enableMetal3Provisioning {
// drop this from the list of Files because we don't want to run BMO
continue
}
case isMOTD(&config.Storage.Files[i]):
// workaround for https://github.com/openshift/machine-config-operator/issues/2086
g.fixMOTDFile(&config.Storage.Files[i])
case isBMHFile(&config.Storage.Files[i]):
// extract bmh
bmh, err2 := fileToBMH(&config.Storage.Files[i]) //nolint,shadow
if err2 != nil {
log.Errorf("error parsing File contents to BareMetalHost: %v", err2)
return err2
}
// get corresponding host
var host *models.Host
masterHostnames := getHostnames(masters)
workerHostnames := getHostnames(workers)
// The BMH files in the ignition are sorted according to hostname (please see the implementation in installcfg/installcfg.go).
// The masters and workers are also sorted by hostname. This enables us to correlate correctly the host and the BMH file
if bmhIsMaster(bmh, masterHostnames, workerHostnames) {
if len(masters) == 0 {
return errors.Errorf("Not enough registered masters to match with BareMetalHosts")
}
host, masters = masters[0], masters[1:]
} else {
if len(workers) == 0 {
return errors.Errorf("Not enough registered workers to match with BareMetalHosts")
}
host, workers = workers[0], workers[1:]
}
// modify bmh
log.Infof("modifying BareMetalHost ignition file %s", file.Node.Path)
err = g.modifyBMHFile(&config.Storage.Files[i], bmh, host)
if err != nil {
return err
}
}
newFiles = append(newFiles, config.Storage.Files[i])
}
config.Storage.Files = newFiles
if swag.StringValue(g.cluster.HighAvailabilityMode) != models.ClusterHighAvailabilityModeNone {
setFileInIgnition(config, "/opt/openshift/assisted-install-bootstrap", "data:,", false, 420, false)
}
// add new Network Manager config file that disables handling of /etc/resolv.conf
// as there is no network scripts added in SNO mode (None) we should not touch Netmanager config
if !common.IsSingleNodeCluster(g.cluster) {
setNMConfigration(config)
}
err = writeIgnitionFile(bootstrapPath, config)
if err != nil {
log.Error(err)
return err
}
log.Infof("Updated file %s", bootstrapPath)
return nil
}
func setNMConfigration(config *config_latest_types.Config) {
fileContents := "data:text/plain;charset=utf-8;base64," + base64.StdEncoding.EncodeToString([]byte(common.UnmanagedResolvConf))
setFileInIgnition(config, "/etc/NetworkManager/conf.d/99-kni.conf", fileContents, false, 420, false)
}
func isBMHFile(file *config_latest_types.File) bool {
return strings.Contains(file.Node.Path, "openshift-cluster-api_hosts")
}
func isMOTD(file *config_latest_types.File) bool {
return file.Node.Path == "/etc/motd"
}
func isBaremetalProvisioningConfig(file *config_latest_types.File) bool {
return strings.Contains(file.Node.Path, "baremetal-provisioning-config")
}
func fileToBMH(file *config_latest_types.File) (*bmh_v1alpha1.BareMetalHost, error) {
parts := strings.Split(*file.Contents.Source, "base64,")
if len(parts) != 2 {
return nil, errors.Errorf("could not parse source for file %s", file.Node.Path)
}
decoded, err := base64.StdEncoding.DecodeString(parts[1])
if err != nil {
return nil, err
}
bmh := &bmh_v1alpha1.BareMetalHost{}
_, _, err = scheme.Codecs.UniversalDeserializer().Decode(decoded, nil, bmh)
if err != nil {
return nil, err
}
return bmh, nil
}
// fixMOTDFile is a workaround for a bug in machine-config-operator, where it
// incorrectly parses igition when a File is configured to append content
// instead of overwrite. Currently, /etc/motd is the only file involved in
// provisioning that is configured for appending. This code converts it to
// overwriting the existing /etc/motd with whatever content had been indended
// to be appened.
// https://github.com/openshift/machine-config-operator/issues/2086
func (g *installerGenerator) fixMOTDFile(file *config_latest_types.File) {
if file.Contents.Source != nil {
// the bug only happens if Source == nil, so no need to take action
return
}
if len(file.Append) == 1 {
file.Contents.Source = file.Append[0].Source
file.Append = file.Append[:0]
return
}
g.log.Info("could not apply workaround to file /etc/motd for MCO bug. The workaround may no longer be necessary.")
}
// modifyBMHFile modifies the File contents so that the serialized BareMetalHost
// includes a status annotation
func (g *installerGenerator) modifyBMHFile(file *config_latest_types.File, bmh *bmh_v1alpha1.BareMetalHost, host *models.Host) error {
inventory := models.Inventory{}
err := json.Unmarshal([]byte(host.Inventory), &inventory)
if err != nil {
return err
}
hw := bmh_v1alpha1.HardwareDetails{
CPU: bmh_v1alpha1.CPU{
Arch: inventory.CPU.Architecture,
Model: inventory.CPU.ModelName,
ClockMegahertz: bmh_v1alpha1.ClockSpeed(inventory.CPU.Frequency),
Flags: inventory.CPU.Flags,
Count: int(inventory.CPU.Count),
},
Hostname: host.RequestedHostname,
NIC: make([]bmh_v1alpha1.NIC, len(inventory.Interfaces)),
Storage: make([]bmh_v1alpha1.Storage, len(inventory.Disks)),
}
if inventory.Memory != nil {
hw.RAMMebibytes = int(inventory.Memory.PhysicalBytes / 1024 / 1024)
}
for i, iface := range inventory.Interfaces {
hw.NIC[i] = bmh_v1alpha1.NIC{
Name: iface.Name,
Model: iface.Product,
MAC: iface.MacAddress,
SpeedGbps: int(iface.SpeedMbps / 1024),
}
switch {
case len(iface.IPV4Addresses) > 0:
hw.NIC[i].IP = g.selectInterfaceIPInsideMachineCIDR(iface.IPV4Addresses)
case len(iface.IPV6Addresses) > 0:
hw.NIC[i].IP = g.selectInterfaceIPInsideMachineCIDR(iface.IPV6Addresses)
}
}
for i, disk := range inventory.Disks {
device := disk.Path
if disk.ByPath != "" {
device = disk.ByPath
}
hw.Storage[i] = bmh_v1alpha1.Storage{
Name: device,
Vendor: disk.Vendor,
SizeBytes: bmh_v1alpha1.Capacity(disk.SizeBytes),
Model: disk.Model,
WWN: disk.Wwn,
HCTL: disk.Hctl,
SerialNumber: disk.Serial,
Rotational: (disk.DriveType == models.DriveTypeHDD),
}
}
if inventory.SystemVendor != nil {
hw.SystemVendor = bmh_v1alpha1.HardwareSystemVendor{
Manufacturer: inventory.SystemVendor.Manufacturer,
ProductName: inventory.SystemVendor.ProductName,
SerialNumber: inventory.SystemVendor.SerialNumber,
}
}
status := bmh_v1alpha1.BareMetalHostStatus{
HardwareDetails: &hw,
PoweredOn: true,
}
statusJSON, err := json.Marshal(status)
if err != nil {
return err
}
metav1.SetMetaDataAnnotation(&bmh.ObjectMeta, bmh_v1alpha1.StatusAnnotation, string(statusJSON))
if g.enableMetal3Provisioning {
bmh.Spec.ExternallyProvisioned = true
}
serializer := k8sjson.NewSerializerWithOptions(
k8sjson.DefaultMetaFactory, nil, nil,
k8sjson.SerializerOptions{
Yaml: true,
Pretty: true,
Strict: true,
},
)
buf := bytes.Buffer{}
err = serializer.Encode(bmh, &buf)
if err != nil {
return err
}
// remove status if exists
res := bytes.Split(buf.Bytes(), []byte("status:\n"))
encodedBMH := base64.StdEncoding.EncodeToString(res[0])
source := "data:text/plain;charset=utf-8;base64," + encodedBMH
file.Contents.Source = &source
return nil
}
func (g *installerGenerator) updateDhcpFiles() error {
path := filepath.Join(g.workDir, masterIgn)
config, err := parseIgnitionFile(path)
if err != nil {
return err
}
setFileInIgnition(config, "/etc/keepalived/unsupported-monitor.conf", g.encodedDhcpFileContents, false, 0o644, false)
encodedApiVip := network.GetEncodedApiVipLease(g.cluster)
if encodedApiVip != "" {
setFileInIgnition(config, "/etc/keepalived/lease-api", encodedApiVip, false, 0o644, false)
}
encodedIngressVip := network.GetEncodedIngressVipLease(g.cluster)