github.com/openshift/installer@v1.4.17/pkg/asset/imagebased/image/ignition_test.go (about)

     1  package image
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"os"
     7  	"path"
     8  	"testing"
     9  
    10  	"github.com/containers/image/v5/pkg/sysregistriesv2"
    11  	igntypes "github.com/coreos/ignition/v2/config/v3_2/types"
    12  	"github.com/pelletier/go-toml"
    13  	"github.com/stretchr/testify/assert"
    14  	"github.com/vincent-petithory/dataurl"
    15  
    16  	aiv1beta1 "github.com/openshift/assisted-service/api/v1beta1"
    17  	"github.com/openshift/installer/pkg/asset"
    18  	"github.com/openshift/installer/pkg/types"
    19  )
    20  
    21  var (
    22  	testCert = `-----BEGIN CERTIFICATE-----
    23  MIICYTCCAcqgAwIBAgIJAI2kA+uXAbhOMA0GCSqGSIb3DQEBCwUAMEgxCzAJBgNV
    24  BAYTAlVTMQswCQYDVQQIDAJDQTEWMBQGA1UEBwwNU2FuIEZyYW5jaXNjbzEUMBIG
    25  A1UECgwLUmVkIEhhdCBJbmMwHhcNMTkwMjEyMTkzMjUzWhcNMTkwMjEzMTkzMjUz
    26  WjBIMQswCQYDVQQGEwJVUzELMAkGA1UECAwCQ0ExFjAUBgNVBAcMDVNhbiBGcmFu
    27  Y2lzY28xFDASBgNVBAoMC1JlZCBIYXQgSW5jMIGfMA0GCSqGSIb3DQEBAQUAA4GN
    28  ADCBiQKBgQC+HOC0mKig/oINAKPo88LqxDJ4l7lozdLtp5oGeqWrLUXSfkvXAkQY
    29  2QYdvPAjpRfH7Ii7G0Asx+HTKdvula7B5fXDjc6NYKuEpTJZRV1ugntI97bozF/E
    30  C2BBmxxEnJN3+Xe8RYXMjz5Q4aqPw9vZhlWN+0hrREl1Ea/zHuWFIQIDAQABo1Mw
    31  UTAdBgNVHQ4EFgQUvTS1XjlvOdsufSyWxukyQu3LriEwHwYDVR0jBBgwFoAUvTS1
    32  XjlvOdsufSyWxukyQu3LriEwDwYDVR0TAQH/BAUwAwEB/zANBgkqhkiG9w0BAQsF
    33  AAOBgQB9gFcOXnzJrM65QqxeCB9Z5l5JMjp45UFC9Bj2cgwDHP80Zvi4omlaacC6
    34  aavmnLd67zm9PbYDWRaOIWAMeB916Iwaw/v6I0jwhAk/VxX5Fl6cGlZu9jZ3zbFE
    35  2sDqkwzIuSjCG2A23s6d4M1S3IXCCydoCSLMu+WhLkbboK6jEg==
    36  -----END CERTIFICATE-----
    37  `
    38  )
    39  
    40  func TestIgnition_Generate(t *testing.T) {
    41  	// This patch currently allows testing the Ignition asset using the embedded resources.
    42  	// TODO: Replace it by mocking the filesystem in bootstrap.AddStorageFiles()
    43  	workingDirectory, err := os.Getwd()
    44  	assert.NoError(t, err)
    45  	err = os.Chdir(path.Join(workingDirectory, "../../../../data"))
    46  	assert.NoError(t, err)
    47  
    48  	registriesConf := &RegistriesConf{
    49  		Config: &sysregistriesv2.V2RegistriesConf{
    50  			Registries: []sysregistriesv2.Registry{
    51  				{
    52  					Endpoint:           sysregistriesv2.Endpoint{Location: "quay.io"},
    53  					MirrorByDigestOnly: true,
    54  					Mirrors:            []sysregistriesv2.Endpoint{{Location: "mirror-quay.io"}},
    55  				},
    56  			},
    57  		},
    58  	}
    59  	registriesConfData, err := toml.Marshal(registriesConf.Config)
    60  	assert.NoError(t, err)
    61  
    62  	testNetworkConfig := "interfaces:\n- ipv4:\n    address:\n    - ip: 192.168.122.21\n      prefix-length: 24\n    enabled: true\n  mac-address: 00:01:02:03:04:05\n  name: eth0\n  state: up\n  type: ethernet\n\n"
    63  
    64  	ignitionConfigOverride := `{"ignition": {"version": "3.2.0"}, "storage": {"files": [{"path": "/tmp/example", "contents": {"source": "data:text/plain;charset=utf-8;base64,aGVscGltdHJhcHBlZGluYXN3YWdnZXJzcGVj"}}]}}`
    65  
    66  	postDeploymentScript := "#!/bin/bash\necho \"Post image-based installation script\""
    67  
    68  	cases := []struct {
    69  		name         string
    70  		dependencies []asset.Asset
    71  
    72  		expectedError        string
    73  		expectedFiles        map[string]string
    74  		expectedSystemdUnits map[string]bool
    75  	}{
    76  		{
    77  			name: "comprehensive configuration",
    78  			dependencies: []asset.Asset{
    79  				&ImageBasedInstallationConfig{
    80  					Config: ibiConfig().
    81  						imageDigestSources([]types.ImageDigestSource{
    82  							{
    83  								Source:  "quay.io",
    84  								Mirrors: []string{"mirror-quay.io"},
    85  							},
    86  						}).
    87  						additionalTrustBundle(testCert).
    88  						networkConfig(aiv1beta1.NetConfig{Raw: []byte(testNetworkConfig)}).
    89  						ignitionConfigOverride(ignitionConfigOverride).
    90  						build(),
    91  				},
    92  				&RegistriesConf{Data: registriesConfData},
    93  				&PostDeployment{File: &asset.File{
    94  					Filename: "post.sh",
    95  					Data:     []byte(postDeploymentScript),
    96  				}},
    97  			},
    98  
    99  			expectedFiles: map[string]string{
   100  				"/var/tmp/pull-secret.json": "{\"auths\":{\"example.com\":{\"auth\":\"c3VwZXItc2VjcmV0Cg==\"}}}\n",
   101  
   102  				"/usr/local/bin/install-rhcos-and-restore-seed.sh": `#!/bin/bash
   103  
   104  set -e # Halt on error
   105  
   106  seed_image=${1:-$SEED_IMAGE}
   107  authfile=${PULL_SECRET_FILE:-"/var/tmp/pull-secret.json"}
   108  ibi_config=${IBI_CONFIGURATION_FILE:-"/var/tmp/ibi-configuration.json"}
   109  
   110  # Copy the lca-cli binary to the host, pulling the seed image can sometimes fail
   111  until podman create --authfile "${authfile}" --name lca-cli "${seed_image}" lca-cli ; do
   112      sleep 10
   113  done
   114  podman cp lca-cli:lca-cli /usr/local/bin/lca-cli
   115  podman rm lca-cli
   116  
   117  /usr/local/bin/lca-cli ibi -f "${ibi_config}"
   118  `,
   119  
   120  				"/var/tmp/ibi-configuration.json": "{\"extraPartitionLabel\":\"varlibcontainers\",\"extraPartitionNumber\":5,\"extraPartitionStart\":\"-40G\",\"installationDisk\":\"/dev/vda\",\"seedImage\":\"quay.io/openshift-kni/seed-image:4.16.0\",\"seedVersion\":\"4.16.0\"}\n",
   121  
   122  				"/etc/containers/registries.conf": "credential-helpers = []\nshort-name-mode = \"\"\nunqualified-search-registries = []\n\n[[registry]]\n  location = \"quay.io\"\n  mirror-by-digest-only = true\n  prefix = \"\"\n\n  [[registry.mirror]]\n    location = \"mirror-quay.io\"\n",
   123  
   124  				"/etc/pki/ca-trust/source/anchors/additional-trust-bundle.pem": testCert,
   125  
   126  				"/var/tmp/network-config.yaml": testNetworkConfig + "\n",
   127  
   128  				"/tmp/example": "helpimtrappedinaswaggerspec",
   129  
   130  				"/var/tmp/post.sh": "#!/bin/bash\necho \"Post image-based installation script\"",
   131  			},
   132  			expectedSystemdUnits: map[string]bool{
   133  				"install-rhcos-and-restore-seed.service": true,
   134  
   135  				"network-config.service": true,
   136  			},
   137  		},
   138  	}
   139  
   140  	for _, tc := range cases {
   141  		t.Run(tc.name, func(t *testing.T) {
   142  			parents := asset.Parents{}
   143  			parents.Add(tc.dependencies...)
   144  
   145  			ignitionAsset := &Ignition{}
   146  			err := ignitionAsset.Generate(context.Background(), parents)
   147  
   148  			if tc.expectedError != "" {
   149  				assert.Equal(t, tc.expectedError, err.Error())
   150  			} else {
   151  				assert.NoError(t, err)
   152  
   153  				assertFiles(t, ignitionAsset.Config, tc.expectedFiles)
   154  
   155  				assertSystemdUnits(t, ignitionAsset.Config, tc.expectedSystemdUnits)
   156  			}
   157  		})
   158  	}
   159  }
   160  
   161  func assertFiles(t *testing.T, config *igntypes.Config, files map[string]string) {
   162  	t.Helper()
   163  
   164  	if len(files) > 0 {
   165  		assert.Equal(t, len(files), len(config.Storage.Files))
   166  
   167  		for name, content := range files {
   168  			found := false
   169  			for _, i := range config.Storage.Files {
   170  				if i.Node.Path == name {
   171  					actualData, err := dataurl.DecodeString(*i.FileEmbedded1.Contents.Source)
   172  					assert.NoError(t, err)
   173  					assert.Equal(t, content, string(actualData.Data))
   174  
   175  					found = true
   176  					break
   177  				}
   178  			}
   179  			assert.True(t, found, fmt.Sprintf("expected file %s not found", name))
   180  		}
   181  	}
   182  }
   183  
   184  func assertSystemdUnits(t *testing.T, config *igntypes.Config, units map[string]bool) {
   185  	t.Helper()
   186  
   187  	for name, enabled := range units {
   188  		for _, unit := range config.Systemd.Units {
   189  			if unit.Name != name {
   190  				continue
   191  			}
   192  
   193  			if unit.Enabled == nil {
   194  				assert.Equal(t, enabled, false)
   195  			} else {
   196  				assert.Equal(t, enabled, *unit.Enabled)
   197  			}
   198  		}
   199  	}
   200  }