repo_name
stringlengths 1
52
| repo_creator
stringclasses 6
values | programming_language
stringclasses 4
values | code
stringlengths 0
9.68M
| num_lines
int64 1
234k
|
---|---|---|---|---|
eks-anywhere | aws | Go | package framework
import "testing"
// T defines test support functionality, ala the Go stdlib testing.T.
//
// Being able to change its implementation supports logging functionality for
// test support methods that are executed outside of a test, such as when
// bringing up or tearing down test clusters that will be used and re-used
// throughout multiple tests.
//
// Only those methods currently in use are defined. Add more methods from
// stdlib testing.T as necessary.
type T interface {
Cleanup(func())
Error(...any)
Errorf(string, ...any)
Fail()
FailNow()
Failed() bool
Fatal(...any)
Fatalf(string, ...any)
Helper()
Log(args ...any)
Logf(format string, args ...any)
Name() string
Parallel()
Run(string, func(*testing.T)) bool
Setenv(string, string)
Skip(...any)
SkipNow()
Skipf(string, ...any)
Skipped() bool
TempDir() string
}
// T ensures that *testing.T implements T, to detect API drift.
var _ T = (*testing.T)(nil)
// LoggingOnlyT implements select logging and error handling functionality of T.
//
// Most non-logging, non-error reporting methods will simply panic.
type LoggingOnlyT struct{}
// NewLoggingOnlyT creates a LoggingOnlyT, which does what its name implies.
func NewLoggingOnlyT() *LoggingOnlyT { return &LoggingOnlyT{} }
// Cleanup implements T.
func (t LoggingOnlyT) Cleanup(_ func()) {
panic("LoggingOnlyT implements only the logging methods of T")
}
// Error implements T.
func (t LoggingOnlyT) Error(_ ...any) {
panic("LoggingOnlyT implements only the logging methods of T")
}
// Errorf implements T.
func (t LoggingOnlyT) Errorf(_ string, _ ...any) {
panic("LoggingOnlyT implements only the logging methods of T")
}
// Fail implements T.
func (t LoggingOnlyT) Fail() {
panic("LoggingOnlyT implements only the logging methods of T")
}
// FailNow implements T.
func (t LoggingOnlyT) FailNow() {
panic("LoggingOnlyT implements only the logging methods of T")
}
// Failed implements T.
func (t LoggingOnlyT) Failed() bool {
panic("LoggingOnlyT implements only the logging methods of T")
}
// Fatal implements T.
func (t LoggingOnlyT) Fatal(_ ...any) {
v := &testing.T{}
v.Fatal("foo")
// panic("LoggingOnlyT implements only the logging methods of T")
}
// Fatalf implements T.
func (t LoggingOnlyT) Fatalf(format string, args ...any) {
v := &testing.T{}
v.Fatalf(format, args...)
}
// Helper implements T.
func (t LoggingOnlyT) Helper() {
panic("LoggingOnlyT implements only the logging methods of T")
}
// Log implements T.
func (t LoggingOnlyT) Log(args ...any) {
(&testing.T{}).Log(args...)
}
// Logf implements T.
func (t LoggingOnlyT) Logf(format string, args ...any) {
(&testing.T{}).Logf(format, args...)
}
// Name implements T.
func (t LoggingOnlyT) Name() string {
panic("LoggingOnlyT implements only the logging methods of T")
}
// Parallel implements T.
func (t LoggingOnlyT) Parallel() {
panic("LoggingOnlyT implements only the logging methods of T")
}
// Run implements T.
func (t LoggingOnlyT) Run(_ string, _ func(*testing.T)) bool {
panic("LoggingOnlyT implements only the logging methods of T")
}
// Setenv implements T.
func (t LoggingOnlyT) Setenv(_ string, _ string) {
panic("LoggingOnlyT implements only the logging methods of T")
}
// Skip implements T.
func (t LoggingOnlyT) Skip(_ ...any) {
panic("LoggingOnlyT implements only the logging methods of T")
}
// SkipNow implements T.
func (t LoggingOnlyT) SkipNow() {
panic("LoggingOnlyT implements only the logging methods of T")
}
// Skipf implements T.
func (t LoggingOnlyT) Skipf(_ string, _ ...any) {
panic("LoggingOnlyT implements only the logging methods of T")
}
// Skipped implements T.
func (t LoggingOnlyT) Skipped() bool {
panic("LoggingOnlyT implements only the logging methods of T")
}
// TempDir implements T.
func (t LoggingOnlyT) TempDir() string {
panic("LoggingOnlyT implements only the logging methods of T")
}
| 150 |
eks-anywhere | aws | Go | package framework
import (
"os"
"testing"
"github.com/aws/eks-anywhere/internal/pkg/api"
anywherev1 "github.com/aws/eks-anywhere/pkg/api/v1alpha1"
clusterf "github.com/aws/eks-anywhere/test/framework/cluster"
)
const (
TinkerbellProviderName = "tinkerbell"
tinkerbellBootstrapIPEnvVar = "T_TINKERBELL_BOOTSTRAP_IP"
tinkerbellControlPlaneNetworkCidrEnvVar = "T_TINKERBELL_CP_NETWORK_CIDR"
tinkerbellImageUbuntu123EnvVar = "T_TINKERBELL_IMAGE_UBUNTU_1_23"
tinkerbellImageUbuntu124EnvVar = "T_TINKERBELL_IMAGE_UBUNTU_1_24"
tinkerbellImageUbuntu125EnvVar = "T_TINKERBELL_IMAGE_UBUNTU_1_25"
tinkerbellImageUbuntu126EnvVar = "T_TINKERBELL_IMAGE_UBUNTU_1_26"
tinkerbellImageUbuntu127EnvVar = "T_TINKERBELL_IMAGE_UBUNTU_1_27"
tinkerbellImageRedHat123EnvVar = "T_TINKERBELL_IMAGE_REDHAT_1_23"
tinkerbellImageRedHat124EnvVar = "T_TINKERBELL_IMAGE_REDHAT_1_24"
tinkerbellImageRedHat125EnvVar = "T_TINKERBELL_IMAGE_REDHAT_1_25"
tinkerbellImageRedHat126EnvVar = "T_TINKERBELL_IMAGE_REDHAT_1_26"
tinkerbellImageRedHat127EnvVar = "T_TINKERBELL_IMAGE_REDHAT_1_27"
tinkerbellInventoryCsvFilePathEnvVar = "T_TINKERBELL_INVENTORY_CSV"
tinkerbellSSHAuthorizedKey = "T_TINKERBELL_SSH_AUTHORIZED_KEY"
TinkerbellCIEnvironment = "T_TINKERBELL_CI_ENVIRONMENT"
)
var requiredTinkerbellEnvVars = []string{
tinkerbellControlPlaneNetworkCidrEnvVar,
tinkerbellImageUbuntu123EnvVar,
tinkerbellImageUbuntu124EnvVar,
tinkerbellImageUbuntu125EnvVar,
tinkerbellImageUbuntu126EnvVar,
tinkerbellImageUbuntu127EnvVar,
tinkerbellImageRedHat123EnvVar,
tinkerbellImageRedHat124EnvVar,
tinkerbellImageRedHat125EnvVar,
tinkerbellImageRedHat126EnvVar,
tinkerbellImageRedHat127EnvVar,
tinkerbellInventoryCsvFilePathEnvVar,
tinkerbellSSHAuthorizedKey,
}
func RequiredTinkerbellEnvVars() []string {
return requiredTinkerbellEnvVars
}
type TinkerbellOpt func(*Tinkerbell)
type Tinkerbell struct {
t *testing.T
fillers []api.TinkerbellFiller
clusterFillers []api.ClusterFiller
serverIP string
cidr string
inventoryCsvFilePath string
}
func UpdateTinkerbellUbuntuTemplate123Var() api.TinkerbellFiller {
return api.WithStringFromEnvVarTinkerbell(tinkerbellImageUbuntu123EnvVar, api.WithTinkerbellOSImageURL)
}
// UpdateTinkerbellUbuntuTemplate124Var updates the tinkerbell template.
func UpdateTinkerbellUbuntuTemplate124Var() api.TinkerbellFiller {
return api.WithStringFromEnvVarTinkerbell(tinkerbellImageUbuntu124EnvVar, api.WithTinkerbellOSImageURL)
}
// UpdateTinkerbellUbuntuTemplate125Var updates the tinkerbell template.
func UpdateTinkerbellUbuntuTemplate125Var() api.TinkerbellFiller {
return api.WithStringFromEnvVarTinkerbell(tinkerbellImageUbuntu125EnvVar, api.WithTinkerbellOSImageURL)
}
// UpdateTinkerbellUbuntuTemplate126Var updates the tinkerbell template.
func UpdateTinkerbellUbuntuTemplate126Var() api.TinkerbellFiller {
return api.WithStringFromEnvVarTinkerbell(tinkerbellImageUbuntu126EnvVar, api.WithTinkerbellOSImageURL)
}
// UpdateTinkerbellUbuntuTemplate127Var updates the tinkerbell template.
func UpdateTinkerbellUbuntuTemplate127Var() api.TinkerbellFiller {
return api.WithStringFromEnvVarTinkerbell(tinkerbellImageUbuntu127EnvVar, api.WithTinkerbellOSImageURL)
}
// UpdateTinkerbellMachineSSHAuthorizedKey updates a tinkerbell machine configs SSHAuthorizedKey.
func UpdateTinkerbellMachineSSHAuthorizedKey() api.TinkerbellMachineFiller {
return api.WithStringFromEnvVarTinkerbellMachineFiller(tinkerbellSSHAuthorizedKey, api.WithSSHAuthorizedKeyForTinkerbellMachineConfig)
}
func NewTinkerbell(t *testing.T, opts ...TinkerbellOpt) *Tinkerbell {
checkRequiredEnvVars(t, requiredTinkerbellEnvVars)
cidr := os.Getenv(tinkerbellControlPlaneNetworkCidrEnvVar)
serverIP, err := GetIP(cidr, ClusterIPPoolEnvVar)
if err != nil {
t.Fatalf("failed to get tinkerbell ip for test environment: %v", err)
}
tink := &Tinkerbell{
t: t,
fillers: []api.TinkerbellFiller{
api.WithTinkerbellServer(serverIP),
api.WithStringFromEnvVarTinkerbell(tinkerbellSSHAuthorizedKey, api.WithSSHAuthorizedKeyForAllTinkerbellMachines),
api.WithHardwareSelectorLabels(),
},
}
tink.serverIP = serverIP
tink.cidr = cidr
tink.inventoryCsvFilePath = os.Getenv(tinkerbellInventoryCsvFilePathEnvVar)
for _, opt := range opts {
opt(tink)
}
return tink
}
func (t *Tinkerbell) Name() string {
return TinkerbellProviderName
}
func (t *Tinkerbell) Setup() {}
// UpdateKubeConfig customizes generated kubeconfig for the provider.
func (t *Tinkerbell) UpdateKubeConfig(content *[]byte, clusterName string) error {
return nil
}
// ClusterConfigUpdates satisfies the test framework Provider.
func (t *Tinkerbell) ClusterConfigUpdates() []api.ClusterConfigFiller {
clusterIP, err := GetIP(t.cidr, ClusterIPPoolEnvVar)
if err != nil {
t.t.Fatalf("failed to get cluster ip for test environment: %v", err)
}
f := make([]api.ClusterFiller, 0, len(t.clusterFillers)+1)
f = append(f, t.clusterFillers...)
f = append(f, api.WithControlPlaneEndpointIP(clusterIP))
return []api.ClusterConfigFiller{api.ClusterToConfigFiller(f...), api.TinkerbellToConfigFiller(t.fillers...)}
}
func (t *Tinkerbell) WithProviderUpgrade(fillers ...api.TinkerbellFiller) ClusterE2ETestOpt {
return func(e *ClusterE2ETest) {
e.UpdateClusterConfig(api.TinkerbellToConfigFiller(fillers...))
}
}
func (t *Tinkerbell) CleanupVMs(_ string) error {
return nil
}
// WithKubeVersionAndOS returns a cluster config filler that sets the cluster kube version and the right template for all
// tinkerbell machine configs.
func (t *Tinkerbell) WithKubeVersionAndOS(osFamily anywherev1.OSFamily, kubeVersion anywherev1.KubernetesVersion) api.ClusterConfigFiller {
// TODO: Update tests to use this
panic("Not implemented for Tinkerbell yet")
}
// WithNewWorkerNodeGroup returns an api.ClusterFiller that adds a new workerNodeGroupConfiguration and
// a corresponding TinkerbellMachineConfig to the cluster config.
func (t *Tinkerbell) WithNewWorkerNodeGroup(name string, workerNodeGroup *WorkerNodeGroup) api.ClusterConfigFiller {
// TODO: Implement for Tinkerbell provider
panic("Not implemented for Tinkerbell yet")
}
func WithUbuntu123Tinkerbell() TinkerbellOpt {
return func(t *Tinkerbell) {
t.fillers = append(t.fillers,
api.WithStringFromEnvVarTinkerbell(tinkerbellImageUbuntu123EnvVar, api.WithTinkerbellOSImageURL),
api.WithOsFamilyForAllTinkerbellMachines(anywherev1.Ubuntu),
)
}
}
// WithUbuntu124Tinkerbell tink test with ubuntu 1.24.
func WithUbuntu124Tinkerbell() TinkerbellOpt {
return func(t *Tinkerbell) {
t.fillers = append(t.fillers,
api.WithStringFromEnvVarTinkerbell(tinkerbellImageUbuntu124EnvVar, api.WithTinkerbellOSImageURL),
api.WithOsFamilyForAllTinkerbellMachines(anywherev1.Ubuntu),
)
}
}
// WithUbuntu125Tinkerbell tink test with ubuntu 1.25.
func WithUbuntu125Tinkerbell() TinkerbellOpt {
return func(t *Tinkerbell) {
t.fillers = append(t.fillers,
api.WithStringFromEnvVarTinkerbell(tinkerbellImageUbuntu125EnvVar, api.WithTinkerbellOSImageURL),
api.WithOsFamilyForAllTinkerbellMachines(anywherev1.Ubuntu),
)
}
}
// WithUbuntu126Tinkerbell tink test with ubuntu 1.26.
func WithUbuntu126Tinkerbell() TinkerbellOpt {
return func(t *Tinkerbell) {
t.fillers = append(t.fillers,
api.WithStringFromEnvVarTinkerbell(tinkerbellImageUbuntu126EnvVar, api.WithTinkerbellOSImageURL),
api.WithOsFamilyForAllTinkerbellMachines(anywherev1.Ubuntu),
)
}
}
// WithUbuntu127Tinkerbell tink test with ubuntu 1.27.
func WithUbuntu127Tinkerbell() TinkerbellOpt {
return func(t *Tinkerbell) {
t.fillers = append(t.fillers,
api.WithStringFromEnvVarTinkerbell(tinkerbellImageUbuntu127EnvVar, api.WithTinkerbellOSImageURL),
api.WithOsFamilyForAllTinkerbellMachines(anywherev1.Ubuntu),
)
}
}
// WithRedHat123Tinkerbell tink test with redhat 1.23.
func WithRedHat123Tinkerbell() TinkerbellOpt {
return func(t *Tinkerbell) {
t.fillers = append(t.fillers,
api.WithStringFromEnvVarTinkerbell(tinkerbellImageRedHat123EnvVar, api.WithTinkerbellOSImageURL),
api.WithOsFamilyForAllTinkerbellMachines(anywherev1.RedHat),
)
}
}
// WithRedHat124Tinkerbell tink test with redhat 1.24.
func WithRedHat124Tinkerbell() TinkerbellOpt {
return func(t *Tinkerbell) {
t.fillers = append(t.fillers,
api.WithStringFromEnvVarTinkerbell(tinkerbellImageRedHat124EnvVar, api.WithTinkerbellOSImageURL),
api.WithOsFamilyForAllTinkerbellMachines(anywherev1.RedHat),
)
}
}
// WithRedHat125Tinkerbell tink test with redhat 1.25.
func WithRedHat125Tinkerbell() TinkerbellOpt {
return func(t *Tinkerbell) {
t.fillers = append(t.fillers,
api.WithStringFromEnvVarTinkerbell(tinkerbellImageRedHat125EnvVar, api.WithTinkerbellOSImageURL),
api.WithOsFamilyForAllTinkerbellMachines(anywherev1.RedHat),
)
}
}
// WithRedHat126Tinkerbell tink test with redhat 1.26.
func WithRedHat126Tinkerbell() TinkerbellOpt {
return func(t *Tinkerbell) {
t.fillers = append(t.fillers,
api.WithStringFromEnvVarTinkerbell(tinkerbellImageRedHat126EnvVar, api.WithTinkerbellOSImageURL),
api.WithOsFamilyForAllTinkerbellMachines(anywherev1.RedHat),
)
}
}
// WithRedHat127Tinkerbell tink test with redhat 1.27.
func WithRedHat127Tinkerbell() TinkerbellOpt {
return func(t *Tinkerbell) {
t.fillers = append(t.fillers,
api.WithStringFromEnvVarTinkerbell(tinkerbellImageRedHat127EnvVar, api.WithTinkerbellOSImageURL),
api.WithOsFamilyForAllTinkerbellMachines(anywherev1.RedHat),
)
}
}
func WithBottleRocketTinkerbell() TinkerbellOpt {
return func(t *Tinkerbell) {
t.fillers = append(t.fillers,
api.WithOsFamilyForAllTinkerbellMachines(anywherev1.Bottlerocket),
)
}
}
func WithTinkerbellExternalEtcdTopology(count int) TinkerbellOpt {
return func(t *Tinkerbell) {
t.fillers = append([]api.TinkerbellFiller{api.WithTinkerbellEtcdMachineConfig()}, t.fillers...)
t.clusterFillers = append(t.clusterFillers, api.WithExternalEtcdTopology(count), api.WithExternalEtcdMachineRef(anywherev1.TinkerbellMachineConfigKind))
}
}
func WithCustomTinkerbellMachineConfig(selector string) TinkerbellOpt {
return func(t *Tinkerbell) {
t.fillers = append([]api.TinkerbellFiller{api.WithCustomTinkerbellMachineConfig(selector)}, t.fillers...)
}
}
// ClusterStateValidations returns a list of provider specific validations.
func (t *Tinkerbell) ClusterStateValidations() []clusterf.StateValidation {
return []clusterf.StateValidation{}
}
// WithOSImageURL Modify OS Image url.
func WithOSImageURL(url string) TinkerbellOpt {
return func(t *Tinkerbell) {
t.fillers = append(t.fillers,
api.WithTinkerbellOSImageURL(url),
)
}
}
// WithHookImagesURLPath Modify Hook OS Image url.
func WithHookImagesURLPath(url string) TinkerbellOpt {
return func(t *Tinkerbell) {
t.fillers = append(t.fillers,
api.WithHookImagesURLPath(url),
)
}
}
| 312 |
eks-anywhere | aws | Go | package framework
import (
"context"
"fmt"
"os"
"path/filepath"
"strings"
"testing"
"sigs.k8s.io/cluster-api/bootstrap/kubeadm/api/v1beta1"
"github.com/aws/eks-anywhere/internal/pkg/api"
"github.com/aws/eks-anywhere/internal/test/cleanup"
anywherev1 "github.com/aws/eks-anywhere/pkg/api/v1alpha1"
"github.com/aws/eks-anywhere/pkg/executables"
"github.com/aws/eks-anywhere/pkg/manifests/bundles"
"github.com/aws/eks-anywhere/pkg/manifests/releases"
anywheretypes "github.com/aws/eks-anywhere/pkg/types"
releasev1 "github.com/aws/eks-anywhere/release/api/v1alpha1"
clusterf "github.com/aws/eks-anywhere/test/framework/cluster"
)
const (
vsphereDatacenterVar = "T_VSPHERE_DATACENTER"
vsphereDatastoreVar = "T_VSPHERE_DATASTORE"
vsphereFolderVar = "T_VSPHERE_FOLDER"
vsphereNetworkVar = "T_VSPHERE_NETWORK"
vspherePrivateNetworkVar = "T_VSPHERE_PRIVATE_NETWORK"
vsphereResourcePoolVar = "T_VSPHERE_RESOURCE_POOL"
vsphereServerVar = "T_VSPHERE_SERVER"
vsphereSshAuthorizedKeyVar = "T_VSPHERE_SSH_AUTHORIZED_KEY"
vsphereStoragePolicyNameVar = "T_VSPHERE_STORAGE_POLICY_NAME"
vsphereTlsInsecureVar = "T_VSPHERE_TLS_INSECURE"
vsphereTlsThumbprintVar = "T_VSPHERE_TLS_THUMBPRINT"
vsphereUsernameVar = "EKSA_VSPHERE_USERNAME"
vspherePasswordVar = "EKSA_VSPHERE_PASSWORD"
cidrVar = "T_VSPHERE_CIDR"
privateNetworkCidrVar = "T_VSPHERE_PRIVATE_NETWORK_CIDR"
govcUrlVar = "VSPHERE_SERVER"
govcInsecureVar = "GOVC_INSECURE"
govcDatacenterVar = "GOVC_DATACENTER"
vsphereTemplateEnvVarPrefix = "T_VSPHERE_TEMPLATE_"
vsphereTemplatesFolder = "T_VSPHERE_TEMPLATE_FOLDER"
vsphereTestTagEnvVar = "T_VSPHERE_TAG"
)
var requiredEnvVars = []string{
vsphereDatacenterVar,
vsphereDatastoreVar,
vsphereFolderVar,
vsphereNetworkVar,
vspherePrivateNetworkVar,
vsphereResourcePoolVar,
vsphereServerVar,
vsphereSshAuthorizedKeyVar,
vsphereTlsInsecureVar,
vsphereTlsThumbprintVar,
vsphereUsernameVar,
vspherePasswordVar,
cidrVar,
privateNetworkCidrVar,
govcUrlVar,
govcInsecureVar,
govcDatacenterVar,
vsphereTestTagEnvVar,
}
type VSphere struct {
t *testing.T
testsConfig vsphereConfig
fillers []api.VSphereFiller
clusterFillers []api.ClusterFiller
cidr string
GovcClient *executables.Govc
devRelease *releasev1.EksARelease
templatesRegistry *templateRegistry
}
type vsphereConfig struct {
Datacenter string
Datastore string
Folder string
Network string
ResourcePool string
Server string
SSHAuthorizedKey string
StoragePolicyName string
TLSInsecure bool
TLSThumbprint string
TemplatesFolder string
}
// VSphereOpt is construction option for the E2E vSphere provider.
type VSphereOpt func(*VSphere)
func NewVSphere(t *testing.T, opts ...VSphereOpt) *VSphere {
checkRequiredEnvVars(t, requiredEnvVars)
c := buildGovc(t)
config, err := readVSphereConfig()
if err != nil {
t.Fatalf("Failed reading vSphere tests config: %v", err)
}
v := &VSphere{
t: t,
GovcClient: c,
testsConfig: config,
fillers: []api.VSphereFiller{
api.WithDatacenter(config.Datacenter),
api.WithDatastoreForAllMachines(config.Datastore),
api.WithFolderForAllMachines(config.Folder),
api.WithNetwork(config.Network),
api.WithResourcePoolForAllMachines(config.ResourcePool),
api.WithServer(config.Server),
api.WithSSHAuthorizedKeyForAllMachines(config.SSHAuthorizedKey),
api.WithStoragePolicyNameForAllMachines(config.StoragePolicyName),
api.WithTLSInsecure(config.TLSInsecure),
api.WithTLSThumbprint(config.TLSThumbprint),
},
}
v.cidr = os.Getenv(cidrVar)
v.templatesRegistry = &templateRegistry{cache: map[string]string{}, generator: v}
for _, opt := range opts {
opt(v)
}
return v
}
// WithRedHat123VSphere vsphere test with redhat 1.23.
func WithRedHat123VSphere() VSphereOpt {
return func(v *VSphere) {
v.fillers = append(v.fillers,
api.WithTemplateForAllMachines(v.templateForDevRelease(anywherev1.RedHat, anywherev1.Kube123)),
api.WithOsFamilyForAllMachines(anywherev1.RedHat),
)
}
}
// WithRedHat124VSphere vsphere test with redhat 1.24.
func WithRedHat124VSphere() VSphereOpt {
return func(v *VSphere) {
v.fillers = append(v.fillers,
api.WithTemplateForAllMachines(v.templateForDevRelease(anywherev1.RedHat, anywherev1.Kube124)),
api.WithOsFamilyForAllMachines(anywherev1.RedHat),
)
}
}
// WithRedHat125VSphere vsphere test with redhat 1.25.
func WithRedHat125VSphere() VSphereOpt {
return func(v *VSphere) {
v.fillers = append(v.fillers,
api.WithTemplateForAllMachines(v.templateForDevRelease(anywherev1.RedHat, anywherev1.Kube125)),
api.WithOsFamilyForAllMachines(anywherev1.RedHat),
)
}
}
// WithRedHat126VSphere vsphere test with redhat 1.26.
func WithRedHat126VSphere() VSphereOpt {
return func(v *VSphere) {
v.fillers = append(v.fillers,
api.WithTemplateForAllMachines(v.templateForDevRelease(anywherev1.RedHat, anywherev1.Kube126)),
api.WithOsFamilyForAllMachines(anywherev1.RedHat),
)
}
}
// WithRedHat127VSphere vsphere test with redhat 1.27.
func WithRedHat127VSphere() VSphereOpt {
return func(v *VSphere) {
v.fillers = append(v.fillers,
api.WithTemplateForAllMachines(v.templateForDevRelease(anywherev1.RedHat, anywherev1.Kube127)),
api.WithOsFamilyForAllMachines(anywherev1.RedHat),
)
}
}
// WithUbuntu127 returns a VSphereOpt that adds API fillers to use a Ubuntu vSphere template for k8s 1.27
// and the "ubuntu" osFamily in all machine configs.
func WithUbuntu127() VSphereOpt {
return func(v *VSphere) {
v.fillers = append(v.fillers,
api.WithTemplateForAllMachines(v.templateForDevRelease(anywherev1.Ubuntu, anywherev1.Kube127)),
api.WithOsFamilyForAllMachines(anywherev1.Ubuntu),
)
}
}
// WithUbuntu126 returns a VSphereOpt that adds API fillers to use a Ubuntu vSphere template for k8s 1.26
// and the "ubuntu" osFamily in all machine configs.
func WithUbuntu126() VSphereOpt {
return func(v *VSphere) {
v.fillers = append(v.fillers,
api.WithTemplateForAllMachines(v.templateForDevRelease(anywherev1.Ubuntu, anywherev1.Kube126)),
api.WithOsFamilyForAllMachines(anywherev1.Ubuntu),
)
}
}
// WithUbuntu125 returns a VSphereOpt that adds API fillers to use a Ubuntu vSphere template for k8s 1.25
// and the "ubuntu" osFamily in all machine configs.
func WithUbuntu125() VSphereOpt {
return func(v *VSphere) {
v.fillers = append(v.fillers,
api.WithTemplateForAllMachines(v.templateForDevRelease(anywherev1.Ubuntu, anywherev1.Kube125)),
api.WithOsFamilyForAllMachines(anywherev1.Ubuntu),
)
}
}
// WithUbuntu124 returns a VSphereOpt that adds API fillers to use a Ubuntu vSphere template for k8s 1.24
// and the "ubuntu" osFamily in all machine configs.
func WithUbuntu124() VSphereOpt {
return func(v *VSphere) {
v.fillers = append(v.fillers,
api.WithTemplateForAllMachines(v.templateForDevRelease(anywherev1.Ubuntu, anywherev1.Kube124)),
api.WithOsFamilyForAllMachines(anywherev1.Ubuntu),
)
}
}
// WithUbuntu123 returns a VSphereOpt that adds API fillers to use a Ubuntu vSphere template for k8s 1.23
// and the "ubuntu" osFamily in all machine configs.
func WithUbuntu123() VSphereOpt {
return func(v *VSphere) {
v.fillers = append(v.fillers,
api.WithTemplateForAllMachines(v.templateForDevRelease(anywherev1.Ubuntu, anywherev1.Kube123)),
api.WithOsFamilyForAllMachines(anywherev1.Ubuntu),
)
}
}
func WithBottleRocket123() VSphereOpt {
return func(v *VSphere) {
v.fillers = append(v.fillers,
api.WithTemplateForAllMachines(v.templateForDevRelease(anywherev1.Bottlerocket, anywherev1.Kube123)),
api.WithOsFamilyForAllMachines(anywherev1.Bottlerocket),
)
}
}
// WithUbuntu123 returns a cluster config filler that sets the kubernetes version of the cluster to 1.23
// as well as the right ubuntu template and osFamily for all VSphereMachineConfigs.
func (v *VSphere) WithUbuntu123() api.ClusterConfigFiller {
return api.JoinClusterConfigFillers(
api.ClusterToConfigFiller(api.WithKubernetesVersion(anywherev1.Kube123)),
api.VSphereToConfigFiller(
api.WithTemplateForAllMachines(v.templateForDevRelease(anywherev1.Ubuntu, anywherev1.Kube123)),
api.WithOsFamilyForAllMachines(anywherev1.Ubuntu),
),
)
}
// WithUbuntu124 returns a cluster config filler that sets the kubernetes version of the cluster to 1.24
// as well as the right ubuntu template and osFamily for all VSphereMachineConfigs.
func (v *VSphere) WithUbuntu124() api.ClusterConfigFiller {
return api.JoinClusterConfigFillers(
api.ClusterToConfigFiller(api.WithKubernetesVersion(anywherev1.Kube124)),
api.VSphereToConfigFiller(
api.WithTemplateForAllMachines(v.templateForDevRelease(anywherev1.Ubuntu, anywherev1.Kube124)),
api.WithOsFamilyForAllMachines(anywherev1.Ubuntu),
),
)
}
// WithUbuntu125 returns a cluster config filler that sets the kubernetes version of the cluster to 1.25
// as well as the right ubuntu template and osFamily for all VSphereMachineConfigs.
func (v *VSphere) WithUbuntu125() api.ClusterConfigFiller {
return api.JoinClusterConfigFillers(
api.ClusterToConfigFiller(api.WithKubernetesVersion(anywherev1.Kube125)),
api.VSphereToConfigFiller(
api.WithTemplateForAllMachines(v.templateForDevRelease(anywherev1.Ubuntu, anywherev1.Kube125)),
api.WithOsFamilyForAllMachines(anywherev1.Ubuntu),
),
)
}
// WithUbuntu126 returns a cluster config filler that sets the kubernetes version of the cluster to 1.26
// as well as the right ubuntu template and osFamily for all VSphereMachineConfigs.
func (v *VSphere) WithUbuntu126() api.ClusterConfigFiller {
return api.JoinClusterConfigFillers(
api.ClusterToConfigFiller(api.WithKubernetesVersion(anywherev1.Kube126)),
api.VSphereToConfigFiller(
api.WithTemplateForAllMachines(v.templateForDevRelease(anywherev1.Ubuntu, anywherev1.Kube126)),
api.WithOsFamilyForAllMachines(anywherev1.Ubuntu),
),
)
}
// WithBottleRocket123 returns a cluster config filler that sets the kubernetes version of the cluster to 1.23
// as well as the right botllerocket template and osFamily for all VSphereMachaineConfigs.
func (v *VSphere) WithBottleRocket123() api.ClusterConfigFiller {
return api.JoinClusterConfigFillers(
api.ClusterToConfigFiller(api.WithKubernetesVersion(anywherev1.Kube123)),
api.VSphereToConfigFiller(
api.WithTemplateForAllMachines(v.templateForDevRelease(anywherev1.Bottlerocket, anywherev1.Kube123)),
api.WithOsFamilyForAllMachines(anywherev1.Bottlerocket),
),
)
}
// WithBottleRocket124 returns a cluster config filler that sets the kubernetes version of the cluster to 1.24
// as well as the right botllerocket template and osFamily for all VSphereMachaineConfigs.
func (v *VSphere) WithBottleRocket124() api.ClusterConfigFiller {
return api.JoinClusterConfigFillers(
api.ClusterToConfigFiller(api.WithKubernetesVersion(anywherev1.Kube124)),
api.VSphereToConfigFiller(
api.WithTemplateForAllMachines(v.templateForDevRelease(anywherev1.Bottlerocket, anywherev1.Kube124)),
api.WithOsFamilyForAllMachines(anywherev1.Bottlerocket),
),
)
}
// WithBottleRocket124 returns br 124 var.
func WithBottleRocket124() VSphereOpt {
return func(v *VSphere) {
v.fillers = append(v.fillers,
api.WithTemplateForAllMachines(v.templateForDevRelease(anywherev1.Bottlerocket, anywherev1.Kube124)),
api.WithOsFamilyForAllMachines(anywherev1.Bottlerocket),
)
}
}
// WithBottleRocket125 returns br 1.25 var.
func WithBottleRocket125() VSphereOpt {
return func(v *VSphere) {
v.fillers = append(v.fillers,
api.WithTemplateForAllMachines(v.templateForDevRelease(anywherev1.Bottlerocket, anywherev1.Kube125)),
api.WithOsFamilyForAllMachines(anywherev1.Bottlerocket),
)
}
}
// WithBottleRocket126 returns br 1.26 var.
func WithBottleRocket126() VSphereOpt {
return func(v *VSphere) {
v.fillers = append(v.fillers,
api.WithTemplateForAllMachines(v.templateForDevRelease(anywherev1.Bottlerocket, anywherev1.Kube126)),
api.WithOsFamilyForAllMachines(anywherev1.Bottlerocket),
)
}
}
// WithBottleRocket127 returns br 1.27 var.
func WithBottleRocket127() VSphereOpt {
return func(v *VSphere) {
v.fillers = append(v.fillers,
api.WithTemplateForAllMachines(v.templateForDevRelease(anywherev1.Bottlerocket, anywherev1.Kube127)),
api.WithOsFamilyForAllMachines(anywherev1.Bottlerocket),
)
}
}
func WithPrivateNetwork() VSphereOpt {
return func(v *VSphere) {
v.fillers = append(v.fillers,
api.WithVSphereStringFromEnvVar(vspherePrivateNetworkVar, api.WithNetwork),
)
v.cidr = os.Getenv(privateNetworkCidrVar)
}
}
// WithLinkedCloneMode sets clone mode to LinkedClone for all the machine.
func WithLinkedCloneMode() VSphereOpt {
return func(v *VSphere) {
v.fillers = append(v.fillers,
api.WithCloneModeForAllMachines(anywherev1.LinkedClone),
)
}
}
// WithFullCloneMode sets clone mode to FullClone for all the machine.
func WithFullCloneMode() VSphereOpt {
return func(v *VSphere) {
v.fillers = append(v.fillers,
api.WithCloneModeForAllMachines(anywherev1.FullClone),
)
}
}
// WithDiskGiBForAllMachines sets diskGiB for all the machines.
func WithDiskGiBForAllMachines(value int) VSphereOpt {
return func(v *VSphere) {
v.fillers = append(v.fillers,
api.WithDiskGiBForAllMachines(value),
)
}
}
// WithNTPServersForAllMachines sets NTP servers for all the machines.
func WithNTPServersForAllMachines() VSphereOpt {
return func(v *VSphere) {
checkRequiredEnvVars(v.t, RequiredNTPServersEnvVars())
v.fillers = append(v.fillers,
api.WithNTPServersForAllMachines(GetNTPServersFromEnv()),
)
}
}
// WithBottlerocketKubernetesSettingsForAllMachines sets Bottlerocket Kubernetes settings for all the machines.
func WithBottlerocketKubernetesSettingsForAllMachines() VSphereOpt {
return func(v *VSphere) {
checkRequiredEnvVars(v.t, RequiredBottlerocketKubernetesSettingsEnvVars())
unsafeSysctls, clusterDNSIPS, maxPods, err := GetBottlerocketKubernetesSettingsFromEnv()
if err != nil {
v.t.Fatalf("failed to get bottlerocket kubernetes settings from env: %v", err)
}
config := &anywherev1.BottlerocketConfiguration{
Kubernetes: &v1beta1.BottlerocketKubernetesSettings{
AllowedUnsafeSysctls: unsafeSysctls,
ClusterDNSIPs: clusterDNSIPS,
MaxPods: maxPods,
},
}
v.fillers = append(v.fillers,
api.WithBottlerocketConfigurationForAllMachines(config),
)
}
}
// WithSSHAuthorizedKeyForAllMachines sets SSH authorized keys for all the machines.
func WithSSHAuthorizedKeyForAllMachines(sshKey string) VSphereOpt {
return func(v *VSphere) {
v.fillers = append(v.fillers, api.WithSSHAuthorizedKeyForAllMachines(sshKey))
}
}
// WithVSphereTags with vsphere tags option.
func WithVSphereTags() VSphereOpt {
return func(v *VSphere) {
tags := []string{os.Getenv(vsphereTestTagEnvVar)}
v.fillers = append(v.fillers,
api.WithTagsForAllMachines(tags),
)
}
}
func WithVSphereWorkerNodeGroup(name string, workerNodeGroup *WorkerNodeGroup, fillers ...api.VSphereMachineConfigFiller) VSphereOpt {
return func(v *VSphere) {
v.fillers = append(v.fillers, vSphereMachineConfig(name, fillers...))
v.clusterFillers = append(v.clusterFillers, buildVSphereWorkerNodeGroupClusterFiller(name, workerNodeGroup))
}
}
// WithNewWorkerNodeGroup returns an api.ClusterFiller that adds a new workerNodeGroupConfiguration and
// a corresponding VSphereMachineConfig to the cluster config.
func (v *VSphere) WithNewWorkerNodeGroup(name string, workerNodeGroup *WorkerNodeGroup) api.ClusterConfigFiller {
machineConfigFillers := []api.VSphereMachineConfigFiller{updateMachineSSHAuthorizedKey()}
return api.JoinClusterConfigFillers(
api.VSphereToConfigFiller(vSphereMachineConfig(name, machineConfigFillers...)),
api.ClusterToConfigFiller(buildVSphereWorkerNodeGroupClusterFiller(name, workerNodeGroup)),
)
}
// WithWorkerNodeGroupConfiguration returns an api.ClusterFiller that adds a new workerNodeGroupConfiguration item to the cluster config.
func (v *VSphere) WithWorkerNodeGroupConfiguration(name string, workerNodeGroup *WorkerNodeGroup) api.ClusterConfigFiller {
return api.ClusterToConfigFiller(buildVSphereWorkerNodeGroupClusterFiller(name, workerNodeGroup))
}
// updateMachineSSHAuthorizedKey updates a vsphere machine configs SSHAuthorizedKey.
func updateMachineSSHAuthorizedKey() api.VSphereMachineConfigFiller {
return api.WithStringFromEnvVar(vsphereSshAuthorizedKeyVar, api.WithSSHKey)
}
// WithVSphereFillers adds VSphereFiller to the provider default fillers.
func WithVSphereFillers(fillers ...api.VSphereFiller) VSphereOpt {
return func(v *VSphere) {
v.fillers = append(v.fillers, fillers...)
}
}
// Name returns the provider name. It satisfies the test framework Provider.
func (v *VSphere) Name() string {
return "vsphere"
}
// Setup does nothing. It satisfies the test framework Provider.
func (v *VSphere) Setup() {}
// UpdateKubeConfig customizes generated kubeconfig for the provider.
func (v *VSphere) UpdateKubeConfig(content *[]byte, clusterName string) error {
return nil
}
// ClusterConfigUpdates satisfies the test framework Provider.
func (v *VSphere) ClusterConfigUpdates() []api.ClusterConfigFiller {
clusterIP, err := GetIP(v.cidr, ClusterIPPoolEnvVar)
if err != nil {
v.t.Fatalf("failed to get cluster ip for test environment: %v", err)
}
f := make([]api.ClusterFiller, 0, len(v.clusterFillers)+1)
f = append(f, v.clusterFillers...)
f = append(f, api.WithControlPlaneEndpointIP(clusterIP))
return []api.ClusterConfigFiller{api.ClusterToConfigFiller(f...), api.VSphereToConfigFiller(v.fillers...)}
}
// WithKubeVersionAndOS returns a cluster config filler that sets the cluster kube version and the right template for all
// vsphere machine configs.
func (v *VSphere) WithKubeVersionAndOS(osFamily anywherev1.OSFamily, kubeVersion anywherev1.KubernetesVersion) api.ClusterConfigFiller {
return api.JoinClusterConfigFillers(
api.ClusterToConfigFiller(api.WithKubernetesVersion(kubeVersion)),
api.VSphereToConfigFiller(
api.WithTemplateForAllMachines(v.templateForDevRelease(osFamily, kubeVersion)),
api.WithOsFamilyForAllMachines(osFamily),
),
)
}
// CleanupVMs deletes all the VMs owned by the test EKS-A cluster. It satisfies the test framework Provider.
func (v *VSphere) CleanupVMs(clusterName string) error {
return cleanup.CleanUpVsphereTestResources(context.Background(), clusterName)
}
func (v *VSphere) WithProviderUpgrade(fillers ...api.VSphereFiller) ClusterE2ETestOpt {
return func(e *ClusterE2ETest) {
e.UpdateClusterConfig(api.VSphereToConfigFiller(fillers...))
}
}
func (v *VSphere) WithProviderUpgradeGit(fillers ...api.VSphereFiller) ClusterE2ETestOpt {
return func(e *ClusterE2ETest) {
e.UpdateClusterConfig(api.VSphereToConfigFiller(fillers...))
}
}
// WithNewVSphereWorkerNodeGroup adds a new worker node group to the cluster config.
func (v *VSphere) WithNewVSphereWorkerNodeGroup(name string, workerNodeGroup *WorkerNodeGroup) ClusterE2ETestOpt {
return func(e *ClusterE2ETest) {
e.UpdateClusterConfig(
api.ClusterToConfigFiller(buildVSphereWorkerNodeGroupClusterFiller(name, workerNodeGroup)),
)
}
}
// Ubuntu123Template returns vsphere filler for 1.23 Ubuntu.
func (v *VSphere) Ubuntu123Template() api.VSphereFiller {
return api.WithTemplateForAllMachines(v.templateForDevRelease(anywherev1.Ubuntu, anywherev1.Kube123))
}
// Ubuntu124Template returns vsphere filler for 1.24 Ubuntu.
func (v *VSphere) Ubuntu124Template() api.VSphereFiller {
return api.WithTemplateForAllMachines(v.templateForDevRelease(anywherev1.Ubuntu, anywherev1.Kube124))
}
// Ubuntu125Template returns vsphere filler for 1.25 Ubuntu.
func (v *VSphere) Ubuntu125Template() api.VSphereFiller {
return api.WithTemplateForAllMachines(v.templateForDevRelease(anywherev1.Ubuntu, anywherev1.Kube125))
}
// Ubuntu126Template returns vsphere filler for 1.26 Ubuntu.
func (v *VSphere) Ubuntu126Template() api.VSphereFiller {
return api.WithTemplateForAllMachines(v.templateForDevRelease(anywherev1.Ubuntu, anywherev1.Kube126))
}
// Ubuntu127Template returns vsphere filler for 1.27 Ubuntu.
func (v *VSphere) Ubuntu127Template() api.VSphereFiller {
return api.WithTemplateForAllMachines(v.templateForDevRelease(anywherev1.Ubuntu, anywherev1.Kube127))
}
// Bottlerocket123Template returns vsphere filler for 1.23 BR.
func (v *VSphere) Bottlerocket123Template() api.VSphereFiller {
return api.WithTemplateForAllMachines(v.templateForDevRelease(anywherev1.Bottlerocket, anywherev1.Kube123))
}
// Bottlerocket124Template returns vsphere filler for 1.24 BR.
func (v *VSphere) Bottlerocket124Template() api.VSphereFiller {
return api.WithTemplateForAllMachines(v.templateForDevRelease(anywherev1.Bottlerocket, anywherev1.Kube124))
}
// Bottlerocket125Template returns vsphere filler for 1.25 BR.
func (v *VSphere) Bottlerocket125Template() api.VSphereFiller {
return api.WithTemplateForAllMachines(v.templateForDevRelease(anywherev1.Bottlerocket, anywherev1.Kube125))
}
// Bottlerocket126Template returns vsphere filler for 1.26 BR.
func (v *VSphere) Bottlerocket126Template() api.VSphereFiller {
return api.WithTemplateForAllMachines(v.templateForDevRelease(anywherev1.Bottlerocket, anywherev1.Kube126))
}
// Bottlerocket127Template returns vsphere filler for 1.27 BR.
func (v *VSphere) Bottlerocket127Template() api.VSphereFiller {
return api.WithTemplateForAllMachines(v.templateForDevRelease(anywherev1.Bottlerocket, anywherev1.Kube127))
}
func (v *VSphere) getDevRelease() *releasev1.EksARelease {
v.t.Helper()
if v.devRelease == nil {
latestRelease, err := getLatestDevRelease()
if err != nil {
v.t.Fatal(err)
}
v.devRelease = latestRelease
}
return v.devRelease
}
func (v *VSphere) templateForDevRelease(osFamily anywherev1.OSFamily, kubeVersion anywherev1.KubernetesVersion) string {
v.t.Helper()
return v.templatesRegistry.templateForRelease(v.t, osFamily, v.getDevRelease(), kubeVersion)
}
func RequiredVsphereEnvVars() []string {
return requiredEnvVars
}
// VSphereExtraEnvVarPrefixes returns prefixes for env vars that although not always required,
// might be necessary for certain tests.
func VSphereExtraEnvVarPrefixes() []string {
return []string{
vsphereTemplateEnvVarPrefix,
}
}
func vSphereMachineConfig(name string, fillers ...api.VSphereMachineConfigFiller) api.VSphereFiller {
f := make([]api.VSphereMachineConfigFiller, 0, len(fillers)+6)
// Need to add these because at this point the default fillers that assign these
// values to all machines have already ran
f = append(f,
api.WithVSphereMachineDefaultValues(),
api.WithDatastore(os.Getenv(vsphereDatastoreVar)),
api.WithFolder(os.Getenv(vsphereFolderVar)),
api.WithResourcePool(os.Getenv(vsphereResourcePoolVar)),
api.WithStoragePolicyName(os.Getenv(vsphereStoragePolicyNameVar)),
api.WithSSHKey(os.Getenv(vsphereSshAuthorizedKeyVar)),
)
f = append(f, fillers...)
return api.WithVSphereMachineConfig(name, f...)
}
func buildVSphereWorkerNodeGroupClusterFiller(machineConfigName string, workerNodeGroup *WorkerNodeGroup) api.ClusterFiller {
// Set worker node group ref to vsphere machine config
workerNodeGroup.MachineConfigKind = anywherev1.VSphereMachineConfigKind
workerNodeGroup.MachineConfigName = machineConfigName
return workerNodeGroup.ClusterFiller()
}
func WithUbuntuForRelease(release *releasev1.EksARelease, kubeVersion anywherev1.KubernetesVersion) VSphereOpt {
return optionToSetTemplateForRelease(anywherev1.Ubuntu, release, kubeVersion)
}
func WithBottlerocketFromRelease(release *releasev1.EksARelease, kubeVersion anywherev1.KubernetesVersion) VSphereOpt {
return optionToSetTemplateForRelease(anywherev1.Bottlerocket, release, kubeVersion)
}
func (v *VSphere) WithBottleRocketForRelease(release *releasev1.EksARelease, kubeVersion anywherev1.KubernetesVersion) api.ClusterConfigFiller {
return api.VSphereToConfigFiller(
api.WithTemplateForAllMachines(v.templatesRegistry.templateForRelease(v.t, anywherev1.Bottlerocket, release, kubeVersion)),
)
}
func optionToSetTemplateForRelease(osFamily anywherev1.OSFamily, release *releasev1.EksARelease, kubeVersion anywherev1.KubernetesVersion) VSphereOpt {
return func(v *VSphere) {
v.fillers = append(v.fillers,
api.WithTemplateForAllMachines(v.templatesRegistry.templateForRelease(v.t, osFamily, release, kubeVersion)),
)
}
}
// envVarForTemplate looks for explicit configuration through an env var: "T_VSPHERE_TEMPLATE_{osFamily}_{eks-d version}"
// eg: T_VSPHERE_TEMPLATE_REDHAT_KUBERNETES_1_23_EKS_22.
func (v *VSphere) envVarForTemplate(osFamily, eksDName string) string {
return fmt.Sprintf("T_VSPHERE_TEMPLATE_%s_%s", strings.ToUpper(osFamily), strings.ToUpper(strings.ReplaceAll(eksDName, "-", "_")))
}
// defaultNameForTemplate looks for a template with the name path: "{folder}/{eks-d version}-{osFamily}"
// eg: /SDDC-Datacenter/vm/Templates/kubernetes-1-23-eks-22-redhat.
func (v *VSphere) defaultNameForTemplate(osFamily, eksDName string) string {
folder := v.testsConfig.TemplatesFolder
if folder == "" {
v.t.Log("vSphere templates folder is not configured.")
return ""
}
return filepath.Join(folder, fmt.Sprintf("%s-%s", strings.ToLower(eksDName), strings.ToLower(osFamily)))
}
// defaultEnvVarForTemplate returns the value of the default template env vars: "T_VSPHERE_TEMPLATE_{osFamily}_{kubeVersion}"
// eg. T_VSPHERE_TEMPLATE_REDHAT_1_23.
func (v *VSphere) defaultEnvVarForTemplate(osFamily string, kubeVersion anywherev1.KubernetesVersion) string {
if osFamily == "bottlerocket" {
// This is only to maintain backwards compatibility with old env var naming
osFamily = "br"
}
return fmt.Sprintf("T_VSPHERE_TEMPLATE_%s_%s", strings.ToUpper(osFamily), strings.ReplaceAll(string(kubeVersion), ".", "_"))
}
// searchTemplate returns template name if the given template exists in the datacenter.
func (v *VSphere) searchTemplate(ctx context.Context, template string) (string, error) {
foundTemplate, err := v.GovcClient.SearchTemplate(context.Background(), v.testsConfig.Datacenter, template)
if err != nil {
return "", err
}
return foundTemplate, nil
}
func readVersionsBundles(t testing.TB, release *releasev1.EksARelease, kubeVersion anywherev1.KubernetesVersion) *releasev1.VersionsBundle {
reader := newFileReader()
b, err := releases.ReadBundlesForRelease(reader, release)
if err != nil {
t.Fatal(err)
}
return bundles.VersionsBundleForKubernetesVersion(b, string(kubeVersion))
}
func readVSphereConfig() (vsphereConfig, error) {
return vsphereConfig{
Datacenter: os.Getenv(vsphereDatacenterVar),
Datastore: os.Getenv(vsphereDatastoreVar),
Folder: os.Getenv(vsphereFolderVar),
Network: os.Getenv(vsphereNetworkVar),
ResourcePool: os.Getenv(vsphereResourcePoolVar),
Server: os.Getenv(vsphereServerVar),
SSHAuthorizedKey: os.Getenv(vsphereSshAuthorizedKeyVar),
StoragePolicyName: os.Getenv(vsphereStoragePolicyNameVar),
TLSInsecure: os.Getenv(vsphereTlsInsecureVar) == "true",
TLSThumbprint: os.Getenv(vsphereTlsThumbprintVar),
TemplatesFolder: os.Getenv(vsphereTemplatesFolder),
}, nil
}
// ClusterStateValidations returns a list of provider specific validations.
func (v *VSphere) ClusterStateValidations() []clusterf.StateValidation {
return []clusterf.StateValidation{}
}
// ValidateNodesDiskGiB validates DiskGiB for all the machines.
func (v *VSphere) ValidateNodesDiskGiB(machines map[string]anywheretypes.Machine, expectedDiskSize int) error {
v.t.Log("===================== Disk Size Validation Task =====================")
for _, m := range machines {
v.t.Log("Verifying disk size for VM", "Virtual Machine", m.Metadata.Name)
diskSize, err := v.GovcClient.GetVMDiskSizeInGB(context.Background(), m.Metadata.Name, v.testsConfig.Datacenter)
if err != nil {
v.t.Fatalf("validating disk size: %v", err)
}
v.t.Log("Disk Size in GiB", "Expected", expectedDiskSize, "Actual", diskSize)
if diskSize != expectedDiskSize {
v.t.Fatalf("diskGib for node %s did not match the expected disk size. Expected=%dGiB, Actual=%dGiB", m.Metadata.Name, expectedDiskSize, diskSize)
}
}
return nil
}
| 751 |
eks-anywhere | aws | Go | package framework
import (
"context"
"time"
"github.com/aws/eks-anywhere/pkg/retrier"
)
func (e *ClusterE2ETest) WaitForControlPlaneReady() {
e.T.Log("Waiting for control plane to be ready")
err := retrier.New(5 * time.Minute).Retry(func() error {
return e.KubectlClient.ValidateControlPlaneNodes(context.Background(), e.Cluster(), e.ClusterName)
})
if err != nil {
e.T.Fatal(err)
}
}
| 19 |
eks-anywhere | aws | Go | package framework
import "github.com/aws/eks-anywhere/internal/pkg/api"
type WorkerNodeGroup struct {
Name string
Fillers []api.WorkerNodeGroupFiller
MachineConfigKind, MachineConfigName string
}
func WithWorkerNodeGroup(name string, fillers ...api.WorkerNodeGroupFiller) *WorkerNodeGroup {
return &WorkerNodeGroup{
Name: name,
Fillers: fillers,
}
}
func (w *WorkerNodeGroup) ClusterFiller() api.ClusterFiller {
wf := make([]api.WorkerNodeGroupFiller, 0, len(w.Fillers)+1)
wf = append(wf, api.WithMachineGroupRef(w.MachineConfigName, w.MachineConfigKind))
wf = append(wf, w.Fillers...)
return api.WithWorkerNodeGroup(w.Name, wf...)
}
| 25 |
eks-anywhere | aws | Go | package framework
import (
"context"
"fmt"
corev1 "k8s.io/api/core/v1"
"github.com/aws/eks-anywhere/pkg/api/v1alpha1"
"github.com/aws/eks-anywhere/pkg/constants"
"github.com/aws/eks-anywhere/pkg/executables"
)
// WorkerNodeValidation should return an error if either an error is encountered during execution or the validation logically fails.
// This validation function will be executed by ValidateWorkerNodes with a worker node group configuration and a corresponding node
// which was created as a part of that worker node group configuration.
type WorkerNodeValidation func(configuration v1alpha1.WorkerNodeGroupConfiguration, node corev1.Node) (err error)
// ValidateWorkerNodes deduces the worker node group configuration to node mapping
// and for each configuration/node pair executes the provided validation functions.
func (e *ClusterE2ETest) ValidateWorkerNodes(workerNodeValidations ...WorkerNodeValidation) {
ctx := context.Background()
nodes, err := e.KubectlClient.GetNodes(ctx, e.Cluster().KubeconfigFile)
if err != nil {
e.T.Fatal(err)
}
c := e.ClusterConfig.Cluster
wn := c.Spec.WorkerNodeGroupConfigurations
// deduce the worker node group configuration to node mapping via the machine deployment and machine set
for _, w := range wn {
mdName := fmt.Sprintf("%v-%v", e.ClusterName, w.Name)
md, err := e.KubectlClient.GetMachineDeployment(ctx, mdName, executables.WithKubeconfig(e.Cluster().KubeconfigFile), executables.WithNamespace(constants.EksaSystemNamespace))
if err != nil {
e.T.Fatal(fmt.Errorf("failed to get machine deployment for worker node %s when validating taints: %v", w.Name, err))
}
ms, err := e.KubectlClient.GetMachineSets(ctx, md.Name, e.Cluster())
if err != nil {
e.T.Fatal(fmt.Errorf("failed to get machine sets when validating taints: %v", err))
}
if len(ms) == 0 {
e.T.Fatal(fmt.Errorf("invalid number of machine sets associated with worker node configuration %v", w.Name))
}
for _, node := range nodes {
ownerName, ok := node.Annotations[ownerAnnotation]
if ok {
// there will be multiple machineSets present on a cluster following an upgrade.
// find the one that is associated with this worker node, and execute the validations.
for _, machineSet := range ms {
if ownerName == machineSet.Name {
for _, validation := range workerNodeValidations {
err = validation(w, node)
if err != nil {
e.T.Errorf("Worker node %v, member of Worker Node Group Configuration %v, is not valid: %v", node.Name, w.Name, err)
}
}
}
}
}
}
e.StopIfFailed()
}
}
| 65 |
eks-anywhere | aws | Go | package framework
import (
"context"
"errors"
"fmt"
"path/filepath"
"time"
"github.com/aws/eks-anywhere/internal/pkg/api"
"github.com/aws/eks-anywhere/pkg/constants"
"github.com/aws/eks-anywhere/pkg/filewriter"
"github.com/aws/eks-anywhere/pkg/retrier"
)
const (
kubectlDeleteTimeout = "20m"
)
type WorkloadCluster struct {
*ClusterE2ETest
ManagementClusterKubeconfigFile func() string
}
type WorkloadClusters map[string]*WorkloadCluster
func (w *WorkloadCluster) CreateCluster(opts ...CommandOpt) {
opts = append(opts, withKubeconfig(w.ManagementClusterKubeconfigFile()))
w.createCluster(opts...)
}
func (w *WorkloadCluster) UpgradeCluster(clusterOpts []ClusterE2ETestOpt, commandOpts ...CommandOpt) {
commandOpts = append(commandOpts, withKubeconfig(w.ManagementClusterKubeconfigFile()))
w.upgradeCluster(clusterOpts, commandOpts...)
}
func (w *WorkloadCluster) DeleteCluster(opts ...CommandOpt) {
opts = append(opts, withKubeconfig(w.ManagementClusterKubeconfigFile()))
w.deleteCluster(opts...)
}
// ApplyClusterManifest uses client-side logic to create/update objects defined in a cluster yaml manifest.
func (w *WorkloadCluster) ApplyClusterManifest() {
ctx := context.Background()
w.T.Logf("Applying workload cluster %s spec located at %s", w.ClusterName, w.ClusterConfigLocation)
if err := w.KubectlClient.ApplyManifest(ctx, w.ManagementClusterKubeconfigFile(), w.ClusterConfigLocation); err != nil {
w.T.Fatalf("Failed to apply workload cluster config: %s", err)
}
w.StopIfFailed()
}
// DeleteClusterWithKubectl uses client-side logic to delete a cluster.
func (w *WorkloadCluster) DeleteClusterWithKubectl() {
ctx := context.Background()
w.T.Logf("Deleting workload cluster %s with kubectl", w.ClusterName)
opts := func(params *[]string) {
*params = append(*params, "--timeout", kubectlDeleteTimeout)
}
if err := w.KubectlClient.DeleteManifest(ctx, w.ManagementClusterKubeconfigFile(), w.ClusterConfigLocation, opts); err != nil {
w.T.Fatalf("Failed to delete workload cluster config: %s", err)
}
w.StopIfFailed()
}
// WaitForAvailableHardware waits for workload cluster hardware to be available.
func (w *WorkloadCluster) WaitForAvailableHardware() {
ctx := context.Background()
w.T.Logf("Waiting for workload cluster %s hardware to be available", w.ClusterName)
err := retrier.Retry(240, 5*time.Second, func() error {
return w.availableHardware(ctx)
})
if err != nil {
w.T.Fatalf("Failed waiting for cluster hardware: %s", err)
}
}
// WaitForKubeconfig waits for the kubeconfig for the workload cluster to be available and then writes it to disk.
func (w *WorkloadCluster) WaitForKubeconfig() {
ctx := context.Background()
w.T.Logf("Waiting for workload cluster %s kubeconfig to be available", w.ClusterName)
err := retrier.Retry(120, 5*time.Second, func() error {
return w.writeKubeconfigToDisk(ctx, fmt.Sprintf("%s-kubeconfig", w.ClusterName), w.KubeconfigFilePath())
})
if err != nil {
w.T.Fatalf("Failed waiting for cluster kubeconfig: %s", err)
}
if len(w.ClusterConfig.AWSIAMConfigs) != 0 {
w.T.Logf("Waiting for workload cluster %s iam auth kubeconfig to be available", w.ClusterName)
err := retrier.Retry(120, 5*time.Second, func() error {
return w.writeKubeconfigToDisk(ctx, fmt.Sprintf("%s-aws-iam-kubeconfig", w.ClusterName), w.iamAuthKubeconfigFilePath())
})
if err != nil {
w.T.Fatalf("Failed waiting for cluster kubeconfig: %s", err)
}
}
w.T.Logf("Waiting for workload cluster %s control plane to be ready", w.ClusterName)
if err := w.KubectlClient.WaitForControlPlaneReady(ctx, w.managementCluster(), "15m", w.ClusterName); err != nil {
w.T.Errorf("Failed waiting for control plane ready: %s", err)
}
}
// ValidateClusterDelete verifies the cluster has been deleted.
func (w *WorkloadCluster) ValidateClusterDelete() {
ctx := context.Background()
w.T.Logf("Validating cluster deletion %s", w.ClusterName)
clusterStateValidator := newClusterStateValidator(w.clusterStateValidationConfig)
clusterStateValidator.WithValidations(
validationsForClusterDoesNotExist()...,
)
if err := clusterStateValidator.Validate(ctx); err != nil {
w.T.Fatalf("failed to validate cluster deletion %v", err)
}
}
func (w *WorkloadCluster) writeKubeconfigToDisk(ctx context.Context, secretName string, filePath string) error {
secret, err := w.KubectlClient.GetSecretFromNamespace(ctx, w.ManagementClusterKubeconfigFile(), secretName, constants.EksaSystemNamespace)
if err != nil {
return fmt.Errorf("failed to get kubeconfig for cluster: %s", err)
}
kubeconfig := secret.Data["value"]
if err := w.Provider.UpdateKubeConfig(&kubeconfig, w.ClusterName); err != nil {
return fmt.Errorf("failed to update kubeconfig for cluster: %s", err)
}
writer, err := filewriter.NewWriter(w.ClusterConfigFolder)
if err != nil {
return fmt.Errorf("failed to write kubeconfig to disk: %v", err)
}
_, err = writer.Write(filepath.Base(filePath), kubeconfig, func(op *filewriter.FileOptions) {
op.IsTemp = false
})
if err != nil {
return fmt.Errorf("failed to write kubeconfig to disk: %v", err)
}
return err
}
func (w *WorkloadCluster) availableHardware(ctx context.Context) error {
hardwareList, err := w.KubectlClient.GetUnprovisionedTinkerbellHardware(ctx, w.ManagementClusterKubeconfigFile(), constants.EksaSystemNamespace)
if err != nil {
return fmt.Errorf("failed to get unprovisioned hardware: %s", err)
}
cpHardwareRequired := w.ClusterConfig.Cluster.Spec.ControlPlaneConfiguration.Count
var workerHardwareRequired int
for _, workerNodeGroup := range w.ClusterConfig.Cluster.Spec.WorkerNodeGroupConfigurations {
workerHardwareRequired += *workerNodeGroup.Count
}
var cpHardwareAvailable int
var workerHardwareAvailable int
for _, hardware := range hardwareList {
switch hardware.Labels[api.HardwareLabelTypeKeyName] {
case api.ControlPlane:
cpHardwareAvailable++
case api.Worker:
workerHardwareAvailable++
}
}
if cpHardwareAvailable < cpHardwareRequired || workerHardwareAvailable < workerHardwareRequired {
return errors.New("Insufficient hardware available for cluster")
}
return nil
}
| 170 |
eks-anywhere | aws | Go | package cluster_test
import (
"context"
"fmt"
"testing"
"time"
. "github.com/onsi/gomega"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"github.com/aws/eks-anywhere/internal/test"
"github.com/aws/eks-anywhere/pkg/api/v1alpha1"
"github.com/aws/eks-anywhere/pkg/cluster"
"github.com/aws/eks-anywhere/pkg/retrier"
clusterf "github.com/aws/eks-anywhere/test/framework/cluster"
)
func validations() []clusterf.StateValidation {
r := retrier.NewWithMaxRetries(2, time.Second)
return []clusterf.StateValidation{
clusterf.RetriableStateValidation(r, func(ctx context.Context, vc clusterf.StateValidationConfig) error {
if vc.ClusterSpec == nil {
return fmt.Errorf("spec not defined")
}
return nil
}),
clusterf.RetriableStateValidation(r, func(ctx context.Context, vc clusterf.StateValidationConfig) error {
if vc.ClusterSpec != nil && vc.ClusterSpec.Cluster.Name != "test-cluster" {
return fmt.Errorf("cluster name not valid")
}
return nil
}),
clusterf.RetriableStateValidation(r, func(ctx context.Context, vc clusterf.StateValidationConfig) error {
if vc.ClusterSpec != nil && vc.ClusterSpec.Cluster.Namespace != "test-namespace" {
return fmt.Errorf("cluster namespace not valid")
}
return nil
}),
}
}
func TestClusterStateValidatorValidate(t *testing.T) {
g := NewWithT(t)
tests := []struct {
name string
clusterSpec *cluster.Spec
wantErr []string
}{
{
name: "validate success",
clusterSpec: test.NewClusterSpec(func(s *cluster.Spec) {
s.Cluster = &v1alpha1.Cluster{
ObjectMeta: metav1.ObjectMeta{
Name: "test-cluster",
Namespace: "test-namespace",
},
}
}),
wantErr: []string{},
},
{
name: "cluster spec nil",
clusterSpec: nil,
wantErr: []string{"spec not defined"},
},
{
name: "invalid cluster name in spec",
clusterSpec: test.NewClusterSpec(func(s *cluster.Spec) {
s.Cluster = &v1alpha1.Cluster{
ObjectMeta: metav1.ObjectMeta{
Name: "test-cluster-invalid-name",
Namespace: "test-namespace",
},
}
}),
wantErr: []string{"cluster name not valid"},
},
{
name: "invalid cluster name in spec",
clusterSpec: test.NewClusterSpec(func(s *cluster.Spec) {
s.Cluster = &v1alpha1.Cluster{
ObjectMeta: metav1.ObjectMeta{
Name: "test-cluster-name-invalid",
Namespace: "test-namespace-invalid",
},
}
}),
wantErr: []string{"cluster name not valid", "cluster namespace not valid"},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
cv := clusterf.NewStateValidator(clusterf.StateValidationConfig{
ClusterSpec: tt.clusterSpec,
})
cv.WithValidations(validations()...)
ctx := context.Background()
err := cv.Validate(ctx)
if len(tt.wantErr) == 0 {
g.Expect(err).To(BeNil())
} else {
for _, wantErr := range tt.wantErr {
g.Expect(err).To(MatchError(ContainSubstring(wantErr)))
}
}
})
}
}
| 111 |
eks-anywhere | aws | Go | package cluster
import (
"context"
"k8s.io/apimachinery/pkg/util/errors"
"sigs.k8s.io/controller-runtime/pkg/client"
"github.com/aws/eks-anywhere/pkg/cluster"
"github.com/aws/eks-anywhere/pkg/retrier"
)
// StateValidation defines a validation that can be registered to the StateValidator.
type StateValidation = func(ctx context.Context, vc StateValidationConfig) error
// RetriableStateValidation returns a StateValidation that is executed with the provided retrier.
func RetriableStateValidation(retrier *retrier.Retrier, validation StateValidation) StateValidation {
return func(ctx context.Context, vc StateValidationConfig) error {
err := retrier.Retry(func() error {
return validation(ctx, vc)
})
return err
}
}
// StateValidator is responsible for checking if a cluster is valid against the spec that is provided.
type StateValidator struct {
Config StateValidationConfig
validations []StateValidation
}
// WithValidations registers multiple validations to the StateValidator that will be run when Validate is called.
func (c *StateValidator) WithValidations(validations ...StateValidation) {
c.validations = append(c.validations, validations...)
}
// Validate runs through the set registered validations and returns an error if any of them fail after a number of retries.
func (c *StateValidator) Validate(ctx context.Context) error {
errList := make([]error, 0)
for _, validate := range c.validations {
err := validate(ctx, c.Config)
if err != nil {
errList = append(errList, err)
}
}
return errors.NewAggregate(errList)
}
// Opt represents is a function that represents an option to configure a StateValidator.
type Opt = func(cv *StateValidator)
// NewStateValidator returns a cluster validator which can be configured by passing Opt arguments.
func NewStateValidator(config StateValidationConfig, opts ...Opt) *StateValidator {
cv := StateValidator{
Config: config,
validations: []StateValidation{},
}
for _, opt := range opts {
opt(&cv)
}
return &cv
}
// StateValidationConfig represents the input for the performing validations on the cluster.
type StateValidationConfig struct {
ClusterClient client.Client // the client for the cluster
ManagementClusterClient client.Client // the client for the management cluster
ClusterSpec *cluster.Spec // the cluster spec
}
| 71 |
eks-anywhere | aws | Go | package validations
import (
"context"
"fmt"
"k8s.io/apimachinery/pkg/types"
cloudstackv1 "sigs.k8s.io/cluster-api-provider-cloudstack/api/v1beta2"
"github.com/aws/eks-anywhere/pkg/constants"
clusterf "github.com/aws/eks-anywhere/test/framework/cluster"
)
// ValidateAvailabilityZones checks each availability zones defined cloudstackdatacenterconfig in the cluster.Spec
// have corresponding cloudstackfailuredomains objects within the cluster.
func ValidateAvailabilityZones(ctx context.Context, vc clusterf.StateValidationConfig) error {
c := vc.ManagementClusterClient
for _, az := range vc.ClusterSpec.CloudStackDatacenter.Spec.AvailabilityZones {
fdName := cloudstackv1.FailureDomainHashedMetaName(az.Name, vc.ClusterSpec.Cluster.Name)
key := types.NamespacedName{Namespace: constants.EksaSystemNamespace, Name: fdName}
failureDomain := &cloudstackv1.CloudStackFailureDomain{}
if err := c.Get(context.Background(), key, failureDomain); err != nil {
return fmt.Errorf("failed to find failure domain %s corresponding to availability zone %s: %v", az.Name, fdName, err)
}
}
return nil
}
| 31 |
eks-anywhere | aws | Go | package validations_test
import (
"context"
"testing"
. "github.com/onsi/gomega"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
cloudstackv1 "sigs.k8s.io/cluster-api-provider-cloudstack/api/v1beta2"
"sigs.k8s.io/controller-runtime/pkg/client"
"github.com/aws/eks-anywhere/internal/test"
"github.com/aws/eks-anywhere/pkg/api/v1alpha1"
"github.com/aws/eks-anywhere/pkg/cluster"
"github.com/aws/eks-anywhere/pkg/constants"
"github.com/aws/eks-anywhere/test/framework/cluster/validations"
)
const (
azName1 = "test-az-1"
azAccount = "test-account-1"
azDomain = "test-domain-1"
azCredentialsRef = "global"
)
func TestValidateAvailabilityZones(t *testing.T) {
g := NewWithT(t)
ctx := context.Background()
tests := []struct {
name string
availabilityZones []v1alpha1.CloudStackAvailabilityZone
failureDomainObjects []client.Object
wantErr string
}{
{
name: "found az failure domain",
availabilityZones: []v1alpha1.CloudStackAvailabilityZone{
{
Name: azName1,
CredentialsRef: azCredentialsRef,
Domain: azDomain,
Account: azAccount,
ManagementApiEndpoint: "test-api-endpoint",
Zone: v1alpha1.CloudStackZone{},
},
},
failureDomainObjects: []client.Object{
&cloudstackv1.CloudStackFailureDomain{
TypeMeta: metav1.TypeMeta{
Kind: "CloudStackFailureDomain",
APIVersion: "infrastructure.cluster.x-k8s.io/v1beta2",
},
ObjectMeta: metav1.ObjectMeta{
Namespace: constants.EksaSystemNamespace,
Name: cloudstackv1.FailureDomainHashedMetaName(azName1, clusterName),
},
Spec: cloudstackv1.CloudStackFailureDomainSpec{
Name: azName1,
Zone: cloudstackv1.CloudStackZoneSpec{},
Account: azAccount,
Domain: azDomain,
ACSEndpoint: corev1.SecretReference{
Name: azCredentialsRef,
Namespace: constants.EksaSystemNamespace,
},
},
},
},
wantErr: "",
},
{
name: "missing az failure domain",
availabilityZones: []v1alpha1.CloudStackAvailabilityZone{
{
Name: azName1,
CredentialsRef: azCredentialsRef,
Domain: azDomain,
Account: azAccount,
ManagementApiEndpoint: "test-api-endpoint",
Zone: v1alpha1.CloudStackZone{},
},
},
failureDomainObjects: []client.Object{},
wantErr: "failed to find failure domain",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
spec := test.NewClusterSpec(func(s *cluster.Spec) {
s.Cluster = testCluster()
s.CloudStackDatacenter = &v1alpha1.CloudStackDatacenterConfig{
ObjectMeta: metav1.ObjectMeta{
Namespace: clusterNamespace,
Name: clusterName,
},
Spec: v1alpha1.CloudStackDatacenterConfigSpec{
AvailabilityZones: tt.availabilityZones,
},
}
})
vt := newStateValidatorTest(t, spec)
vt.createTestObjects(ctx)
vt.createManagementClusterObjects(ctx, tt.failureDomainObjects...)
err := validations.ValidateAvailabilityZones(ctx, vt.config)
if tt.wantErr != "" {
g.Expect(err).To(MatchError(ContainSubstring(tt.wantErr)))
} else {
g.Expect(err).To(BeNil())
}
})
}
}
| 117 |
eks-anywhere | aws | Go | package validations
import (
"context"
"fmt"
"strings"
"github.com/pkg/errors"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/types"
apierrors "k8s.io/apimachinery/pkg/util/errors"
"sigs.k8s.io/cluster-api/api/v1beta1"
"sigs.k8s.io/cluster-api/util/conditions"
"sigs.k8s.io/controller-runtime/pkg/client"
"github.com/aws/eks-anywhere/internal/pkg/api"
"github.com/aws/eks-anywhere/pkg/api/v1alpha1"
"github.com/aws/eks-anywhere/pkg/clusterapi"
"github.com/aws/eks-anywhere/pkg/constants"
"github.com/aws/eks-anywhere/pkg/controller"
clusterf "github.com/aws/eks-anywhere/test/framework/cluster"
)
// ValidateClusterReady gets the CAPICluster from the client then validates that it is in a ready state.
func ValidateClusterReady(ctx context.Context, vc clusterf.StateValidationConfig) error {
clus := vc.ClusterSpec.Cluster
mgmtClusterClient := vc.ManagementClusterClient
capiCluster, err := controller.GetCAPICluster(ctx, mgmtClusterClient, clus)
if err != nil {
return fmt.Errorf("failed to retrieve cluster %s", err)
}
if capiCluster == nil {
return fmt.Errorf("cluster %s does not exist", clus.Name)
}
if conditions.IsFalse(capiCluster, v1beta1.ReadyCondition) {
return fmt.Errorf("CAPI cluster %s not ready yet. %s", capiCluster.GetName(), conditions.GetReason(capiCluster, v1beta1.ReadyCondition))
}
return nil
}
// ValidateEKSAObjects retrieves all the child objects from the cluster.Spec and validates that they exist in the clusterf.
func ValidateEKSAObjects(ctx context.Context, vc clusterf.StateValidationConfig) error {
mgmtClusterClient := vc.ManagementClusterClient
errorList := make([]error, 0)
for _, obj := range vc.ClusterSpec.ChildObjects() {
u := &unstructured.Unstructured{}
u.SetGroupVersionKind(obj.GetObjectKind().GroupVersionKind())
key := types.NamespacedName{Namespace: obj.GetNamespace(), Name: obj.GetName()}
if key.Namespace == "" {
key.Namespace = "default"
}
if err := mgmtClusterClient.Get(ctx, key, u); err != nil {
errorList = append(errorList, errors.Wrap(err, "reading eks-a cluster's child object"))
}
}
if len(errorList) > 0 {
return apierrors.NewAggregate(errorList)
}
return nil
}
// ValidateControlPlaneNodes retrieves the control plane nodes from the cluster and checks them against the cluster.Spec.
func ValidateControlPlaneNodes(ctx context.Context, vc clusterf.StateValidationConfig) error {
clus := vc.ClusterSpec.Cluster
cpNodes := &corev1.NodeList{}
if err := vc.ClusterClient.List(ctx, cpNodes, client.MatchingLabels{"node-role.kubernetes.io/control-plane": ""}); err != nil {
return fmt.Errorf("failed to list controlplane nodes %s", err)
}
cpConfig := clus.Spec.ControlPlaneConfiguration
if len(cpNodes.Items) != cpConfig.Count {
return fmt.Errorf("control plane node count does not match expected: %v of %v", len(cpNodes.Items), cpConfig.Count)
}
errorList := make([]error, 0)
for _, node := range cpNodes.Items {
if err := validateNodeReady(node, clus.Spec.KubernetesVersion); err != nil {
errorList = append(errorList, fmt.Errorf("failed to validate controlplane node ready: %v", err))
}
if err := validateControlPlaneTaints(clus, node); err != nil {
errorList = append(errorList, fmt.Errorf("failed to validate controlplane node taints: %v", err))
}
}
if len(errorList) > 0 {
return apierrors.NewAggregate(errorList)
}
return nil
}
// ValidateWorkerNodes retries the worker nodes from the cluster and checks them against the cluster.Spec.
func ValidateWorkerNodes(ctx context.Context, vc clusterf.StateValidationConfig) error {
clus := vc.ClusterSpec.Cluster
nodes := &corev1.NodeList{}
if err := vc.ClusterClient.List(ctx, nodes); err != nil {
return fmt.Errorf("failed to list nodes %s", err)
}
errorList := make([]error, 0)
wn := clus.Spec.WorkerNodeGroupConfigurations
// deduce the worker node group configuration to node mapping via the machine deployment and machine set
for _, w := range wn {
workerGroupCount := 0
ms, err := getWorkerNodeMachineSets(ctx, vc, w)
if err != nil {
return fmt.Errorf("failed to get machine sets when validating worker node: %v", err)
}
workerNodes := filterWorkerNodes(nodes.Items, ms, w)
workerGroupCount += len(workerNodes)
for _, node := range workerNodes {
if err := validateNodeReady(node, vc.ClusterSpec.Cluster.Spec.KubernetesVersion); err != nil {
errorList = append(errorList, fmt.Errorf("failed to validate worker node ready %v", err))
}
if err := api.ValidateWorkerNodeTaints(w, node); err != nil {
errorList = append(errorList, fmt.Errorf("failed to validate worker node taints %v", err))
}
}
if workerGroupCount != *w.Count {
errorList = append(errorList, fmt.Errorf("worker node group %s count does not match expected: %d of %d", w.Name, workerGroupCount, *w.Count))
}
}
if len(errorList) > 0 {
return apierrors.NewAggregate(errorList)
}
return nil
}
// ValidateClusterDoesNotExist checks that the cluster does not exist by attempting to retrieve the CAPI cluster.
func ValidateClusterDoesNotExist(ctx context.Context, vc clusterf.StateValidationConfig) error {
clus := vc.ClusterSpec.Cluster
capiCluster, err := controller.GetCAPICluster(ctx, vc.ManagementClusterClient, clus)
if err != nil {
return fmt.Errorf("failed to retrieve cluster %s", err)
}
if capiCluster != nil {
return fmt.Errorf("cluster %s exists", capiCluster.Name)
}
return nil
}
// ValidateCilium gets the cilium-config from the cluster and checks that the cilium
// policy in cluster.Spec matches the enabled policy in the config.
func ValidateCilium(ctx context.Context, vc clusterf.StateValidationConfig) error {
cniConfig := vc.ClusterSpec.Cluster.Spec.ClusterNetwork.CNIConfig
if cniConfig == nil || cniConfig.Cilium == nil {
return errors.New("Cilium configuration missing from cluster spec")
}
if !cniConfig.Cilium.IsManaged() {
// It would be nice if we could log something here given we're skipping the validation.
return nil
}
clusterClient := vc.ClusterClient
yaml := vc.ClusterSpec.Cluster
cm := &corev1.ConfigMap{}
key := types.NamespacedName{Namespace: "kube-system", Name: "cilium-config"}
err := clusterClient.Get(ctx, key, cm)
if err != nil {
return fmt.Errorf("failed to retrieve configmap: %s", err)
}
clusterCilium := cm.Data["enable-policy"]
yamlCilium := string(yaml.Spec.ClusterNetwork.CNIConfig.Cilium.PolicyEnforcementMode)
if yamlCilium == "" && clusterCilium == "default" {
return nil
}
if clusterCilium != yamlCilium {
return fmt.Errorf("cilium policy does not match. ConfigMap: %s, YAML: %s", clusterCilium, yamlCilium)
}
return nil
}
func validateNodeReady(node corev1.Node, kubeVersion v1alpha1.KubernetesVersion) error {
for _, condition := range node.Status.Conditions {
if condition.Type == "Ready" && condition.Status != corev1.ConditionTrue {
return fmt.Errorf("node %s not ready yet. %s", node.GetName(), condition.Reason)
}
}
kubeletVersion := node.Status.NodeInfo.KubeletVersion
if !strings.Contains(kubeletVersion, string(kubeVersion)) {
return fmt.Errorf("validating node version: kubernetes version %s does not match expected version %s", kubeletVersion, kubeVersion)
}
return nil
}
func validateControlPlaneTaints(cluster *v1alpha1.Cluster, node corev1.Node) error {
if cluster.IsSingleNode() {
return api.ValidateControlPlaneNoTaints(cluster.Spec.ControlPlaneConfiguration, node)
}
return api.ValidateControlPlaneTaints(cluster.Spec.ControlPlaneConfiguration, node)
}
func filterWorkerNodes(nodes []corev1.Node, ms []v1beta1.MachineSet, w v1alpha1.WorkerNodeGroupConfiguration) []corev1.Node {
wNodes := make([]corev1.Node, 0)
for _, node := range nodes {
ownerName, ok := node.Annotations["cluster.x-k8s.io/owner-name"]
if ok {
// there will be multiple machineSets present on a cluster following an upgrade.
// find the one that is associated with this worker node, and execute the validations.
for _, machineSet := range ms {
if ownerName == machineSet.Name {
wNodes = append(wNodes, node)
}
}
}
}
return wNodes
}
func getWorkerNodeMachineSets(ctx context.Context, vc clusterf.StateValidationConfig, w v1alpha1.WorkerNodeGroupConfiguration) ([]v1beta1.MachineSet, error) {
mdName := clusterapi.MachineDeploymentName(vc.ClusterSpec.Cluster, w)
ms := &v1beta1.MachineSetList{}
err := vc.ManagementClusterClient.List(ctx, ms, client.InNamespace(constants.EksaSystemNamespace), client.MatchingLabels{
"cluster.x-k8s.io/deployment-name": mdName,
})
if err != nil {
return nil, fmt.Errorf("failed to get machine sets for deployment %s: %v", mdName, err)
}
if len(ms.Items) == 0 {
return nil, fmt.Errorf("invalid number of machine sets associated with worker node configuration %s", w.Name)
}
return ms.Items, nil
}
| 227 |
eks-anywhere | aws | Go | package validations_test
import (
"context"
"fmt"
"testing"
"time"
. "github.com/onsi/gomega"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/equality"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"sigs.k8s.io/cluster-api/api/v1beta1"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/client/fake"
"github.com/aws/eks-anywhere/internal/pkg/api"
"github.com/aws/eks-anywhere/internal/test"
"github.com/aws/eks-anywhere/pkg/api/v1alpha1"
"github.com/aws/eks-anywhere/pkg/cluster"
"github.com/aws/eks-anywhere/pkg/constants"
"github.com/aws/eks-anywhere/pkg/controller/clientutil"
clusterf "github.com/aws/eks-anywhere/test/framework/cluster"
"github.com/aws/eks-anywhere/test/framework/cluster/validations"
)
const (
clusterName = "test-cluster"
clusterNamespace = "test-namespace"
)
type clusterValidationTest struct {
t testing.TB
*WithT
config clusterf.StateValidationConfig
clusterSpec *cluster.Spec
eksaSupportObjs []client.Object
}
func newStateValidatorTest(t testing.TB, clusterSpec *cluster.Spec) *clusterValidationTest {
tt := &clusterValidationTest{
t: t,
WithT: NewWithT(t),
clusterSpec: clusterSpec,
config: clusterf.StateValidationConfig{
ClusterClient: fake.NewClientBuilder().Build(),
ManagementClusterClient: fake.NewClientBuilder().Build(),
ClusterSpec: clusterSpec,
},
eksaSupportObjs: []client.Object{
test.Namespace(clusterNamespace),
test.Namespace(constants.EksaSystemNamespace),
test.Namespace(constants.KubeSystemNamespace),
},
}
return tt
}
func (tt *clusterValidationTest) actualObjects(excludedObjs ...client.Object) []client.Object {
objs := tt.allObjs()
actual := make([]client.Object, 0, len(objs)-len(excludedObjs))
for _, obj := range objs {
isExcluded := false
for _, excluded := range excludedObjs {
isExcluded = equality.Semantic.DeepEqual(obj, excluded)
if isExcluded {
break
}
}
if !isExcluded {
actual = append(actual, obj)
}
}
return actual
}
func (tt *clusterValidationTest) createTestObjects(ctx context.Context, excludedObjects ...client.Object) {
tt.createManagementClusterObjects(ctx, tt.actualObjects(excludedObjects...)...)
}
func (tt *clusterValidationTest) createClusterObjects(ctx context.Context, objs ...client.Object) {
if err := createClientObjects(ctx, tt.config.ClusterClient, objs...); err != nil {
tt.t.Fatalf("failed to create cluster objects: %v", err)
}
}
func (tt *clusterValidationTest) createManagementClusterObjects(ctx context.Context, objs ...client.Object) {
if err := createClientObjects(ctx, tt.config.ManagementClusterClient, objs...); err != nil {
tt.t.Fatalf("failed to create management cluster objects: %v", err)
}
}
func createClientObjects(ctx context.Context, clusterClient client.Client, objs ...client.Object) error {
for _, obj := range objs {
if err := clusterClient.Create(ctx, obj); err != nil {
return err
}
}
return nil
}
func (tt *clusterValidationTest) allObjs() []client.Object {
childObjects := tt.clusterSpec.ChildObjects()
objs := make([]client.Object, 0, len(tt.eksaSupportObjs)+len(childObjects)+1)
objs = append(objs, tt.eksaSupportObjs...)
objs = append(objs, tt.clusterSpec.Cluster)
for _, o := range childObjects {
objs = append(objs, o)
}
return objs
}
func TestValidateClusterReady(t *testing.T) {
g := NewWithT(t)
tests := []struct {
name string
conditions v1beta1.Conditions
cluster *v1alpha1.Cluster
wantErr string
}{
{
name: "CAPI cluster ready",
conditions: v1beta1.Conditions{
{
Type: v1beta1.ConditionType(corev1.NodeReady),
Status: "True",
Reason: "",
LastTransitionTime: metav1.Time{
Time: time.Now(),
},
},
},
cluster: testCluster(),
wantErr: "",
},
{
name: "CAPI cluster does not ready",
conditions: v1beta1.Conditions{
{
Type: v1beta1.ConditionType(corev1.NodeReady),
Status: "False",
Reason: "Never ready for testing",
LastTransitionTime: metav1.Time{
Time: time.Now(),
},
},
},
cluster: testCluster(),
wantErr: fmt.Sprintf("CAPI cluster %s not ready yet.", clusterName),
},
{
name: "CAPI cluster does not exist",
conditions: v1beta1.Conditions{},
cluster: testCluster(),
wantErr: fmt.Sprintf("cluster %s does not exist", clusterName),
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ctx := context.Background()
spec := test.NewClusterSpec(func(s *cluster.Spec) {
s.Cluster = tt.cluster
})
vt := newStateValidatorTest(t, spec)
vt.createTestObjects(ctx)
if len(tt.conditions) != 0 {
capiCluster := test.CAPICluster(func(c *v1beta1.Cluster) {
c.Name = tt.cluster.Name
c.SetConditions(tt.conditions)
})
vt.createManagementClusterObjects(ctx, capiCluster)
}
err := validations.ValidateClusterReady(ctx, vt.config)
if tt.wantErr != "" {
g.Expect(err).To(MatchError(ContainSubstring(tt.wantErr)))
} else {
g.Expect(err).To(BeNil())
}
})
}
}
func TestValidateEKSAObjects(t *testing.T) {
clusterDatacenter := dataCenter()
tests := []struct {
name string
spec *cluster.Spec
excludedObjs []client.Object
wantErr string
}{
{
name: "EKSA objects exists",
spec: test.NewClusterSpec(func(s *cluster.Spec) {
s.Cluster = testCluster()
s.Cluster.Spec.DatacenterRef = v1alpha1.Ref{
Kind: v1alpha1.DockerDatacenterKind,
Name: clusterDatacenter.Name,
}
s.DockerDatacenter = clusterDatacenter
}),
excludedObjs: []client.Object{},
wantErr: "",
},
{
name: "EKSA objects missing",
spec: test.NewClusterSpec(func(s *cluster.Spec) {
s.Cluster = testCluster()
s.Cluster.Spec.DatacenterRef = v1alpha1.Ref{
Kind: v1alpha1.DockerDatacenterKind,
Name: clusterDatacenter.Name,
}
s.DockerDatacenter = clusterDatacenter
}),
excludedObjs: []client.Object{
clusterDatacenter,
},
wantErr: "dockerdatacenterconfigs.anywhere.eks.amazonaws.com \"datacenter\" not found",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ctx := context.Background()
g := NewWithT(t)
vt := newStateValidatorTest(t, tt.spec)
vt.createTestObjects(ctx, tt.excludedObjs...)
err := validations.ValidateEKSAObjects(ctx, vt.config)
if tt.wantErr != "" {
g.Expect(err).To(MatchError(ContainSubstring(tt.wantErr)))
} else {
g.Expect(err).To(BeNil())
}
})
}
}
func TestValidateControlPlanes(t *testing.T) {
tests := []struct {
name string
spec *cluster.Spec
nodes []*corev1.Node
wantErr string
}{
{
name: "control plane nodes valid",
spec: test.NewClusterSpec(func(s *cluster.Spec) {
s.Cluster = testCluster()
s.Cluster.Spec.ControlPlaneConfiguration = v1alpha1.ControlPlaneConfiguration{
Count: 2,
}
}),
nodes: []*corev1.Node{
controlPlaneNode(func(node *corev1.Node) {
node.Name = "test-node-1"
node.Status.Conditions = []corev1.NodeCondition{
{
Type: corev1.NodeReady,
Status: corev1.ConditionTrue,
},
}
}),
controlPlaneNode(func(node *corev1.Node) {
node.Name = "test-node-2"
node.Status.Conditions = []corev1.NodeCondition{
{
Type: corev1.NodeReady,
Status: corev1.ConditionTrue,
},
}
}),
},
wantErr: "",
},
{
name: "control planes nodes count mismatch",
spec: test.NewClusterSpec(func(s *cluster.Spec) {
s.Cluster = testCluster()
s.Cluster.Spec.ControlPlaneConfiguration = v1alpha1.ControlPlaneConfiguration{
Count: 2,
}
}),
nodes: []*corev1.Node{
controlPlaneNode(func(node *corev1.Node) {
node.Name = "test-node-1"
node.Status.Conditions = []corev1.NodeCondition{
{
Type: corev1.NodeReady,
Status: corev1.ConditionTrue,
},
}
}),
},
wantErr: "control plane node count does not match",
},
{
name: "control planes nodes not ready",
spec: test.NewClusterSpec(func(s *cluster.Spec) {
s.Cluster = testCluster()
s.Cluster.Spec.ControlPlaneConfiguration = v1alpha1.ControlPlaneConfiguration{
Count: 2,
}
}),
nodes: []*corev1.Node{
controlPlaneNode(func(node *corev1.Node) {
node.Name = "test-node-1"
node.Status.Conditions = []corev1.NodeCondition{
{
Type: corev1.NodeReady,
Status: corev1.ConditionTrue,
},
}
}),
controlPlaneNode(func(node *corev1.Node) {
node.Name = "test-node-2"
node.Status.Conditions = []corev1.NodeCondition{
{
Type: corev1.NodeReady,
Status: corev1.ConditionFalse,
},
}
}),
},
wantErr: "node test-node-2 not ready yet.",
},
{
name: "control plane node with taint match ",
spec: test.NewClusterSpec(func(s *cluster.Spec) {
s.Cluster = testCluster()
s.Cluster.Spec.ControlPlaneConfiguration = v1alpha1.ControlPlaneConfiguration{
Count: 2,
Taints: []corev1.Taint{api.ControlPlaneTaint()},
}
}),
nodes: []*corev1.Node{
controlPlaneNode(func(node *corev1.Node) {
node.Name = "test-node-1"
node.Status.Conditions = []corev1.NodeCondition{
{
Type: corev1.NodeReady,
Status: corev1.ConditionTrue,
},
}
}),
controlPlaneNode(func(node *corev1.Node) {
node.Name = "test-node-2"
node.Status.Conditions = []corev1.NodeCondition{
{
Type: corev1.NodeReady,
Status: corev1.ConditionTrue,
},
}
}),
},
wantErr: "",
},
{
name: "control plane single node with taints ",
spec: test.NewClusterSpec(func(s *cluster.Spec) {
s.Cluster = testCluster()
s.Cluster.Spec.ControlPlaneConfiguration = v1alpha1.ControlPlaneConfiguration{
Count: 1,
Taints: []corev1.Taint{api.ControlPlaneTaint()},
}
}),
nodes: []*corev1.Node{
controlPlaneNode(func(node *corev1.Node) {
node.Name = "test-node-1"
node.Status.Conditions = []corev1.NodeCondition{
{
Type: corev1.NodeReady,
Status: corev1.ConditionTrue,
},
}
node.Spec.Taints = append(node.Spec.Taints, api.ControlPlaneTaint())
}),
},
wantErr: "taints on control plane node test-node-1 or corresponding control plane configuration found",
},
{
name: "control plane node with taint does not match ",
spec: test.NewClusterSpec(func(s *cluster.Spec) {
s.Cluster = testCluster()
s.Cluster.Spec.ControlPlaneConfiguration = v1alpha1.ControlPlaneConfiguration{
Count: 1,
Taints: []corev1.Taint{
{
Key: "key1",
Value: "value1",
Effect: corev1.TaintEffectNoExecute,
},
},
}
}),
nodes: []*corev1.Node{
controlPlaneNode(func(node *corev1.Node) {
node.Name = "test-node-1"
node.Status.Conditions = []corev1.NodeCondition{
{
Type: corev1.NodeReady,
Status: corev1.ConditionTrue,
},
}
}),
},
wantErr: "failed to validate controlplane node taints: taints on control plane node test-node-1 or corresponding control plane configuration found",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ctx := context.Background()
g := NewWithT(t)
vt := newStateValidatorTest(t, tt.spec)
vt.createTestObjects(ctx)
vt.createClusterObjects(ctx, clientutil.ObjectsToClientObjects(tt.nodes)...)
err := validations.ValidateControlPlaneNodes(ctx, vt.config)
if tt.wantErr != "" {
g.Expect(err).To(MatchError(ContainSubstring(tt.wantErr)))
} else {
g.Expect(err).To(BeNil())
}
})
}
}
func TestValidateCilium(t *testing.T) {
g := NewWithT(t)
ctx := context.Background()
tests := []struct {
name string
cilumPolicy v1alpha1.CiliumPolicyEnforcementMode
cilumConfigMap *corev1.ConfigMap
wantErr string
}{
{
name: "cilium policy enforcement empty",
cilumPolicy: "",
cilumConfigMap: &corev1.ConfigMap{
TypeMeta: metav1.TypeMeta{
Kind: "ConfigMap",
APIVersion: "v1",
},
ObjectMeta: metav1.ObjectMeta{
Namespace: constants.KubeSystemNamespace,
Name: "cilium-config",
},
Data: map[string]string{
"enable-policy": "default",
},
},
wantErr: "",
},
{
name: "matching cilium enforcement policy",
cilumPolicy: v1alpha1.CiliumPolicyModeAlways,
cilumConfigMap: &corev1.ConfigMap{
TypeMeta: metav1.TypeMeta{
Kind: "ConfigMap",
APIVersion: "v1",
},
ObjectMeta: metav1.ObjectMeta{
Namespace: constants.KubeSystemNamespace,
Name: "cilium-config",
},
Data: map[string]string{
"enable-policy": "always",
},
},
wantErr: "",
},
{
name: "no cilium config map",
cilumPolicy: v1alpha1.CiliumPolicyModeAlways,
cilumConfigMap: nil,
wantErr: "failed to retrieve configmap: configmaps \"cilium-config\" not found",
},
{
name: "mismatched cilium enforcement policy ",
cilumPolicy: v1alpha1.CiliumPolicyModeNever,
cilumConfigMap: &corev1.ConfigMap{
TypeMeta: metav1.TypeMeta{
Kind: "ConfigMap",
APIVersion: "v1",
},
ObjectMeta: metav1.ObjectMeta{
Namespace: constants.KubeSystemNamespace,
Name: "cilium-config",
},
Data: map[string]string{
"enable-policy": "always",
},
},
wantErr: "cilium policy does not match. ConfigMap: always, YAML: never",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
vt := newStateValidatorTest(t, test.NewClusterSpec(func(s *cluster.Spec) {
s.Cluster = testCluster()
s.Cluster.Spec.ClusterNetwork = v1alpha1.ClusterNetwork{
CNIConfig: &v1alpha1.CNIConfig{
Cilium: &v1alpha1.CiliumConfig{
PolicyEnforcementMode: tt.cilumPolicy,
},
},
Pods: v1alpha1.Pods{
CidrBlocks: []string{"192.168.0.0/16"},
},
Services: v1alpha1.Services{
CidrBlocks: []string{"10.96.0.0/12"},
},
}
}))
vt.createTestObjects(ctx)
if tt.cilumConfigMap != nil {
vt.createClusterObjects(ctx, tt.cilumConfigMap)
}
err := validations.ValidateCilium(ctx, vt.config)
if tt.wantErr != "" {
g.Expect(err).To(MatchError(ContainSubstring(tt.wantErr)))
} else {
g.Expect(err).To(BeNil())
}
})
}
}
func testCluster() *v1alpha1.Cluster {
return &v1alpha1.Cluster{
ObjectMeta: metav1.ObjectMeta{
Name: clusterName,
Namespace: clusterNamespace,
},
}
}
func dataCenter() *v1alpha1.DockerDatacenterConfig {
return &v1alpha1.DockerDatacenterConfig{
TypeMeta: metav1.TypeMeta{
Kind: v1alpha1.DockerDatacenterKind,
APIVersion: v1alpha1.GroupVersion.String(),
},
ObjectMeta: metav1.ObjectMeta{
Name: "datacenter",
Namespace: clusterNamespace,
},
}
}
type controlPlaneNodeOpt = func(node *corev1.Node)
func controlPlaneNode(opts ...controlPlaneNodeOpt) *corev1.Node {
n := &corev1.Node{
TypeMeta: metav1.TypeMeta{
APIVersion: "v1",
Kind: "Node",
},
ObjectMeta: metav1.ObjectMeta{
Name: "test-node",
Namespace: clusterNamespace,
Labels: map[string]string{
"node-role.kubernetes.io/control-plane": "",
},
},
Spec: corev1.NodeSpec{
Taints: []corev1.Taint{
api.ControlPlaneTaint(),
},
},
Status: corev1.NodeStatus{
Conditions: []corev1.NodeCondition{
{
Type: corev1.NodeReady,
Status: corev1.ConditionFalse,
},
},
},
}
for _, opt := range opts {
opt(n)
}
return n
}
| 586 |
eks-anywhere-build-tooling | aws | Go | package main
import (
"flag"
"fmt"
"github.com/eks-anywhere-build-tooling/aws/bottlerocket-bootstrap/pkg"
"github.com/eks-anywhere-build-tooling/aws/bottlerocket-bootstrap/pkg/utils"
)
func main() {
logVerbosity := flag.String("v", "9", "Verbosity of logs")
utils.LogVerbosity = fmt.Sprintf("-v%s", *logVerbosity)
pkg.Bootstrap()
}
| 16 |
eks-anywhere-build-tooling | aws | Go | package pkg
import (
"fmt"
"os"
"strings"
"time"
"github.com/eks-anywhere-build-tooling/aws/bottlerocket-bootstrap/pkg/etcdadm"
"github.com/eks-anywhere-build-tooling/aws/bottlerocket-bootstrap/pkg/kubeadm"
"github.com/eks-anywhere-build-tooling/aws/bottlerocket-bootstrap/pkg/utils"
"github.com/pkg/errors"
)
const (
marker = "/.bottlerocket/host-containers/" + utils.BootstrapContainerName + "/.ran"
)
func acquireLock() {
if _, err := os.Stat(marker); err == nil {
// Lock cannot be acquired, another instance of bootstrap is running
fmt.Println("Cannot acquire lock, another instance of bootstrap is already running")
err = utils.DisableBootstrapContainer()
if err != nil {
fmt.Println("Failed to run command, set bootstrapContainer to false")
}
time.Sleep(100000)
} else {
// Create file to indicate lock acquisition
os.Create(marker)
fmt.Println("Acquired lock for bootstrap")
}
}
func waitForPreReqs() error {
fmt.Println("Waiting for bottlerocket boot to complete...")
err := utils.WaitForSystemdService(utils.MultiUserTarget, 5*time.Minute)
if err != nil {
return errors.Wrapf(err, "Error waiting for multi-user.target\n")
}
err = utils.WaitForSystemdService(utils.KubeletService, 30*time.Second)
if err != nil {
return errors.Wrapf(err, "Error waiting for kubelet")
}
fmt.Println("Bottlerocket bootstrap pre-requisites complete")
return nil
}
func Bootstrap() {
err := waitForPreReqs()
if err != nil {
fmt.Printf("Error waiting for bottlerocket pre-reqs: %v", err)
os.Exit(1)
}
fmt.Println("Initiating bottlerocket bootstrap")
acquireLock()
userData, err := utils.ResolveHostContainerUserData()
if err != nil {
fmt.Printf("Error parsing user-data: %v\n", err)
os.Exit(1)
}
b := buildBootstrapper(userData)
if err = b.InitializeDirectories(); err != nil {
fmt.Printf("Error initializing directories: %v\n", err)
os.Exit(1)
}
if err = utils.WriteUserDataFiles(userData); err != nil {
fmt.Printf("Error writing files from user-data: %v\n", err)
os.Exit(1)
}
if err = b.RunCmd(); err != nil {
fmt.Printf("Error running bootstrapper cmd: %v\n", err)
os.Exit(1)
}
// Bootstrapping done
err = utils.DisableBootstrapContainer()
if err != nil {
fmt.Printf("Error disabling bootstrap container: %v\n", err)
os.Exit(1)
}
fmt.Println("Bottlerocket bootstrap was successful. Disabled bootstrap container")
os.Exit(0)
}
type bootstrapper interface {
InitializeDirectories() error
RunCmd() error
}
func buildBootstrapper(userData *utils.UserData) bootstrapper {
if strings.HasPrefix(userData.RunCmd, etcdadm.CmdPrefix) {
fmt.Println("Using etcdadm support by CAPI")
return etcdadm.New(userData)
} else {
fmt.Println("Using kubeadm support by CAPI")
return kubeadm.New(userData)
}
}
| 107 |
eks-anywhere-build-tooling | aws | Go | package etcdadm
import (
"os"
"strings"
"github.com/eks-anywhere-build-tooling/aws/bottlerocket-bootstrap/pkg/files"
"github.com/eks-anywhere-build-tooling/aws/bottlerocket-bootstrap/pkg/utils"
"github.com/pkg/errors"
)
const (
CmdPrefix = "Etcdadm"
manifestFileName = "etcd.manifest"
rootfsEtcdBaseDir = "/.bottlerocket/rootfs/var/lib/etcd"
etcdBaseDir = "/var/lib/etcd"
certFolder = "/pki"
dataFolder = "/data"
certDir = etcdBaseDir + certFolder
dataDir = etcdBaseDir + dataFolder
rootfsCertDir = rootfsEtcdBaseDir + certFolder
rootfsDataDir = rootfsEtcdBaseDir + dataFolder
podSpecDir = "./manifests"
initCmd = "EtcdadmInit"
joinCmd = "EtcdadmJoin"
etcdadmBinary = "/opt/bin/etcdadm"
)
var dirs = []string{podSpecDir, rootfsDataDir, rootfsCertDir}
type etcdadm struct {
userData *utils.UserData
}
func New(userData *utils.UserData) *etcdadm {
return &etcdadm{userData: userData}
}
func (e *etcdadm) InitializeDirectories() error {
for _, dir := range dirs {
if err := os.MkdirAll(dir, 0o640); err != nil {
return errors.Wrapf(err, "error creating etcdadm directory [%s]", dir)
}
}
if err := files.CreateSymLink(rootfsEtcdBaseDir, etcdBaseDir); err != nil {
return errors.Wrap(err, "failed init symlinks for etcdadm")
}
return nil
}
func (e *etcdadm) RunCmd() error {
cmd, err := parseCmd(e.userData.RunCmd)
if err != nil {
return err
}
if err = cmd.run(); err != nil {
return err
}
return nil
}
type command interface {
run() error
}
func parseCmd(bootstrapCmd string) (command, error) {
words := strings.Fields(bootstrapCmd)
if len(words) == 0 {
return nil, errors.Errorf("invalid bootstrap etcdadm command [%s]", bootstrapCmd)
}
cmd := words[0]
switch cmd {
case initCmd:
if len(words) != 4 {
return nil, errors.Errorf("invalid bootstrap etcdadm init command [%s]", bootstrapCmd)
}
return &initCommand{repository: words[1], version: words[2], cipherSuites: words[3]}, nil
case joinCmd:
if len(words) != 5 {
return nil, errors.Errorf("invalid bootstrap etcdadm join command [%s]", bootstrapCmd)
}
return &joinCommand{repository: words[1], version: words[2], cipherSuites: words[3], endpoint: words[4]}, nil
default:
return nil, errors.Errorf("invalid etcdadm bootstrap command %s", bootstrapCmd)
}
}
| 97 |
eks-anywhere-build-tooling | aws | Go | package etcdadm
func buildFlags(repository, version, cipherSuites string) []string {
return []string{
"-l", "debug",
"--version", version,
"--init-system", "kubelet",
"--image-repository", repository,
"--certs-dir", certDir,
"--data-dir", dataDir,
"--kubelet-pod-manifest-path", podSpecDir,
"--cipher-suites", cipherSuites,
}
}
| 15 |
eks-anywhere-build-tooling | aws | Go | package etcdadm
import (
"fmt"
"github.com/eks-anywhere-build-tooling/aws/bottlerocket-bootstrap/pkg/utils"
"github.com/pkg/errors"
)
var initPreKubeletPhases = []string{
"install",
"certificates",
"snapshot",
"configure",
"start",
}
var initPostKubeletPhases = []string{"health"}
type initCommand struct {
repository string
version string
cipherSuites string
}
func (i *initCommand) run() error {
flags := buildFlags(i.repository, i.version, i.cipherSuites)
fmt.Println("Running etcdadm init phases")
if err := runPhases("init", initPreKubeletPhases, flags); err != nil {
return err
}
fmt.Println("Starting etcd static pods")
podDefinitions, err := utils.EnableStaticPods(podSpecDir)
if err != nil {
return errors.Wrap(err, "error enabling etcd static pods")
}
fmt.Println("Waiting for etcd static pods")
err = utils.WaitForPods(podDefinitions)
if err != nil {
return errors.Wrapf(err, "error waiting for etcd static pods to be up")
}
if err := runPhases("init", initPostKubeletPhases, flags); err != nil {
return err
}
return nil
}
| 51 |
eks-anywhere-build-tooling | aws | Go | package etcdadm
import (
"fmt"
"github.com/eks-anywhere-build-tooling/aws/bottlerocket-bootstrap/pkg/utils"
"github.com/pkg/errors"
)
var joinPreKubeletPhases = []string{
"stop",
"certificates",
"membership",
"install",
"configure",
"start",
}
var joinPostKubeletPhases = []string{"health"}
type joinCommand struct {
repository string
version string
endpoint string
cipherSuites string
}
func (j *joinCommand) run() error {
flags := buildFlags(j.repository, j.version, j.cipherSuites)
fmt.Println("Running etcdadm join phases")
if err := runPhases("join", joinPreKubeletPhases, flags, j.endpoint); err != nil {
return err
}
fmt.Println("Starting etcd static pods")
podDefinitions, err := utils.EnableStaticPods(podSpecDir)
if err != nil {
return errors.Wrap(err, "error enabling etcd static pods")
}
fmt.Println("Waiting for etcd static pods")
err = utils.WaitForPods(podDefinitions)
if err != nil {
return errors.Wrapf(err, "error waiting for etcd static pods to be up")
}
if err := runPhases("join", joinPostKubeletPhases, flags, j.endpoint); err != nil {
return err
}
return nil
}
| 53 |
eks-anywhere-build-tooling | aws | Go | package etcdadm
import (
"fmt"
"os/exec"
"github.com/pkg/errors"
)
func runPhases(command string, phases, flags []string, args ...string) error {
for _, phase := range phases {
fmt.Printf("Running etcdadm %s %s phase\n", command, phase)
cmd := exec.Command(etcdadmBinary, buildPhaseCmd(command, phase, args...).addFlags(flags...)...)
out, err := cmd.CombinedOutput()
fmt.Printf("Phase command output:\n--------\n%s\n--------\n", string(out))
if err != nil {
return errors.Wrapf(err, "error running etcdadm phase '%s %s', out:\n %s", command, phase, string(out))
}
}
return nil
}
type etcdadmCommand []string
func buildPhaseCmd(command, phase string, args ...string) etcdadmCommand {
cmd := make(etcdadmCommand, 0, len(args)+3)
cmd = append(cmd, command, "phase", phase)
cmd = append(cmd, args...)
return cmd
}
func (e etcdadmCommand) addFlags(flags ...string) etcdadmCommand {
e = append(e, flags...)
return e
}
| 37 |
eks-anywhere-build-tooling | aws | Go | package executables
import (
"encoding/json"
"fmt"
"github.com/pkg/errors"
"github.com/eks-anywhere-build-tooling/aws/bottlerocket-bootstrap/pkg/utils"
)
type APIClient struct {
Executable
}
type APISetting struct {
Kernel *Kernel `json:"kernel,omitempty"`
Kubernetes *Kubernetes `json:"kubernetes,omitempty"`
}
type Kernel struct {
Sysctl map[string]string `json:"sysctl,omitempty"`
}
type Kubernetes struct {
AllowedUnsafeSysctls []string `json:"allowed-unsafe-sysctls,omitempty"`
}
func NewAPIClient() *APIClient {
return &APIClient{
Executable: NewExecutable(utils.ApiclientBinary),
}
}
func (a *APIClient) SetKubernetesCloudProvider(cloudProvider string) error {
_, err := a.Execute("set", fmt.Sprintf("kubernetes.cloud-provider=%q", cloudProvider))
return err
}
func (a *APIClient) SetKubernetesNodeIP(ip string) error {
_, err := a.Execute("set", "kubernetes.node-ip="+ip)
return err
}
func (a *APIClient) SetKubernetesProviderID(id string) error {
_, err := a.Execute("set", "kubernetes.provider-id="+id)
return err
}
func (a *APIClient) Set(setting *APISetting) error {
config, err := json.Marshal(setting)
if err != nil {
return errors.Wrap(err, "error json marshalling api setting")
}
_, err = a.Execute("set", "--json", string(config))
return err
}
func (a *APIClient) Reboot() error {
_, err := a.Execute("reboot")
return err
}
| 63 |
eks-anywhere-build-tooling | aws | Go | package executables_test
import (
"errors"
"testing"
"github.com/golang/mock/gomock"
. "github.com/onsi/gomega"
"github.com/eks-anywhere-build-tooling/aws/bottlerocket-bootstrap/pkg/executables"
"github.com/eks-anywhere-build-tooling/aws/bottlerocket-bootstrap/pkg/executables/mocks"
)
type apiClientTest struct {
*WithT
a *executables.APIClient
e *mocks.MockExecutable
}
func newAPIClientTest(t *testing.T) *apiClientTest {
e := mocks.NewMockExecutable(gomock.NewController(t))
return &apiClientTest{
WithT: NewWithT(t),
a: &executables.APIClient{Executable: e},
e: e,
}
}
func TestSetKubernetesCloudProvider(t *testing.T) {
tests := []struct {
testName string
cloudProvider string
args []string
wantError bool
returnError bool
}{
{
testName: "cloud provider empty string",
cloudProvider: "",
args: []string{"set", `kubernetes.cloud-provider=""`},
returnError: false,
wantError: false,
},
{
testName: "cloud provider aws",
cloudProvider: "aws",
args: []string{"set", `kubernetes.cloud-provider="aws"`},
returnError: false,
wantError: false,
},
{
testName: "cloud provider empty, error",
cloudProvider: "",
args: []string{"set", `kubernetes.cloud-provider=""`},
returnError: true,
wantError: true,
},
}
for _, tc := range tests {
t.Run(tc.testName, func(t *testing.T) {
tt := newAPIClientTest(t)
if tc.returnError {
tt.e.EXPECT().Execute(tc.args).Return(nil, errors.New("exec error"))
} else {
tt.e.EXPECT().Execute(tc.args).Return([]byte{}, nil)
}
err := tt.a.SetKubernetesCloudProvider(tc.cloudProvider)
if tc.wantError {
tt.Expect(err).NotTo(BeNil())
} else {
tt.Expect(err).To(BeNil())
}
})
}
}
func TestSetKubernetesNodeIP(t *testing.T) {
tests := []struct {
testName string
ip string
args []string
wantError bool
returnError bool
}{
{
testName: "ip empty string",
ip: "",
args: []string{"set", "kubernetes.node-ip="},
returnError: false,
wantError: false,
},
{
testName: "valid",
ip: "1.2.3.4",
args: []string{"set", "kubernetes.node-ip=1.2.3.4"},
returnError: false,
wantError: false,
},
{
testName: "exec error",
ip: "1.2.3.4",
args: []string{"set", "kubernetes.node-ip=1.2.3.4"},
returnError: true,
wantError: true,
},
}
for _, tc := range tests {
t.Run(tc.testName, func(t *testing.T) {
tt := newAPIClientTest(t)
if tc.returnError {
tt.e.EXPECT().Execute(tc.args).Return(nil, errors.New("exec error"))
} else {
tt.e.EXPECT().Execute(tc.args).Return([]byte{}, nil)
}
err := tt.a.SetKubernetesNodeIP(tc.ip)
if tc.wantError {
tt.Expect(err).NotTo(BeNil())
} else {
tt.Expect(err).To(BeNil())
}
})
}
}
func TestSetKubernetesProviderID(t *testing.T) {
tests := []struct {
testName string
id string
args []string
wantError bool
returnError bool
}{
{
testName: "valid",
id: "id-0",
args: []string{"set", "kubernetes.provider-id=id-0"},
returnError: false,
wantError: false,
},
{
testName: "exec error",
id: "id-0",
args: []string{"set", "kubernetes.provider-id=id-0"},
returnError: true,
wantError: true,
},
}
for _, tc := range tests {
t.Run(tc.testName, func(t *testing.T) {
tt := newAPIClientTest(t)
if tc.returnError {
tt.e.EXPECT().Execute(tc.args).Return(nil, errors.New("exec error"))
} else {
tt.e.EXPECT().Execute(tc.args).Return([]byte{}, nil)
}
err := tt.a.SetKubernetesProviderID(tc.id)
if tc.wantError {
tt.Expect(err).NotTo(BeNil())
} else {
tt.Expect(err).To(BeNil())
}
})
}
}
func TestAPISet(t *testing.T) {
tests := []struct {
testName string
setting *executables.APISetting
args []string
wantError bool
returnError bool
}{
{
testName: "kernel config",
setting: &executables.APISetting{
Kernel: &executables.Kernel{
Sysctl: map[string]string{
"net.core.rmem_max": "0123",
"net.core.wmem_max": "0123",
"kernel.core_pattern": "/var/corefile/core.%e.%p.%h.%t",
},
},
Kubernetes: &executables.Kubernetes{
AllowedUnsafeSysctls: []string{
"net.ipv4.tcp_mtu_probing",
},
},
},
args: []string{"set", "--json", `{"kernel":{"sysctl":{"kernel.core_pattern":"/var/corefile/core.%e.%p.%h.%t","net.core.rmem_max":"0123","net.core.wmem_max":"0123"}},"kubernetes":{"allowed-unsafe-sysctls":["net.ipv4.tcp_mtu_probing"]}}`},
returnError: false,
wantError: false,
},
{
testName: "exec error",
setting: &executables.APISetting{
Kernel: &executables.Kernel{
Sysctl: map[string]string{
"kernel.core_pattern": "pattern-1",
},
},
},
args: []string{"set", "--json", `{"kernel":{"sysctl":{"kernel.core_pattern":"pattern-1"}}}`},
returnError: true,
wantError: true,
},
}
for _, tc := range tests {
t.Run(tc.testName, func(t *testing.T) {
tt := newAPIClientTest(t)
if tc.returnError {
tt.e.EXPECT().Execute(tc.args).Return(nil, errors.New("exec error"))
} else {
tt.e.EXPECT().Execute(tc.args).Return([]byte{}, nil)
}
err := tt.a.Set(tc.setting)
if tc.wantError {
tt.Expect(err).NotTo(BeNil())
} else {
tt.Expect(err).To(BeNil())
}
})
}
}
func TestReboot(t *testing.T) {
tests := []struct {
testName string
args []string
wantError bool
returnError bool
}{
{
testName: "success",
args: []string{"reboot"},
returnError: false,
wantError: false,
},
{
testName: "exec error",
args: []string{"reboot"},
returnError: true,
wantError: true,
},
}
for _, tc := range tests {
t.Run(tc.testName, func(t *testing.T) {
tt := newAPIClientTest(t)
if tc.returnError {
tt.e.EXPECT().Execute(tc.args).Return(nil, errors.New("exec error"))
} else {
tt.e.EXPECT().Execute(tc.args).Return([]byte{}, nil)
}
err := tt.a.Reboot()
if tc.wantError {
tt.Expect(err).NotTo(BeNil())
} else {
tt.Expect(err).To(BeNil())
}
})
}
}
| 273 |
eks-anywhere-build-tooling | aws | Go | //go:generate ../../hack/tools/bin/mockgen -destination ./mocks/executables_mock.go -package mocks . Executable
package executables
import (
"os/exec"
"github.com/pkg/errors"
)
type Executable interface {
Execute(args ...string) (out []byte, err error)
}
type executable struct {
binary string
}
func NewExecutable(binary string) Executable {
return &executable{
binary: binary,
}
}
func (e *executable) Execute(args ...string) ([]byte, error) {
cmd := exec.Command(e.binary, args...)
out, err := cmd.CombinedOutput()
if err != nil {
return nil, errors.Wrapf(err, "Error running command: %v, output: %s\n", cmd, string(out))
}
return out, nil
}
| 33 |
eks-anywhere-build-tooling | aws | Go | package executables
const (
mountBinary = "mount"
mkfsExt4Binary = "mkfs.ext4"
)
type FileSystem struct {
Mount, Mkfs Executable
}
func NewFileSystem() *FileSystem {
return &FileSystem{
Mount: NewExecutable(mountBinary),
Mkfs: NewExecutable(mkfsExt4Binary),
}
}
func (f *FileSystem) MountVolume(device, dir string) error {
_, err := f.Mount.Execute(device, dir)
return err
}
func (f *FileSystem) Partition(device string) error {
_, err := f.Mkfs.Execute(device)
return err
}
| 28 |
eks-anywhere-build-tooling | aws | Go | package executables_test
import (
"errors"
"testing"
"github.com/golang/mock/gomock"
. "github.com/onsi/gomega"
"github.com/eks-anywhere-build-tooling/aws/bottlerocket-bootstrap/pkg/executables"
"github.com/eks-anywhere-build-tooling/aws/bottlerocket-bootstrap/pkg/executables/mocks"
)
type fileSystemTest struct {
*WithT
f *executables.FileSystem
e *mocks.MockExecutable
}
func newFileSystemTest(t *testing.T) *fileSystemTest {
e := mocks.NewMockExecutable(gomock.NewController(t))
return &fileSystemTest{
WithT: NewWithT(t),
f: &executables.FileSystem{Mount: e, Mkfs: e},
e: e,
}
}
func TestMountVolume(t *testing.T) {
tests := []struct {
testName string
device string
dir string
args []string
wantError bool
returnError bool
}{
{
testName: "valid",
device: "device-1",
dir: "dir-1",
args: []string{"device-1", "dir-1"},
returnError: false,
wantError: false,
},
{
testName: "exec error",
device: "device-1",
dir: "dir-1",
args: []string{"device-1", "dir-1"},
returnError: true,
wantError: true,
},
}
for _, tc := range tests {
t.Run(tc.testName, func(t *testing.T) {
tt := newFileSystemTest(t)
if tc.returnError {
tt.e.EXPECT().Execute(tc.args).Return(nil, errors.New("exec error"))
} else {
tt.e.EXPECT().Execute(tc.args).Return([]byte{}, nil)
}
err := tt.f.MountVolume(tc.device, tc.dir)
if tc.wantError {
tt.Expect(err).NotTo(BeNil())
} else {
tt.Expect(err).To(BeNil())
}
})
}
}
func TestPartition(t *testing.T) {
tests := []struct {
testName string
partition string
args []string
wantError bool
returnError bool
}{
{
testName: "valid",
partition: "device-1",
args: []string{"device-1"},
returnError: false,
wantError: false,
},
{
testName: "exec error",
partition: "device-1",
args: []string{"device-1"},
returnError: true,
wantError: true,
},
}
for _, tc := range tests {
t.Run(tc.testName, func(t *testing.T) {
tt := newFileSystemTest(t)
if tc.returnError {
tt.e.EXPECT().Execute(tc.args).Return(nil, errors.New("exec error"))
} else {
tt.e.EXPECT().Execute(tc.args).Return([]byte{}, nil)
}
err := tt.f.Partition(tc.partition)
if tc.wantError {
tt.Expect(err).NotTo(BeNil())
} else {
tt.Expect(err).To(BeNil())
}
})
}
}
| 117 |
eks-anywhere-build-tooling | aws | Go | // Code generated by MockGen. DO NOT EDIT.
// Source: github.com/eks-anywhere-build-tooling/aws/bottlerocket-bootstrap/pkg/executables (interfaces: Executable)
// Package mocks is a generated GoMock package.
package mocks
import (
reflect "reflect"
gomock "github.com/golang/mock/gomock"
)
// MockExecutable is a mock of Executable interface.
type MockExecutable struct {
ctrl *gomock.Controller
recorder *MockExecutableMockRecorder
}
// MockExecutableMockRecorder is the mock recorder for MockExecutable.
type MockExecutableMockRecorder struct {
mock *MockExecutable
}
// NewMockExecutable creates a new mock instance.
func NewMockExecutable(ctrl *gomock.Controller) *MockExecutable {
mock := &MockExecutable{ctrl: ctrl}
mock.recorder = &MockExecutableMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockExecutable) EXPECT() *MockExecutableMockRecorder {
return m.recorder
}
// Execute mocks base method.
func (m *MockExecutable) Execute(arg0 ...string) ([]byte, error) {
m.ctrl.T.Helper()
varargs := []interface{}{}
for _, a := range arg0 {
varargs = append(varargs, a)
}
ret := m.ctrl.Call(m, "Execute", varargs...)
ret0, _ := ret[0].([]byte)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// Execute indicates an expected call of Execute.
func (mr *MockExecutableMockRecorder) Execute(arg0 ...interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Execute", reflect.TypeOf((*MockExecutable)(nil).Execute), arg0...)
}
| 54 |
eks-anywhere-build-tooling | aws | Go | package files
import (
"fmt"
"os"
"os/exec"
"github.com/pkg/errors"
)
func CreateSymLink(from, to string) error {
// Force symlink creation with cmd. sdk calls fail if the symlink dir exists
cmd := exec.Command("bash", "-c", fmt.Sprintf("ln -sfn %s %s", from, to))
if err := cmd.Run(); err != nil {
return errors.Wrapf(err, "error creating symlink: %v", cmd)
}
return nil
}
func PathExists(path string) bool {
_, err := os.Stat(path)
return !os.IsNotExist(err)
}
| 25 |
eks-anywhere-build-tooling | aws | Go | package files
import (
"bytes"
"text/template"
"github.com/pkg/errors"
)
func ExecuteTemplate(content string, data interface{}) ([]byte, error) {
temp := template.New("tmpl")
temp, err := temp.Parse(content)
if err != nil {
return nil, errors.Wrap(err, "Error parsing template")
}
var buf bytes.Buffer
err = temp.Execute(&buf, data)
if err != nil {
return nil, errors.Wrap(err, "Error substituting values for template")
}
return buf.Bytes(), nil
}
| 24 |
eks-anywhere-build-tooling | aws | Go | package files
import (
"io/fs"
"io/ioutil"
"os"
"path/filepath"
"github.com/pkg/errors"
)
func Write(path string, content []byte, permission fs.FileMode) error {
dir := filepath.Dir(path)
if err := os.MkdirAll(dir, 0o640); err != nil {
return errors.Wrap(err, "Error creating directory")
}
if err := ioutil.WriteFile(path, content, permission); err != nil {
return errors.Wrapf(err, "Error writing file: %s", path)
}
return nil
}
| 22 |
eks-anywhere-build-tooling | aws | Go | package kubeadm
import (
"fmt"
"os/exec"
"strings"
"time"
versionutil "k8s.io/apimachinery/pkg/util/version"
"github.com/eks-anywhere-build-tooling/aws/bottlerocket-bootstrap/pkg/utils"
"github.com/pkg/errors"
)
const (
kubeadmFile = "/tmp/kubeadm.yaml"
kubectl = "/opt/bin/kubectl"
kubeadmBinary = "/opt/bin/kubeadm"
)
func controlPlaneInit() error {
err := setHostName(kubeadmFile)
if err != nil {
return errors.Wrap(err, "Error replacing hostname on kubeadm")
}
// start optional EBS initialization
ebsInitControl := startEbsInit()
// Generate keys and write all the manifests
fmt.Println("Running kubeadm init commands")
cmd := exec.Command(kubeadmBinary, utils.LogVerbosity, "init", "phase", "certs", "all", "--config", kubeadmFile)
out, err := cmd.CombinedOutput()
if err != nil {
return errors.Wrapf(err, "Error running command, out: %s", string(out))
}
fmt.Printf("Running command: %v\n, output: %s\n", cmd, string(out))
cmd = exec.Command(kubeadmBinary, utils.LogVerbosity, "init", "phase", "kubeconfig", "all", "--config", kubeadmFile)
out, err = cmd.CombinedOutput()
if err != nil {
return errors.Wrapf(err, "Error running command: %v", cmd)
}
fmt.Printf("Running command: %v\n, output: %s\n", cmd, string(out))
cmd = exec.Command(kubeadmBinary, utils.LogVerbosity, "init", "phase", "control-plane", "all", "--config", kubeadmFile)
out, err = cmd.CombinedOutput()
if err != nil {
return errors.Wrapf(err, "Error running command: %v", cmd)
}
fmt.Printf("Running command: %v\n, output: %s\n", cmd, string(out))
cmd = exec.Command(kubeadmBinary, utils.LogVerbosity, "init", "phase", "etcd", "local", "--config", kubeadmFile)
out, err = cmd.CombinedOutput()
if err != nil {
return errors.Wrapf(err, "Error running command: %v", cmd)
}
fmt.Printf("Running command: %v\n, output: %s\n", cmd, string(out))
// Migrate all static pods from host-container to bottlerocket host using apiclient
podDefinitions, err := utils.EnableStaticPods("/etc/kubernetes/manifests")
if err != nil {
return errors.Wrap(err, "Error enabling static pods")
}
// Wait for all static pods liveness probe to be up
err = utils.WaitForPods(podDefinitions)
if err != nil {
return errors.Wrapf(err, "Error waiting for static pods to be up")
}
// Get server from admin.conf
apiServer, err := utils.GetApiServerFromKubeConfig("/etc/kubernetes/admin.conf")
if err != nil {
return errors.Wrap(err, "Error getting api server")
}
fmt.Printf("APIServer is %s\n", apiServer)
// Get CA
b64CA, err := getEncodedCA()
if err != nil {
return errors.Wrap(err, "Error reading the ca data")
}
localApiServerReadinessEndpoint, err := getLocalApiServerReadinessEndpoint()
if err != nil {
fmt.Printf("unable to get local apiserver readiness endpoint, falling back to localhost:6443. caused by: %s", err.Error())
localApiServerReadinessEndpoint = "https://localhost:6443/healthz"
}
// Wait for Kubernetes API server to come up.
err = utils.WaitFor200(localApiServerReadinessEndpoint, 30*time.Second)
if err != nil {
return err
}
// If the api advertise url is different than localhost, like when using kube-vip, make
// sure it is accessible
err = utils.WaitFor200(string(apiServer)+"/healthz", 30*time.Second)
if err != nil {
return err
}
// Set up the roles so our kubelet can bootstrap.
cmd = exec.Command(kubeadmBinary, utils.LogVerbosity, "init", "phase", "bootstrap-token", "--config", kubeadmFile)
if err := cmd.Run(); err != nil {
return errors.Wrapf(err, "Error running command: %v", cmd)
}
token, err := getBootstrapToken()
if err != nil {
return errors.Wrap(err, "Error getting token")
}
fmt.Printf("Bootstrap token is: %s\n", token)
// token string already has escaped quotes
args := []string{
"set",
"kubernetes.api-server=" + apiServer,
"kubernetes.cluster-certificate=" + b64CA,
"kubernetes.bootstrap-token=" + string(token),
"kubernetes.authentication-mode=tls",
"kubernetes.standalone-mode=false",
}
kubeletTlsConfig := readKubeletTlsConfig(&RealFileReader{})
if kubeletTlsConfig != nil {
args = append(args, "settings.kubernetes.server-certificate="+kubeletTlsConfig.KubeletServingCert)
args = append(args, "settings.kubernetes.server-key="+kubeletTlsConfig.KubeletServingPrivateKey)
}
cmd = exec.Command(utils.ApiclientBinary, args...)
out, err = cmd.CombinedOutput()
if err != nil {
fmt.Println(string(out))
return errors.Wrapf(err, "Error running command: %v", cmd)
}
err = waitForActiveKubelet()
if err != nil {
return errors.Wrap(err, "Error waiting for kubelet to come up")
}
cmd = exec.Command(kubeadmBinary, "version", "-o=short")
out, err = cmd.CombinedOutput()
if err != nil {
return errors.Wrapf(err, "Error running command: %v, Output: %s\n", cmd, string(out))
}
kubeadmVersion, err := versionutil.ParseSemantic(strings.TrimSuffix(string(out), "\n"))
if err != nil {
return errors.Wrapf(err, "%s is not a valid kubeadm version", string(out))
}
// we compare the kubeadm version to v1.26 because a new phase "show-join-command" was introduced in that version.
// this comparison can be removed when we deprecate v1.25.
compare, err := kubeadmVersion.Compare("1.26.0")
if err != nil {
return errors.Wrap(err, "Error comparing versions")
}
// finish kubeadm
if compare == -1 {
cmd = exec.Command(kubeadmBinary, utils.LogVerbosity, "init", "--skip-phases", "preflight,kubelet-start,certs,kubeconfig,bootstrap-token,control-plane,etcd",
"--config", kubeadmFile)
} else {
cmd = exec.Command(kubeadmBinary, utils.LogVerbosity, "init", "--skip-phases", "preflight,kubelet-start,certs,kubeconfig,bootstrap-token,control-plane,etcd,show-join-command",
"--config", kubeadmFile)
}
out, err = cmd.CombinedOutput()
if err != nil {
return errors.Wrapf(err, "Error running command: %v, Output: %s\n", cmd, string(out))
}
// Now that Core DNS is installed, find the cluster DNS IP.
dns, err := getDNS("/etc/kubernetes/admin.conf")
if err != nil {
return errors.Wrap(err, "Error getting dns ip")
}
// set dns
cmd = exec.Command(utils.ApiclientBinary, "set", "kubernetes.cluster-dns-ip="+string(dns))
out, err = cmd.CombinedOutput()
if err != nil {
return errors.Wrapf(err, "Error running command: %v, output: %s\n", cmd, string(out))
}
if ebsInitControl != nil {
checkEbsInit(ebsInitControl)
}
return nil
}
| 188 |
eks-anywhere-build-tooling | aws | Go | package kubeadm
import (
"fmt"
"os"
"os/exec"
"time"
"github.com/eks-anywhere-build-tooling/aws/bottlerocket-bootstrap/pkg/utils"
"github.com/pkg/errors"
)
const kubeconfigPath = "/etc/kubernetes/admin.conf"
func controlPlaneJoin() error {
err := setHostName(kubeadmJoinFile)
if err != nil {
return errors.Wrap(err, "Error replacing hostname on kubeadm")
}
// start optional EBS initialization
ebsInitControl := startEbsInit()
cmd := exec.Command(kubeadmBinary, utils.LogVerbosity, "join", "phase", "control-plane-prepare", "all", "--config", kubeadmJoinFile)
if err := cmd.Run(); err != nil {
return errors.Wrapf(err, "Error running command: %v", cmd)
}
cmd = exec.Command(kubeadmBinary, utils.LogVerbosity, "join", "phase", "kubelet-start", "--config", kubeadmJoinFile)
if err := cmd.Start(); err != nil {
return errors.Wrapf(err, "Error running command: %v", cmd)
}
err = killCmdAfterJoinFilesGeneration(cmd)
if err != nil {
return errors.Wrap(err, "Error waiting for worker join files")
}
dns, err := getDNSFromJoinConfig("/var/lib/kubelet/config.yaml")
if err != nil {
return errors.Wrap(err, "Error getting api server")
}
apiServer, token, err := getBootstrapFromJoinConfig(kubeadmJoinFile)
if err != nil {
return errors.Wrap(err, "Error getting api server")
}
// Get CA
b64CA, err := getEncodedCA()
if err != nil {
return errors.Wrap(err, "Error reading the ca data")
}
args := []string{
"set",
"kubernetes.api-server=" + apiServer,
"kubernetes.cluster-certificate=" + b64CA,
"kubernetes.cluster-dns-ip=" + dns,
"kubernetes.bootstrap-token=" + token,
"kubernetes.authentication-mode=tls",
"kubernetes.standalone-mode=false",
}
kubeletTlsConfig := readKubeletTlsConfig(&RealFileReader{})
if kubeletTlsConfig != nil {
args = append(args, "settings.kubernetes.server-certificate="+kubeletTlsConfig.KubeletServingCert)
args = append(args, "settings.kubernetes.server-key="+kubeletTlsConfig.KubeletServingPrivateKey)
}
cmd = exec.Command(utils.ApiclientBinary, args...)
if err := cmd.Run(); err != nil {
return errors.Wrapf(err, "Error running command: %v", cmd)
}
err = waitForActiveKubelet()
if err != nil {
return errors.Wrap(err, "Error waiting for kubelet to come up")
}
if isEtcdExternal, err := isClusterWithExternalEtcd(kubeconfigPath); err != nil {
return err
} else if !isEtcdExternal {
if err := joinLocalEtcd(); err != nil {
return err
}
}
// Migrate all static pods from this host-container to the bottlerocket host using the apiclient
// now that etcd manifest is also created
podDefinitions, err := utils.EnableStaticPods("/etc/kubernetes/manifests")
if err != nil {
return errors.Wrap(err, "Error enabling static pods")
}
// Now that etcd is up and running, check for other pod liveness
err = utils.WaitForPods(podDefinitions)
if err != nil {
return errors.Wrapf(err, "Error waiting for static pods to be up")
}
// Wait for Kubernetes API server to come up.
localApiServerReadinessEndpoint, err := getLocalApiServerReadinessEndpoint()
if err != nil {
fmt.Printf("unable to get local apiserver readiness endpoint, falling back to localhost:6443. caused by: %s", err.Error())
localApiServerReadinessEndpoint = "https://localhost:6443/healthz"
}
err = utils.WaitFor200(localApiServerReadinessEndpoint, 30*time.Second)
if err != nil {
return err
}
err = utils.WaitFor200(string(apiServer)+"/healthz", 30*time.Second)
if err != nil {
return err
}
// finish kubeadm
cmd = exec.Command(kubeadmBinary, utils.LogVerbosity, "join", "--skip-phases", "preflight,control-plane-prepare,kubelet-start,control-plane-join/etcd",
"--config", kubeadmJoinFile)
if err := cmd.Run(); err != nil {
return errors.Wrapf(err, "Error running command: %v", cmd)
}
if ebsInitControl != nil {
checkEbsInit(ebsInitControl)
}
return nil
}
func joinLocalEtcd() error {
// Get kubeadm to write out the manifest for etcd.
// It will wait for etcd to start, which won't succeed because we need to set the static-pods in the BR api.
cmd := exec.Command(kubeadmBinary, utils.LogVerbosity, "join", "phase", "control-plane-join", "etcd", "--config", kubeadmJoinFile)
cmd.Stdout = os.Stdout
if err := cmd.Start(); err != nil {
return errors.Wrapf(err, "Error running command: %v", cmd)
}
etcdCheckFiles := []string{"/etc/kubernetes/manifests/etcd.yaml"}
if err := utils.KillCmdAfterFilesGeneration(cmd, etcdCheckFiles); err != nil {
return errors.Wrap(err, "Error waiting for etcd manifest files")
}
return nil
}
| 148 |
eks-anywhere-build-tooling | aws | Go | package kubeadm
import (
"fmt"
"os"
"os/exec"
"github.com/eks-anywhere-build-tooling/aws/bottlerocket-bootstrap/pkg/utils"
"github.com/pkg/errors"
)
type kubeadm struct {
userData *utils.UserData
}
func New(userData *utils.UserData) *kubeadm {
return &kubeadm{userData: userData}
}
func (k *kubeadm) InitializeDirectories() error {
fmt.Println("Initializing directories")
err := os.MkdirAll("/.bottlerocket/rootfs/var/lib/kubeadm/pki", 0o640)
if err != nil {
return errors.Wrap(err, "error creating directory")
}
// Force symlink creation with cmd. sdk calls fail if the symlink dir exists
cmd := exec.Command("bash", "-c", "ln -sfn /.bottlerocket/rootfs/var/lib/kubeadm /var/lib")
if err := cmd.Run(); err != nil {
return errors.Wrapf(err, "error running command: %v", cmd)
}
cmd = exec.Command("bash", "-c", "ln -sfn /.bottlerocket/rootfs/var/lib/kubeadm /etc/kubernetes")
if err := cmd.Run(); err != nil {
return errors.Wrapf(err, "error running command: %v", cmd)
}
return nil
}
func (k *kubeadm) RunCmd() error {
// Take different directions based on runCmd on node's user data
switch k.userData.RunCmd {
case "ControlPlaneInit":
fmt.Println("Running controlplane init bootstrap sequence")
if err := controlPlaneInit(); err != nil {
return errors.Wrapf(err, "error initing controlplane")
}
case "ControlPlaneJoin":
fmt.Println("Running controlplane join sequence")
if err := controlPlaneJoin(); err != nil {
return errors.Wrapf(err, "error joining controlplane")
}
case "WorkerJoin":
fmt.Println("Running worker join sequence")
if err := workerJoin(); err != nil {
return errors.Wrapf(err, "error joining as worker")
}
}
return nil
}
| 60 |
eks-anywhere-build-tooling | aws | Go | package kubeadm
import (
"context"
"encoding/base64"
"fmt"
"io/fs"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"strings"
"time"
"github.com/eks-anywhere-build-tooling/aws/bottlerocket-bootstrap/pkg/files"
"github.com/eks-anywhere-build-tooling/aws/bottlerocket-bootstrap/pkg/utils"
"github.com/pkg/errors"
"sigs.k8s.io/yaml"
)
const (
apiServerManifestPath = "/.bottlerocket/rootfs/etc/kubernetes/manifests/kube-apiserver"
ebsInitMarker = "/tmp/run-ebs-init"
)
func getBootstrapToken() (string, error) {
token, err := exec.Command(kubeadmBinary, "token", "list", "-o", "jsonpath=\"{.token}\"").Output()
if err != nil {
return "", errors.Wrap(err, "Error getting token")
}
// Remove leading and ending double quotes
// tokens do not contain quotes in the middle
replacedToken := strings.ReplaceAll(string(token), "\"", "")
return replacedToken, nil
}
func getEncodedCA() (string, error) {
caFileData, err := ioutil.ReadFile("/etc/kubernetes/pki/ca.crt")
if err != nil {
return "", errors.Wrap(err, "Error reading the ca data")
}
return base64.StdEncoding.EncodeToString(caFileData), nil
}
func setHostName(filepath string) error {
fmt.Println("Setting hostname in config files")
hostname, err := os.Hostname()
if err != nil {
return errors.Wrap(err, "Error getting hostname")
}
fileData, err := ioutil.ReadFile(filepath)
if err != nil {
return errors.Wrap(err, "Error reading kubeadm file")
}
fileDataStr := string(fileData)
fileDataStr = strings.ReplaceAll(fileDataStr, "{{ ds.meta_data.hostname }}", hostname)
// Write the file back
if err := files.Write(filepath, []byte(fileDataStr), 0o640); err != nil {
return errors.Wrap(err, "Error writing file")
}
fmt.Println("Wrote config file back to kubeadm")
fmt.Println(fileDataStr)
return nil
}
func getDNS(path string) (string, error) {
dns, err := exec.Command(kubectl, "--kubeconfig", path, "get", "svc", "kube-dns", "-n", "kube-system", "-o", "jsonpath='{..clusterIP}'").Output()
if err != nil {
return "", errors.Wrap(err, "Error getting api server")
}
// Remove leading and ending double quotes
// dns ip doesnt have quotes in the middle
replacedDns := strings.ReplaceAll(string(dns), "'", "")
return replacedDns, nil
}
// TODO: ioutil.ReadFile on the kubelet config fails saying no file found,
// but awk and cat command pass. Really weird error. Must try and debug this out
// Possibly we kill the kubeadm command prematurely because we just stat the file
// while the file is being written?
func getDNSFromJoinConfig(path string) (string, error) {
data, err := ioutil.ReadFile(path)
if err != nil {
return "", err
}
fmt.Println(string(data))
dns, err := exec.Command("bash", "-c", "awk '/clusterDNS:/ { getline; print $2 }' "+path).CombinedOutput()
if err != nil {
return "", errors.Wrap(err, "Error getting api server")
}
return strings.TrimSuffix(string(dns), "\n"), nil
}
func getBootstrapFromJoinConfig(path string) (string, string, error) {
data, err := ioutil.ReadFile(path)
if err != nil {
return "", "", errors.Wrap(err, "Error reading kubeadm join config file")
}
joinConfig := strings.TrimPrefix(string(data), "---")
kubeadmJoinData, err := unmarshalIntoMap([]byte(joinConfig))
if err != nil {
return "", "", errors.Wrap(err, "failed unmarshalling yaml kubeadm join config to interfaces")
}
discovery := kubeadmJoinData["discovery"].(map[string]interface{})
bootstrapToken := discovery["bootstrapToken"].(map[string]interface{})
serverEndpoint := bootstrapToken["apiServerEndpoint"].(string)
token := bootstrapToken["token"].(string)
return "https://" + serverEndpoint, token, nil
}
func getLocalApiServerReadinessEndpoint() (string, error) {
data, err := ioutil.ReadFile(apiServerManifestPath)
if err != nil {
return "", errors.Wrap(err, "Error reading ApiServer manifest file")
}
podDef, err := utils.UnmarshalPodDefinition(data)
if err != nil {
return "", errors.Wrap(err, "Error parsing pod def from manifest")
}
for _, container := range podDef.Spec.Containers {
// Validate if readiness probe exists on the definition
if container.ReadinessProbe != nil {
readinessProbeHandler := container.ReadinessProbe.HTTPGet
url := fmt.Sprintf("%s://%s:%d%s", readinessProbeHandler.Scheme, readinessProbeHandler.Host, readinessProbeHandler.Port.IntVal, readinessProbeHandler.Path)
return url, nil
}
}
return "", errors.New("Cannot find readiness probe exists on pod definition")
}
func isClusterWithExternalEtcd(kubeconfigPath string) (bool, error) {
clusterConfiguration, err := getClusterConfigurationFromCluster(kubeconfigPath)
if err != nil {
return false, err
}
return isExternalEtcd(clusterConfiguration)
}
func getClusterConfigurationFromCluster(kubeconfigPath string) ([]byte, error) {
clusterConfiguration, err := exec.Command(kubectl, "--kubeconfig", kubeconfigPath, "-n", "kube-system", "get", "cm", "kubeadm-config", "-o", "jsonpath='{..data.ClusterConfiguration}'").Output()
if err != nil {
return nil, errors.Wrap(err, "failed getting kubeadm-config configMap")
}
return clusterConfiguration, nil
}
func isExternalEtcd(clusterConfiguration []byte) (bool, error) {
config, err := unmarshalIntoMap(clusterConfiguration)
if err != nil {
return false, errors.Wrap(err, "error unmarshalling ClusterConfiguration")
}
etcd := config["etcd"].(map[string]interface{})
return etcd["external"] != nil, nil
}
func unmarshalIntoMap(content []byte) (map[string]interface{}, error) {
var parsedMap map[string]interface{}
content = []byte(strings.Trim(string(content), "'"))
err := yaml.Unmarshal(content, &parsedMap)
if err != nil {
return nil, errors.Wrap(err, "error unmarshalling into map of empty interface")
}
return parsedMap, err
}
type EbsInitControl struct {
Cancel context.CancelFunc
OkChan chan bool
Timeout <-chan time.Time
}
// startEbsInit starts the ebs-init goroutine in the background
// if marker file is present. Currenlty ebs-init is best-effort
// and if it fails it won't prevent the instance from bootstrapping.
// A 2 minutes timeout is added so that instance bootstrap time is
// not inflated.
func startEbsInit() *EbsInitControl {
if _, err := os.Stat(ebsInitMarker); err == nil {
okChan := make(chan bool)
ctx, cancel := context.WithCancel(context.Background())
fmt.Printf("Starting ebs-init \n")
ebsInitControl := &EbsInitControl{
Timeout: time.After(2 * time.Minute),
Cancel: cancel,
OkChan: okChan,
}
go func(ctx context.Context, okChan chan bool) {
for {
select {
case <-ctx.Done():
return
default:
readFiles()
okChan <- true
return
}
}
}(ctx, okChan)
return ebsInitControl
} else {
fmt.Printf("Skipping ebs-init \n")
return nil
}
}
// readFiles walks the filesystem tree and reads all regular files
func readFiles() {
root := "/.bottlerocket/rootfs/"
err := filepath.WalkDir(root, walkDirFunc)
if err != nil {
message := fmt.Errorf("failed reading files %w", err)
fmt.Printf("%s\n", message)
}
fmt.Printf("All files read \n")
}
// walkDirFunc is passed to filepath.WalkDir, it does some validations
// and skips non existing (or deleted/renamed) files and dirs as well as
// some special dirs
func walkDirFunc(path string, dirEntry fs.DirEntry, err error) error {
if dirEntry == nil {
return filepath.SkipDir
}
if dirEntry.IsDir() {
// skip special dirs
if dirEntry.Name() == "proc" || dirEntry.Name() == "sys" || dirEntry.Name() == "run" {
return filepath.SkipDir
}
} else {
entryInfo, entryInfoError := dirEntry.Info()
// check if file exists and is regular
if entryInfoError == nil && entryInfo.Mode().IsRegular() {
ioutil.ReadFile(path)
}
}
return nil
}
// KubeletTlsConfig is a struct that holds cert and private key
type KubeletTlsConfig struct {
KubeletServingCert string
KubeletServingPrivateKey string
}
// readKubeletTlsConfig loads kubelet serving cert and private key from files
func readKubeletTlsConfig(reader FileReader) *KubeletTlsConfig {
kubeletServingCertFile := "/.bottlerocket/rootfs/var/lib/kubeadm/pki/kubelet-serving.crt"
kubeletServingPrivateKeyFile := "/.bottlerocket/rootfs/var/lib/kubeadm/pki/kubelet-serving.key"
kubeletTlsConfig := &KubeletTlsConfig{}
kubeletServingCertContents, err := readAndEncodeFile(kubeletServingCertFile, reader)
if err != nil {
message := fmt.Errorf("skipping Kubelet TLS configuration: %s %w", kubeletServingCertFile, err)
fmt.Printf("%s\n", message)
return nil
}
kubeletServingPrivateKeyContents, err := readAndEncodeFile(kubeletServingPrivateKeyFile, reader)
if err != nil {
message := fmt.Errorf("skipping Kubelet TLS configuration: %s %w", kubeletServingPrivateKeyFile, err)
fmt.Printf("%s\n", message)
return nil
}
kubeletTlsConfig.KubeletServingCert = kubeletServingCertContents
kubeletTlsConfig.KubeletServingPrivateKey = kubeletServingPrivateKeyContents
fmt.Println("Kubelet TLS configuration available")
return kubeletTlsConfig
}
// FileReader is an interface that wraps the ReadFile function.
type FileReader interface {
ReadFile(filename string) ([]byte, error)
}
// RealFileReader is a struct that implements the FileReader interface
// using the ioutil.ReadFile function.
type RealFileReader struct{}
// ReadFile reads the contents of a file using ioutil.ReadFile.
func (r RealFileReader) ReadFile(filename string) ([]byte, error) {
return ioutil.ReadFile(filename)
}
// readAndEncodeFile reads the contents of a file and encodes them as base64 string
func readAndEncodeFile(filePath string, reader FileReader) (string, error) {
contents, err := reader.ReadFile(filePath)
if err == nil {
if string(contents) == "" {
return "", errors.New("empty contents")
}
return base64.StdEncoding.EncodeToString(contents), nil
}
return "", err
}
// isEmpty checks if passed sting is empty
func isEmpty(str string) bool {
return len(str) == 0
}
| 317 |
eks-anywhere-build-tooling | aws | Go | package kubeadm
import (
"os"
"testing"
"github.com/google/go-cmp/cmp"
)
const localEtcdClusterConf = `'apiServer:
certSANs:
- localhost
- 127.0.0.1
extraArgs:
authorization-mode: Node,RBAC
runtime-config: ""
timeoutForControlPlane: 4m0s
apiVersion: kubeadm.k8s.io/v1beta2
certificatesDir: /etc/kubernetes/pki
clusterName: eksa-test-eks-a-cluster
controlPlaneEndpoint: eksa-test-eks-a-cluster-control-plane:6443
controllerManager:
extraArgs:
enable-hostpath-provisioner: "true"
dns:
imageRepository: public.ecr.aws/eks-distro/coredns
imageTag: v1.8.3-eks-1-20-5
type: CoreDNS
etcd:
local:
dataDir: /var/lib/etcd
imageRepository: public.ecr.aws/eks-distro/etcd-io
imageTag: v3.4.15-eks-1-20-5
featureGates:
IPv6DualStack: true
imageRepository: public.ecr.aws/eks-distro/kubernetes
kind: ClusterConfiguration
kubernetesVersion: v1.20.7-eks-1-20-5
networking:
dnsDomain: cluster.local
podSubnet: 10.244.0.0/16
serviceSubnet: 10.96.0.0/16
scheduler: {}'`
const externalEtcdClusterConf = `'apiServer:
extraArgs:
cloud-provider: external
timeoutForControlPlane: 4m0s
apiVersion: kubeadm.k8s.io/v1beta2
certificatesDir: /var/lib/kubeadm/pki
clusterName: eksa-test
controlPlaneEndpoint: 198.18.210.144:6443
controllerManager:
extraArgs:
cloud-provider: external
extraVolumes:
- hostPath: /var/lib/kubeadm/controller-manager.conf
mountPath: /etc/kubernetes/controller-manager.conf
name: kubeconfig
pathType: File
readOnly: true
dns:
imageRepository: public.ecr.aws/eks-distro/coredns
imageTag: v1.8.3-eks-1-20-5
type: CoreDNS
etcd:
external:
caFile: /var/lib/kubeadm/pki/etcd/ca.crt
certFile: /var/lib/kubeadm/pki/server-etcd-client.crt
endpoints:
- https://198.18.138.154:2379
- https://198.18.138.155:2379
- https://198.18.69.78:2379
keyFile: /var/lib/kubeadm/pki/apiserver-etcd-client.key
imageRepository: public.ecr.aws/eks-distro/kubernetes
kind: ClusterConfiguration
kubernetesVersion: v1.20.7-eks-1-20-5
networking:
dnsDomain: cluster.local
podSubnet: 192.168.0.0/16
serviceSubnet: 10.96.0.0/12
scheduler:
extraVolumes:
- hostPath: /var/lib/kubeadm/scheduler.conf
mountPath: /etc/kubernetes/scheduler.conf
name: kubeconfig
pathType: File
readOnly: true'`
func TestIsExternalEtcd(t *testing.T) {
tests := []struct {
testName string
clusterConfiguration []byte
wantExternal bool
}{
{
testName: "local",
clusterConfiguration: []byte(localEtcdClusterConf),
wantExternal: false,
},
{
testName: "external",
clusterConfiguration: []byte(externalEtcdClusterConf),
wantExternal: true,
},
}
for _, tt := range tests {
t.Run(tt.testName, func(t *testing.T) {
gotExternal, err := isExternalEtcd(tt.clusterConfiguration)
if err != nil {
t.Fatalf("isExternalEtcd() -> err = %v, want err = nil", err)
}
if gotExternal != tt.wantExternal {
t.Fatalf("isExternalEtcd() -> gotExternal = %t, wantExternal = %t", gotExternal, tt.wantExternal)
}
})
}
}
type mockFileReader func(filename string) ([]byte, error)
func (m mockFileReader) ReadFile(filename string) ([]byte, error) {
return m(filename)
}
func TestReadKubeletTlsConfig(t *testing.T) {
tests := []struct {
testName string
expectedKubeletTlsConfig *KubeletTlsConfig
mockReader func(t *testing.T) FileReader
}{
{
testName: "skip config cert file missing",
expectedKubeletTlsConfig: nil,
mockReader: func(t *testing.T) FileReader {
return mockFileReader(func(filename string) ([]byte, error) {
t.Helper()
if filename == "/.bottlerocket/rootfs/var/lib/kubeadm/pki/kubelet-serving.crt" {
return nil, os.ErrNotExist
} else {
return []byte("mock-key"), nil
}
})
},
},
{
testName: "skip config key file missing",
expectedKubeletTlsConfig: nil,
mockReader: func(t *testing.T) FileReader {
return mockFileReader(func(filename string) ([]byte, error) {
t.Helper()
if filename == "/.bottlerocket/rootfs/var/lib/kubeadm/pki/kubelet-serving.key" {
return nil, os.ErrNotExist
} else {
return []byte("mock-cert"), nil
}
})
},
},
{
testName: "skip config cert file empty contents",
expectedKubeletTlsConfig: nil,
mockReader: func(t *testing.T) FileReader {
return mockFileReader(func(filename string) ([]byte, error) {
t.Helper()
if filename == "/.bottlerocket/rootfs/var/lib/kubeadm/pki/kubelet-serving.crt" {
return []byte{}, nil
} else {
return []byte("mock-key"), nil
}
})
},
},
{
testName: "skip config key file empty contents",
expectedKubeletTlsConfig: nil,
mockReader: func(t *testing.T) FileReader {
return mockFileReader(func(filename string) ([]byte, error) {
t.Helper()
if filename == "/.bottlerocket/rootfs/var/lib/kubeadm/pki/kubelet-serving.key" {
return []byte{}, nil
} else {
return []byte("mock-cert"), nil
}
})
},
},
{
testName: "success files present with contents",
expectedKubeletTlsConfig: &KubeletTlsConfig{KubeletServingCert: "bW9jay1jcnQ=", KubeletServingPrivateKey: "bW9jay1rZXk="},
mockReader: func(t *testing.T) FileReader {
return mockFileReader(func(filename string) ([]byte, error) {
t.Helper()
switch filename {
case "/.bottlerocket/rootfs/var/lib/kubeadm/pki/kubelet-serving.crt":
return []byte("mock-crt"), nil
case "/.bottlerocket/rootfs/var/lib/kubeadm/pki/kubelet-serving.key":
return []byte("mock-key"), nil
}
return nil, nil
})
},
},
}
for _, tt := range tests {
t.Run(tt.testName, func(t *testing.T) {
kubeletTlsConfig := readKubeletTlsConfig(tt.mockReader(t))
if !cmp.Equal(kubeletTlsConfig, tt.expectedKubeletTlsConfig) {
t.Fatalf("%v different from expected %v", kubeletTlsConfig, tt.expectedKubeletTlsConfig)
}
})
}
}
| 218 |
eks-anywhere-build-tooling | aws | Go | package kubeadm
import (
"fmt"
"os/exec"
"time"
"github.com/eks-anywhere-build-tooling/aws/bottlerocket-bootstrap/pkg/utils"
"github.com/pkg/errors"
)
func waitForKubelet() error {
err := utils.WaitForSystemdService(utils.KubeletService, 90*time.Second)
if err != nil {
return err
}
return nil
}
// waitForActiveKubelet checks for the kubelet status and then sleeps for 20 seconds and
// checks again. We wait for 20 seconds to check the status just to make sure the kubelet
// hasn't crashed for some reason. There can be other reasons kubelet isn't working as expected
// but has also not crashed.
func waitForActiveKubelet() error {
err := waitForKubelet()
if err != nil {
return errors.Wrap(err, "Error waiting for kubelet to come up")
}
// Wait for 20 seconds and check for kubelet status again
// to check if the service has not crashed
time.Sleep(20 * time.Second)
err = waitForKubelet()
if err != nil {
return errors.Wrap(err, "Error waiting for kubelet to come up")
}
return nil
}
func killCmdAfterJoinFilesGeneration(cmd *exec.Cmd) error {
checkFiles := []string{
"/var/lib/kubelet/config.yaml",
"/var/lib/kubelet/kubeadm-flags.env",
"/var/lib/kubeadm/pki/ca.crt",
}
return utils.KillCmdAfterFilesGeneration(cmd, checkFiles)
}
// checkEbsInit checks the execution of ebs-init goroutine,
// the goroutine will be stopped if timeout is reached
func checkEbsInit(ctrl *EbsInitControl) {
select {
case <-ctrl.Timeout:
ctrl.Cancel()
fmt.Printf("Killing ebs-init, timeout reached \n")
return
case <-ctrl.OkChan:
fmt.Printf("Finished ebs-init \n")
return
}
}
| 63 |
eks-anywhere-build-tooling | aws | Go | package kubeadm
import (
"fmt"
"os"
"os/exec"
"github.com/eks-anywhere-build-tooling/aws/bottlerocket-bootstrap/pkg/utils"
"github.com/pkg/errors"
)
const (
kubeadmJoinFile = "/tmp/kubeadm-join-config.yaml"
)
func workerJoin() error {
err := setHostName(kubeadmJoinFile)
if err != nil {
return errors.Wrap(err, "Error replacing hostname on kubeadm")
}
cmd := exec.Command(kubeadmBinary, utils.LogVerbosity, "join", "phase", "kubelet-start", "--config", kubeadmJoinFile)
cmd.Stdout = os.Stdout
if err := cmd.Start(); err != nil {
return errors.Wrapf(err, "Error running command: %v", cmd)
}
err = killCmdAfterJoinFilesGeneration(cmd)
if err != nil {
return errors.Wrap(err, "Error waiting for worker join files")
}
apiServer, token, err := getBootstrapFromJoinConfig(kubeadmJoinFile)
if err != nil {
return errors.Wrap(err, "Error getting api server and token from kubeadm join config")
}
b64CA, err := getEncodedCA()
if err != nil {
return errors.Wrap(err, "Error reading the ca data")
}
dns, err := getDNSFromJoinConfig("/var/lib/kubelet/config.yaml")
if err != nil {
return errors.Wrap(err, "Error getting dns from kubelet config")
}
fmt.Println(dns)
cmd = exec.Command(utils.ApiclientBinary, "set",
"kubernetes.api-server="+apiServer,
"kubernetes.cluster-certificate="+b64CA,
"kubernetes.cluster-dns-ip="+string(dns),
"kubernetes.bootstrap-token="+token,
"kubernetes.authentication-mode=tls",
"kubernetes.standalone-mode=false")
out, err := cmd.CombinedOutput()
if err != nil {
return errors.Wrapf(err, "Error running command: %v, output: %s\n", cmd, string(out))
}
fmt.Printf("Ran apiclient set call: %v\n", string(out))
// wait for kubelet to come up before killing the bootstrap container
err = waitForActiveKubelet()
if err != nil {
fmt.Printf("Error waiting for kubelet: %v", err)
return err
}
return nil
}
| 68 |
eks-anywhere-build-tooling | aws | Go | package main
import (
"flag"
"fmt"
"github.com/eks-anywhere-build-tooling/aws/bottlerocket-bootstrap/pkg/providers/snow/system"
"github.com/eks-anywhere-build-tooling/aws/bottlerocket-bootstrap/pkg/utils"
)
func main() {
utils.LogVerbosity = fmt.Sprintf("-v%s", *flag.String("v", "9", "Verbosity of logs"))
system.NewSnow().Bootstrap()
}
| 15 |
eks-anywhere-build-tooling | aws | Go | //go:generate ../../../../hack/tools/bin/mockgen -destination ./mocks/apiclient_mock.go -package mocks . APIClient
//go:generate ../../../../hack/tools/bin/mockgen -destination ./mocks/filesystem_mock.go -package mocks . FileSystem
package system
import (
"fmt"
"os"
"github.com/eks-anywhere-build-tooling/aws/bottlerocket-bootstrap/pkg/executables"
)
type APIClient interface {
SetKubernetesCloudProvider(cloudProvider string) error
SetKubernetesNodeIP(ip string) error
SetKubernetesProviderID(id string) error
Set(setting *executables.APISetting) error
Reboot() error
}
type FileSystem interface {
MountVolume(device, dir string) error
Partition(device string) error
}
type Snow struct {
api APIClient
fs FileSystem
}
func NewSnow() *Snow {
return &Snow{
api: executables.NewAPIClient(),
fs: executables.NewFileSystem(),
}
}
func (s *Snow) Bootstrap() {
if err := s.configureKubernetesSettings(); err != nil {
fmt.Printf("Error configuring Kubernetes settings: %v\n", err)
os.Exit(1)
}
if err := s.configureKernelSettings(); err != nil {
fmt.Printf("Error configuring kernel settings: %v\n", err)
os.Exit(1)
}
if err := configureDNI(); err != nil {
fmt.Printf("Error configuring snow DNI: %v\n", err)
os.Exit(1)
}
if err := s.mountContainerdVolume(); err != nil {
fmt.Printf("Error configuring container volume: %v\n", err)
os.Exit(1)
}
if err := s.rebootInstanceIfNeeded(); err != nil {
fmt.Printf("Error rebooting instance: %v\n", err)
os.Exit(1)
}
fmt.Println("SUCCESS: Snow bootstrap tasks finished.")
os.Exit(0)
}
| 67 |
eks-anywhere-build-tooling | aws | Go | package system
import (
"github.com/eks-anywhere-build-tooling/aws/bottlerocket-bootstrap/pkg/executables"
)
const (
// Temporary hardcoded kernel config values for beta.
// In the future the kernel config will be exposed for eks-a users to customize.
maxSocketBufferSize = "8388608"
kernelCorePattern = "/var/corefile/core.%e.%p.%h.%t"
)
func (s *Snow) configureKernelSettings() error {
kernelSetting := &executables.APISetting{
Kubernetes: &executables.Kubernetes{
AllowedUnsafeSysctls: []string{
"net.ipv4.tcp_mtu_probing",
},
},
Kernel: &executables.Kernel{
Sysctl: map[string]string{
"net.core.rmem_max": maxSocketBufferSize,
"net.core.wmem_max": maxSocketBufferSize,
"kernel.core_pattern": kernelCorePattern,
},
},
}
return s.api.Set(kernelSetting)
}
| 32 |
eks-anywhere-build-tooling | aws | Go | package system
import (
"fmt"
"os"
"path/filepath"
"github.com/eks-anywhere-build-tooling/aws/bottlerocket-bootstrap/pkg/files"
"github.com/pkg/errors"
)
func (s *Snow) configureKubernetesSettings() error {
if err := s.setCloudProvider(); err != nil {
return errors.Wrap(err, "Error setting K8s cloud provider")
}
if err := s.setProviderID(); err != nil {
return errors.Wrap(err, "Error setting K8s provider id")
}
if err := s.setNodeIP(); err != nil {
return errors.Wrap(err, "Error setting K8s node ip")
}
return nil
}
func (s *Snow) setCloudProvider() error {
return s.api.SetKubernetesCloudProvider("")
}
func (s *Snow) setNodeIP() error {
nodeIPConfiguredPath := filepath.Join(bootstrapContainerPath, "nodeip.configured")
// only set K8s node ip once after reboot
if !files.PathExists(rebootedPath) || files.PathExists(nodeIPConfiguredPath) {
return nil
}
ip, err := currentIP()
if err != nil {
return errors.Wrap(err, "Error getting current ip address")
}
if err := s.api.SetKubernetesNodeIP(ip); err != nil {
return err
}
// Write node ip configured file to make sure the node ip is only configured once
if _, err := os.Create(nodeIPConfiguredPath); err != nil {
return errors.Wrapf(err, "Error writing %s file", nodeIPConfiguredPath)
}
return nil
}
func (s *Snow) setProviderID() error {
id, err := instanceID()
if err != nil {
errors.Wrap(err, "error getting instance id")
}
ip, err := deviceIP()
if err != nil {
errors.Wrap(err, "error getting device ip")
}
return s.api.SetKubernetesProviderID(fmt.Sprintf("aws-snow:///%s/%s", ip, id))
}
func instanceID() (string, error) {
url := fmt.Sprintf("http://%s/latest/meta-data/instance-id", metadataServiceIP)
body, err := httpGet(url)
if err != nil {
return "", errors.Wrap(err, "error requesting instance id through http")
}
return string(body), nil
}
| 78 |
eks-anywhere-build-tooling | aws | Go | package system
import (
"bufio"
_ "embed"
"fmt"
"io/ioutil"
"net/http"
"os"
"path/filepath"
"syscall"
"github.com/pkg/errors"
"github.com/vishvananda/netlink"
"gopkg.in/yaml.v2"
"github.com/eks-anywhere-build-tooling/aws/bottlerocket-bootstrap/pkg/files"
"github.com/eks-anywhere-build-tooling/aws/bottlerocket-bootstrap/pkg/utils"
)
//go:embed config/net.toml
var netConfig string
const (
rootfs = "/.bottlerocket/rootfs"
metadataServiceIP = "169.254.169.254"
networkFilePath = "/tmp/network.yaml"
)
var (
netConfigPath = filepath.Join(rootfs, "/var/lib/netdog/net.toml")
currentIPPath = filepath.Join(rootfs, "/var/lib/netdog/current_ip")
)
type Network struct {
DeviceIP string `yaml:"deviceIP"`
DniCount int `yaml:"dniCount"`
Static []StaticIP `yaml:"static,omitempty"`
}
type StaticIP struct {
Address string `yaml:"address"`
Gateway string `yaml:"gateway"`
Primary bool `yaml:"primary,omitempty"`
}
type NetworkMapping struct {
DNI string
*StaticIP
}
func configureDNI() error {
if files.PathExists(netConfigPath) {
return nil
}
instanceIP, err := instanceIP()
if err != nil {
return errors.Wrap(err, "error getting local instance ip")
}
defaultGateway, err := defaultGateway()
if err != nil {
return errors.Wrap(err, "error getting default gateway")
}
network, err := networkMapping()
if err != nil {
return errors.Wrap(err, "error generating network mapping")
}
data := map[string]interface{}{
"network": network,
"instanceIP": instanceIP,
"defaultGateway": defaultGateway,
"metadataServiceIP": metadataServiceIP,
}
b, err := GenerateNetworkTemplate(data)
if err != nil {
return errors.Wrap(err, "error generating network template")
}
if err := files.Write(netConfigPath, b, 0o640); err != nil {
return errors.Wrapf(err, "error writing network configuration to %s", netConfigPath)
}
return nil
}
func GenerateNetworkTemplate(data map[string]interface{}) ([]byte, error) {
return files.ExecuteTemplate(netConfig, data)
}
// networkMapping returns a single network mapping of DNI and optional static IP.
// currently only support single primary DNI and static IP configuration.
func networkMapping() ([]NetworkMapping, error) {
dniList, err := dniList()
if err != nil {
return nil, errors.Wrap(err, "error getting DNI list")
}
network, err := parseNetworkFile()
if err != nil {
return nil, errors.Wrap(err, "error parsing network file")
}
if len(dniList) != network.DniCount {
return nil, errors.Wrap(err, "the number of DNI found does not match the dniCount in the network file")
}
if len(network.Static) > 0 && len(network.Static) < network.DniCount {
return nil, errors.Wrap(err, "mix of using DHCP and static IP is not supported")
}
m := make([]NetworkMapping, 0, network.DniCount)
for i, dni := range dniList {
n := NetworkMapping{
DNI: dni,
}
if len(network.Static) > 0 {
n.StaticIP = &network.Static[i]
}
m = append(m, n)
}
return m, nil
}
func parseNetworkFile() (*Network, error) {
userData, err := utils.ResolveBootstrapContainerUserData()
if err != nil {
return nil, errors.Wrap(err, "error resolving user data")
}
for _, file := range userData.WriteFiles {
if file.Path == networkFilePath {
network := &Network{}
err := yaml.Unmarshal([]byte(file.Content), network)
if err != nil {
return nil, errors.Wrap(err, "error unmarshalling network file content")
}
return network, nil
}
}
return nil, nil
}
func dniList() ([]string, error) {
devices, err := netlink.LinkList()
if err != nil {
return nil, errors.Wrap(err, "error getting the device list of links")
}
dnis := []string{}
for _, device := range devices {
name := device.Attrs().Name
if name != "lo" && name != "eth0" {
dnis = append(dnis, name)
}
}
return dnis, nil
}
func defaultGateway() (string, error) {
routes, err := netlink.RouteList(nil, syscall.AF_INET)
if err != nil {
return "", errors.Wrap(err, "error getting the route list")
}
for _, route := range routes {
if route.Dst == nil {
return route.Gw.String(), nil
}
}
return "", errors.New("default gateway not found")
}
func instanceIP() (string, error) {
url := fmt.Sprintf("http://%s/latest/meta-data/local-ipv4", metadataServiceIP)
body, err := httpGet(url)
if err != nil {
return "", errors.Wrap(err, "error requesting instance ip through http")
}
return string(body), nil
}
func currentIP() (string, error) {
f, err := os.Open(currentIPPath)
if err != nil {
return "", err
}
defer f.Close()
scanner := bufio.NewScanner(f)
for scanner.Scan() {
return scanner.Text(), nil
}
return "", nil
}
func deviceIP() (string, error) {
network, err := parseNetworkFile()
if err != nil {
return "", errors.Wrap(err, "error parsing network file")
}
return network.DeviceIP, nil
}
func httpGet(url string) (string, error) {
resp, err := http.Get(url)
if err != nil {
return "", errors.Wrapf(err, "error sending http GET request to %s", url)
}
if resp.StatusCode != http.StatusOK {
return "", errors.Errorf("requesting %s returns status code %d", url, resp.StatusCode)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", errors.Wrap(err, "error reading response body")
}
return string(body), nil
}
| 231 |
eks-anywhere-build-tooling | aws | Go | package system_test
import (
"testing"
. "github.com/onsi/gomega"
"github.com/eks-anywhere-build-tooling/aws/bottlerocket-bootstrap/pkg/providers/snow/system"
)
var networkConfigTest = []struct {
name string
data map[string]interface{}
wantConfig string
}{
{
name: "with static ip",
data: map[string]interface{}{
"network": []system.NetworkMapping{
{
DNI: "dni0",
StaticIP: &system.StaticIP{
Address: "address0",
Gateway: "gateway0",
Primary: true,
},
},
{
DNI: "dni1",
StaticIP: &system.StaticIP{
Address: "address1",
Gateway: "gateway1",
Primary: false,
},
},
{
DNI: "dni2",
StaticIP: &system.StaticIP{
Address: "address2",
Gateway: "gateway2",
},
},
},
"instanceIP": "instanceip",
"defaultGateway": "defaultgateway",
"metadataServiceIP": "metaserverip",
},
wantConfig: `version = 2
[dni0]
primary = true
[dni0.static4]
addresses = ["address0"]
[[dni0.route]]
to = "default"
via = "gateway0"
[dni1.static4]
addresses = ["address1"]
[[dni1.route]]
to = "default"
via = "gateway1"
[dni2.static4]
addresses = ["address2"]
[[dni2.route]]
to = "default"
via = "gateway2"
[eth0.static4]
addresses = ["instanceip/25"]
[[eth0.route]]
to = "metaserverip/32"
from = "instanceip"
via = "defaultgateway"
`,
},
{
name: "with dhcp",
data: map[string]interface{}{
"network": []system.NetworkMapping{
{
DNI: "dni0",
},
{
DNI: "dni1",
},
{
DNI: "dni2",
},
},
"instanceIP": "instanceip",
"defaultGateway": "defaultgateway",
"metadataServiceIP": "metaserverip",
},
wantConfig: `version = 2
[dni0]
dhcp4 = true
primary = true
[dni1]
dhcp4 = true
[dni2]
dhcp4 = true
[eth0.static4]
addresses = ["instanceip/25"]
[[eth0.route]]
to = "metaserverip/32"
from = "instanceip"
via = "defaultgateway"
`,
},
}
func TestNetworkConfiguration(t *testing.T) {
g := NewWithT(t)
for _, tt := range networkConfigTest {
t.Run(tt.name, func(t *testing.T) {
b, err := system.GenerateNetworkTemplate(tt.data)
g.Expect(err).NotTo(HaveOccurred())
g.Expect(string(b)).To(Equal(tt.wantConfig))
})
}
}
| 120 |
eks-anywhere-build-tooling | aws | Go | package system
import (
"os"
"path/filepath"
"github.com/pkg/errors"
"github.com/eks-anywhere-build-tooling/aws/bottlerocket-bootstrap/pkg/files"
)
const (
bootstrapContainerPath = "/.bottlerocket/bootstrap-containers/current"
)
var rebootedPath = filepath.Join(bootstrapContainerPath, "rebooted")
func (s *Snow) rebootInstanceIfNeeded() error {
// Skip reboot when instance is already rebooted once
if files.PathExists(rebootedPath) {
return nil
}
// Write rebooted file to make sure reboot only happens once
if _, err := os.Create(rebootedPath); err != nil {
return errors.Wrap(err, "Error writing rebooted file")
}
if err := s.api.Reboot(); err != nil {
return err
}
return nil
}
| 35 |
eks-anywhere-build-tooling | aws | Go | package system
import (
"os"
"path/filepath"
"github.com/eks-anywhere-build-tooling/aws/bottlerocket-bootstrap/pkg/files"
"github.com/pkg/errors"
)
var device = filepath.Join(rootfs, "/dev/vda")
func (s *Snow) mountContainerdVolume() error {
if err := s.createPartition(); err != nil {
return errors.Wrap(err, "error creating partition")
}
if err := s.mountContainerd(); err != nil {
return errors.Wrap(err, "error mounting containerd directory")
}
return nil
}
func (s *Snow) createPartition() error {
partitionCreatedPath := filepath.Join(bootstrapContainerPath, "partition.created")
if files.PathExists(partitionCreatedPath) {
return nil
}
if err := s.fs.Partition(device); err != nil {
return err
}
if _, err := os.Create(partitionCreatedPath); err != nil {
return errors.Wrapf(err, "error writing partition created file")
}
return nil
}
func (s *Snow) mountContainerd() error {
containerdDir := filepath.Join(rootfs, "/var/lib/containerd")
if err := os.MkdirAll(containerdDir, 0o640); err != nil {
return errors.Wrap(err, "error creating directory")
}
return s.fs.MountVolume(device, containerdDir)
}
| 50 |
eks-anywhere-build-tooling | aws | Go | // Code generated by MockGen. DO NOT EDIT.
// Source: github.com/eks-anywhere-build-tooling/aws/bottlerocket-bootstrap/pkg/providers/snow/system (interfaces: APIClient)
// Package mocks is a generated GoMock package.
package mocks
import (
reflect "reflect"
gomock "github.com/golang/mock/gomock"
)
// MockAPIClient is a mock of APIClient interface.
type MockAPIClient struct {
ctrl *gomock.Controller
recorder *MockAPIClientMockRecorder
}
// MockAPIClientMockRecorder is the mock recorder for MockAPIClient.
type MockAPIClientMockRecorder struct {
mock *MockAPIClient
}
// NewMockAPIClient creates a new mock instance.
func NewMockAPIClient(ctrl *gomock.Controller) *MockAPIClient {
mock := &MockAPIClient{ctrl: ctrl}
mock.recorder = &MockAPIClientMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockAPIClient) EXPECT() *MockAPIClientMockRecorder {
return m.recorder
}
// Reboot mocks base method.
func (m *MockAPIClient) Reboot() error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Reboot")
ret0, _ := ret[0].(error)
return ret0
}
// Reboot indicates an expected call of Reboot.
func (mr *MockAPIClientMockRecorder) Reboot() *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Reboot", reflect.TypeOf((*MockAPIClient)(nil).Reboot))
}
// SetKernelCorePattern mocks base method.
func (m *MockAPIClient) SetKernelCorePattern(arg0 string) error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "SetKernelCorePattern", arg0)
ret0, _ := ret[0].(error)
return ret0
}
// SetKernelCorePattern indicates an expected call of SetKernelCorePattern.
func (mr *MockAPIClientMockRecorder) SetKernelCorePattern(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetKernelCorePattern", reflect.TypeOf((*MockAPIClient)(nil).SetKernelCorePattern), arg0)
}
// SetKernelRmemMax mocks base method.
func (m *MockAPIClient) SetKernelRmemMax(arg0 string) error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "SetKernelRmemMax", arg0)
ret0, _ := ret[0].(error)
return ret0
}
// SetKernelRmemMax indicates an expected call of SetKernelRmemMax.
func (mr *MockAPIClientMockRecorder) SetKernelRmemMax(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetKernelRmemMax", reflect.TypeOf((*MockAPIClient)(nil).SetKernelRmemMax), arg0)
}
// SetKernelWmemMax mocks base method.
func (m *MockAPIClient) SetKernelWmemMax(arg0 string) error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "SetKernelWmemMax", arg0)
ret0, _ := ret[0].(error)
return ret0
}
// SetKernelWmemMax indicates an expected call of SetKernelWmemMax.
func (mr *MockAPIClientMockRecorder) SetKernelWmemMax(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetKernelWmemMax", reflect.TypeOf((*MockAPIClient)(nil).SetKernelWmemMax), arg0)
}
// SetKubernetesAllowUnsafeSysctls mocks base method.
func (m *MockAPIClient) SetKubernetesAllowUnsafeSysctls(arg0 []string) error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "SetKubernetesAllowUnsafeSysctls", arg0)
ret0, _ := ret[0].(error)
return ret0
}
// SetKubernetesAllowUnsafeSysctls indicates an expected call of SetKubernetesAllowUnsafeSysctls.
func (mr *MockAPIClientMockRecorder) SetKubernetesAllowUnsafeSysctls(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetKubernetesAllowUnsafeSysctls", reflect.TypeOf((*MockAPIClient)(nil).SetKubernetesAllowUnsafeSysctls), arg0)
}
// SetKubernetesCloudProvider mocks base method.
func (m *MockAPIClient) SetKubernetesCloudProvider(arg0 string) error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "SetKubernetesCloudProvider", arg0)
ret0, _ := ret[0].(error)
return ret0
}
// SetKubernetesCloudProvider indicates an expected call of SetKubernetesCloudProvider.
func (mr *MockAPIClientMockRecorder) SetKubernetesCloudProvider(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetKubernetesCloudProvider", reflect.TypeOf((*MockAPIClient)(nil).SetKubernetesCloudProvider), arg0)
}
// SetKubernetesNodeIP mocks base method.
func (m *MockAPIClient) SetKubernetesNodeIP(arg0 string) error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "SetKubernetesNodeIP", arg0)
ret0, _ := ret[0].(error)
return ret0
}
// SetKubernetesNodeIP indicates an expected call of SetKubernetesNodeIP.
func (mr *MockAPIClientMockRecorder) SetKubernetesNodeIP(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetKubernetesNodeIP", reflect.TypeOf((*MockAPIClient)(nil).SetKubernetesNodeIP), arg0)
}
// SetKubernetesProviderID mocks base method.
func (m *MockAPIClient) SetKubernetesProviderID(arg0 string) error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "SetKubernetesProviderID", arg0)
ret0, _ := ret[0].(error)
return ret0
}
// SetKubernetesProviderID indicates an expected call of SetKubernetesProviderID.
func (mr *MockAPIClientMockRecorder) SetKubernetesProviderID(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetKubernetesProviderID", reflect.TypeOf((*MockAPIClient)(nil).SetKubernetesProviderID), arg0)
}
| 147 |
eks-anywhere-build-tooling | aws | Go | // Code generated by MockGen. DO NOT EDIT.
// Source: github.com/eks-anywhere-build-tooling/aws/bottlerocket-bootstrap/pkg/providers/snow/system (interfaces: FileSystem)
// Package mocks is a generated GoMock package.
package mocks
import (
reflect "reflect"
gomock "github.com/golang/mock/gomock"
)
// MockFileSystem is a mock of FileSystem interface.
type MockFileSystem struct {
ctrl *gomock.Controller
recorder *MockFileSystemMockRecorder
}
// MockFileSystemMockRecorder is the mock recorder for MockFileSystem.
type MockFileSystemMockRecorder struct {
mock *MockFileSystem
}
// NewMockFileSystem creates a new mock instance.
func NewMockFileSystem(ctrl *gomock.Controller) *MockFileSystem {
mock := &MockFileSystem{ctrl: ctrl}
mock.recorder = &MockFileSystemMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockFileSystem) EXPECT() *MockFileSystemMockRecorder {
return m.recorder
}
// MountVolume mocks base method.
func (m *MockFileSystem) MountVolume(arg0, arg1 string) error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "MountVolume", arg0, arg1)
ret0, _ := ret[0].(error)
return ret0
}
// MountVolume indicates an expected call of MountVolume.
func (mr *MockFileSystemMockRecorder) MountVolume(arg0, arg1 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "MountVolume", reflect.TypeOf((*MockFileSystem)(nil).MountVolume), arg0, arg1)
}
// Partition mocks base method.
func (m *MockFileSystem) Partition(arg0 string) error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Partition", arg0)
ret0, _ := ret[0].(error)
return ret0
}
// Partition indicates an expected call of Partition.
func (mr *MockFileSystemMockRecorder) Partition(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Partition", reflect.TypeOf((*MockFileSystem)(nil).Partition), arg0)
}
| 63 |
eks-anywhere-build-tooling | aws | Go | package service
import (
"context"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/feature/ec2/imds"
"github.com/aws/aws-sdk-go-v2/service/secretsmanager"
"github.com/pkg/errors"
)
type SecretsManagerService interface {
GetSecretValue(ctx context.Context, secretName string) (*secretsmanager.GetSecretValueOutput, error)
DeleteSecret(ctx context.Context, secretName string) (*secretsmanager.DeleteSecretOutput, error)
}
type SecretsManagerImpl struct {
BaseClient *secretsmanager.Client
}
func NewSecretsManagerService() (SecretsManagerService, error) {
clientImpl := new(SecretsManagerImpl)
cfg, _ := config.LoadDefaultConfig(context.TODO())
imdsClient := imds.NewFromConfig(cfg)
getRegionOutput, err := imdsClient.GetRegion(context.TODO(), &imds.GetRegionInput{})
if err != nil {
return nil, errors.Wrap(err, "Unable to retrieve the region from the EC2 instance")
}
cfg.Region = getRegionOutput.Region
clientImpl.BaseClient = secretsmanager.NewFromConfig(cfg)
return clientImpl, nil
}
func (client SecretsManagerImpl) GetSecretValue(ctx context.Context, secretName string) (*secretsmanager.GetSecretValueOutput, error) {
input := &secretsmanager.GetSecretValueInput{
SecretId: aws.String(secretName),
}
return client.BaseClient.GetSecretValue(ctx, input)
}
func (client SecretsManagerImpl) DeleteSecret(ctx context.Context, secretName string) (*secretsmanager.DeleteSecretOutput, error) {
deleteSecretInput := &secretsmanager.DeleteSecretInput{
SecretId: aws.String(secretName),
}
return client.BaseClient.DeleteSecret(ctx, deleteSecretInput)
}
| 48 |
eks-anywhere-build-tooling | aws | Go | // Code generated by MockGen. DO NOT EDIT.
// Source: ./secretsmanager.go
package service
import (
context "context"
reflect "reflect"
secretsmanager "github.com/aws/aws-sdk-go-v2/service/secretsmanager"
gomock "github.com/golang/mock/gomock"
)
// MockSecretsManagerService is a mock of SecretsManagerService interface.
type MockSecretsManagerService struct {
ctrl *gomock.Controller
recorder *MockSecretsManagerServiceMockRecorder
}
// MockSecretsManagerServiceMockRecorder is the mock recorder for MockSecretsManagerService.
type MockSecretsManagerServiceMockRecorder struct {
mock *MockSecretsManagerService
}
// NewMockSecretsManagerService creates a new mock instance.
func NewMockSecretsManagerService(ctrl *gomock.Controller) *MockSecretsManagerService {
mock := &MockSecretsManagerService{ctrl: ctrl}
mock.recorder = &MockSecretsManagerServiceMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockSecretsManagerService) EXPECT() *MockSecretsManagerServiceMockRecorder {
return m.recorder
}
// DeleteSecret mocks base method.
func (m *MockSecretsManagerService) DeleteSecret(ctx context.Context, secretName string) (*secretsmanager.DeleteSecretOutput, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "DeleteSecret", ctx, secretName)
ret0, _ := ret[0].(*secretsmanager.DeleteSecretOutput)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// DeleteSecret indicates an expected call of DeleteSecret.
func (mr *MockSecretsManagerServiceMockRecorder) DeleteSecret(ctx, secretName interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteSecret", reflect.TypeOf((*MockSecretsManagerService)(nil).DeleteSecret), ctx, secretName)
}
// GetSecretValue mocks base method.
func (m *MockSecretsManagerService) GetSecretValue(ctx context.Context, secretName string) (*secretsmanager.GetSecretValueOutput, error) {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "GetSecretValue", ctx, secretName)
ret0, _ := ret[0].(*secretsmanager.GetSecretValueOutput)
ret1, _ := ret[1].(error)
return ret0, ret1
}
// GetSecretValue indicates an expected call of GetSecretValue.
func (mr *MockSecretsManagerServiceMockRecorder) GetSecretValue(ctx, secretName interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetSecretValue", reflect.TypeOf((*MockSecretsManagerService)(nil).GetSecretValue), ctx, secretName)
}
| 66 |
eks-anywhere-build-tooling | aws | Go | package utils
var LogVerbosity string
| 4 |
eks-anywhere-build-tooling | aws | Go | package utils
import (
"fmt"
"io/ioutil"
"github.com/pkg/errors"
v1 "k8s.io/api/core/v1"
kubecmd "k8s.io/client-go/tools/clientcmd"
kubecmdapi "k8s.io/client-go/tools/clientcmd/api"
"sigs.k8s.io/yaml"
)
func getKubeConfigRaw(path string) (kubecmdapi.Config, error) {
// Read the kubeconfig and create config using clientcmd tool from client-go
kubeData, err := ioutil.ReadFile(path)
if err != nil {
return kubecmdapi.Config{}, errors.Wrapf(err, "Error reading kubeconfig %s", path)
}
clientConfig, err := kubecmd.NewClientConfigFromBytes(kubeData)
if err != nil {
return kubecmdapi.Config{}, errors.Wrap(err, "Error generating kubeconfig from clientset")
}
rawConfig, err := clientConfig.RawConfig()
if err != nil {
return kubecmdapi.Config{}, errors.Wrap(err, "Error getting rawconfig from kubeconfig")
}
return rawConfig, nil
}
func GetApiServerFromKubeConfig(path string) (string, error) {
rawConfig, err := getKubeConfigRaw(path)
if err != nil {
return "", errors.Wrap(err, "Error getting kubeconfig parsed into raw config")
}
// Get the server from auth information
var server string
if len(rawConfig.Clusters) != 1 {
return "", errors.Wrap(err, "More than one cluster found in control-plane init admin.conf")
}
fmt.Printf("\n%+v\n", rawConfig.Clusters)
for _, clusterInfo := range rawConfig.Clusters {
server = clusterInfo.Server
break
}
return server, nil
}
func UnmarshalPodDefinition(podDef []byte) (*v1.Pod, error) {
pod := v1.Pod{}
err := yaml.Unmarshal(podDef, &pod)
if err != nil {
return nil, errors.Wrap(err, "Error getting unmarshalling pod spec into structs")
}
return &pod, nil
}
| 58 |
eks-anywhere-build-tooling | aws | Go | package utils
import (
"encoding/base64"
"fmt"
"io/fs"
"io/ioutil"
"os/exec"
"path/filepath"
"strings"
"github.com/pkg/errors"
v1 "k8s.io/api/core/v1"
)
func EnableStaticPods(path string) ([]*v1.Pod, error) {
var podDefinitions []*v1.Pod
fmt.Println("Enabling static pods on host")
files, err := ioutil.ReadDir(path)
if err != nil {
return podDefinitions, errors.Wrap(err, "error reading from manifest path")
}
for _, f := range files {
if !isPodFile(f) {
continue
}
baseFileName := strings.TrimSuffix(f.Name(), filepath.Ext(f.Name()))
// Read the manifest and base64 encode it
fileData, err := ioutil.ReadFile(filepath.Join(path, f.Name()))
if err != nil {
return podDefinitions, errors.Wrapf(err, "Error reading file %s", f.Name())
}
b64Manifest := base64.StdEncoding.EncodeToString(fileData)
fmt.Println("Enabling static pod " + baseFileName)
fmt.Println("-------------------------------")
fmt.Printf("Manifest string: \n%s\n", string(fileData))
fmt.Println("-------------------------------")
fmt.Printf("Encoded string: \n%s\n", b64Manifest)
cmd := exec.Command("bash", "-c", "apiclient set \"kubernetes.static-pods."+baseFileName+".manifest\"=\""+b64Manifest+"\" \"kubernetes.static-pods."+baseFileName+".enabled\"=true")
out, err := cmd.CombinedOutput()
if err != nil {
fmt.Printf("Apiclient command for static pod failed, output: %s\n", string(out))
return podDefinitions, errors.Wrapf(err, "error running apiclient command for static pod: %v", err)
}
// Parse manifest from file and add to array
podDef, err := UnmarshalPodDefinition(fileData)
if err != nil {
return podDefinitions, errors.Wrap(err, "Error getting pod def from manifest")
}
podDefinitions = append(podDefinitions, podDef)
}
return podDefinitions, nil
}
var podFileExtensions = map[string]struct{}{".yaml": {}, ".manifest": {}}
func isPodFile(f fs.FileInfo) bool {
_, ok := podFileExtensions[filepath.Ext(f.Name())]
return ok
}
| 65 |
eks-anywhere-build-tooling | aws | Go | package utils
import (
"context"
"encoding/base64"
"fmt"
"io/fs"
"io/ioutil"
"os"
"os/user"
"strconv"
"strings"
"syscall"
"github.com/pkg/errors"
"gopkg.in/yaml.v2"
"github.com/eks-anywhere-build-tooling/aws/bottlerocket-bootstrap/pkg/files"
"github.com/eks-anywhere-build-tooling/aws/bottlerocket-bootstrap/pkg/service"
)
const (
hostContainerUserDataFile = "/.bottlerocket/host-containers/current/user-data"
bootstrapContainerUserDataFile = "/.bottlerocket/bootstrap-containers/current/user-data"
awsSecretsManager = "AWSSecretsManager"
)
type WriteFile struct {
Path string
Owner string
Permissions string
Content string
}
type AWSSecretsManagerData struct {
Provider string
Prefix string
Chunks int
}
type AWSSecretsManagerUserData struct {
// This field is set by the CAPI provider.
// It indicates whether this UserData is normal userdata, or a userdata that is stored remotely.
UserDataType string `yaml:"user_data_type"`
UserDataSource AWSSecretsManagerData `yaml:"secrets_manager_data"`
}
type UserData struct {
// This field is set by the CAPI provider.
// It indicates whether this UserData is normal userdata, or a userdata that is stored remotely.
UserDataType string `yaml:"user_data_type"`
WriteFiles []WriteFile `yaml:"write_files"`
RunCmd string `yaml:"runcmd"`
}
func buildUserData(filePath string) (*UserData, error) {
fmt.Println("Reading userdata file")
// read userdata from the file
data, err := ioutil.ReadFile(filePath)
if err != nil {
return nil, errors.Wrap(err, "Error reading user data file")
}
return processUserData(data)
}
func ResolveBootstrapContainerUserData() (*UserData, error) {
return buildUserData(bootstrapContainerUserDataFile)
}
func ResolveHostContainerUserData() (*UserData, error) {
return buildUserData(hostContainerUserDataFile)
}
func processUserData(data []byte) (*UserData, error) {
userData := &UserData{}
err := yaml.Unmarshal(data, userData)
if err != nil {
return nil, errors.Wrap(err, "Error unmarshalling user data")
}
fmt.Printf("\n%+v\n", userData)
if userData.UserDataType == awsSecretsManager {
secretsManagerService, err := service.NewSecretsManagerService()
if err != nil {
return nil, errors.Wrap(err, "Error creating secrets manager service")
}
return processAWSSecretsManagerUserData(data, secretsManagerService)
} else {
return userData, nil
}
}
func processAWSSecretsManagerUserData(data []byte, secretsManagerService service.SecretsManagerService) (*UserData, error) {
// If this is a AWSSecretsManager typped UserData, parse it as AWSSecretsManagerUserData
fmt.Println("The loaded userdata is referecing an external userdata, loading it...")
awsSecretsManagerUserData := &AWSSecretsManagerUserData{}
err := yaml.Unmarshal(data, awsSecretsManagerUserData)
if err != nil {
return nil, errors.Wrap(err, "Error unmarshalling user data")
}
bootstrapUserData, err := loadUserDataFromSecretsManager(awsSecretsManagerUserData, secretsManagerService)
if err != nil {
fmt.Printf("Error loading userdata from SecretsManager: %v\n", err)
os.Exit(1)
}
fmt.Println("Successfully loaded userdata from SecretsManager")
return bootstrapUserData, nil
}
func loadUserDataFromSecretsManager(awsSecretsManagerUserData *AWSSecretsManagerUserData, secretManagerService service.SecretsManagerService) (*UserData, error) {
compressedCloudConfigBinary := []byte{}
for i := 0; i < awsSecretsManagerUserData.UserDataSource.Chunks; i++ {
secretName := fmt.Sprintf("%s-%d", awsSecretsManagerUserData.UserDataSource.Prefix, i)
secret, err := secretManagerService.GetSecretValue(context.TODO(), secretName)
if err != nil {
return nil, err
}
compressedCloudConfigBinary = append(compressedCloudConfigBinary, secret.SecretBinary...)
secretManagerService.DeleteSecret(context.TODO(), secretName)
}
uncompressedData, err := GUnzipBytes(compressedCloudConfigBinary)
if err != nil {
return nil, err
}
base64UserDataString := string(uncompressedData)
actualUserDataByte, err := base64.StdEncoding.DecodeString(base64UserDataString)
if err != nil {
return nil, err
}
acutalUserData := &UserData{}
err = yaml.Unmarshal(actualUserDataByte, acutalUserData)
if err != nil {
return nil, errors.Wrap(err, "Error unmarshalling user data")
}
return acutalUserData, nil
}
func WriteUserDataFiles(userData *UserData) error {
fmt.Println("Writing userdata write files")
for _, file := range userData.WriteFiles {
if file.Permissions == "" {
file.Permissions = "0640"
}
perm, err := strconv.ParseInt(file.Permissions, 8, 64)
if err != nil {
return errors.Wrap(err, "Error converting string to int for permissions")
}
if err := files.Write(file.Path, []byte(file.Content), fs.FileMode(perm)); err != nil {
return errors.Wrapf(err, "Error writing file: %s", file.Path)
}
// get owner
owners := strings.Split(file.Owner, ":")
owner := owners[0]
userDetails, err := user.Lookup(owner)
if err != nil {
return errors.Wrap(err, "Error getting user/group details ")
}
uid, _ := strconv.Atoi(userDetails.Uid)
gid, _ := strconv.Atoi(userDetails.Gid)
err = syscall.Chown(file.Path, uid, gid)
if err != nil {
return errors.Wrap(err, "Error running chown to set owners/groups")
}
}
return nil
}
| 170 |
eks-anywhere-build-tooling | aws | Go | package utils
import (
"encoding/base64"
"fmt"
"testing"
"github.com/aws/aws-sdk-go-v2/service/secretsmanager"
"github.com/eks-anywhere-build-tooling/aws/bottlerocket-bootstrap/pkg/service"
"github.com/golang/mock/gomock"
)
// Normal UserData
const UserDataString = `
## template: jinja
#cloud-config
write_files:
- path: /var/lib/kubeadm/pki/ca.crt
owner: root:root
permissions: '0640'
content: |
-----BEGIN CERTIFICATE-----
...
-----END CERTIFICATE-----
runcmd: "ControlPlaneInit"
`
// References userdata stored in AWS SecretsManager
const AWSSecrentsManagerDataString = `
user_data_type: "AWSSecretsManager"
secrets_manager_data:
prefix: some-prefix
chunks: 1
`
func TestNormalUserData(t *testing.T) {
processedUserData, err := processUserData([]byte(UserDataString))
if err != nil {
fmt.Printf("error: %s\n", err)
}
if processedUserData.RunCmd != "ControlPlaneInit" {
t.Errorf("Unexpected RunCmd: Expected: %s, Actual: %s", "ControlPlaneInit", processedUserData.RunCmd)
}
}
func TestWithAWSSecretsManagerUserData(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
mockSecretsManagerService := service.NewMockSecretsManagerService(ctrl)
base64UserData := base64.StdEncoding.EncodeToString([]byte(UserDataString))
compressedUserData, _ := GzipBytes([]byte(base64UserData))
getSecretValueOutput := secretsmanager.GetSecretValueOutput{}
getSecretValueOutput.SecretBinary = compressedUserData
mockSecretsManagerService.EXPECT().GetSecretValue(gomock.Any(), "some-prefix-0").Return(&getSecretValueOutput, nil)
mockSecretsManagerService.EXPECT().DeleteSecret(gomock.Any(), "some-prefix-0").Return(&secretsmanager.DeleteSecretOutput{}, nil)
processedUserData, err := processAWSSecretsManagerUserData([]byte(AWSSecrentsManagerDataString), mockSecretsManagerService)
if err != nil {
fmt.Printf("error: %s\n", err)
}
if processedUserData.RunCmd != "ControlPlaneInit" {
t.Errorf("Unexpected RunCmd: Expected: %s, Actual: %s", "ControlPlaneInit", processedUserData.RunCmd)
}
}
| 69 |
eks-anywhere-build-tooling | aws | Go | package utils
import (
"bytes"
"compress/gzip"
"io/ioutil"
"os/exec"
"github.com/pkg/errors"
)
const (
ApiclientBinary = "apiclient"
BootstrapContainerName = "kubeadm-bootstrap"
)
func DisableBootstrapContainer() error {
cmd := exec.Command(ApiclientBinary, "set", "host-containers."+BootstrapContainerName+".enabled=false")
if err := cmd.Run(); err != nil {
return errors.Wrap(err, "Error disabling bootstrap container")
}
return nil
}
// Use Gzip to decompress
func GUnzipBytes(data []byte) ([]byte, error) {
// Write gzipped data to the client
gr, err := gzip.NewReader(bytes.NewBuffer(data))
if err != nil {
return nil, err
}
defer gr.Close()
uncompressedData, err := ioutil.ReadAll(gr)
if err != nil {
return nil, err
}
return uncompressedData, nil
}
// Use Gzip to compress
func GzipBytes(data []byte) ([]byte, error) {
var buf bytes.Buffer
gz := gzip.NewWriter(&buf)
if _, err := gz.Write(data); err != nil {
return []byte{}, errors.Wrap(err, "failed to gzip bytes")
}
if err := gz.Close(); err != nil {
return []byte{}, errors.Wrap(err, "failed to gzip bytes")
}
return buf.Bytes(), nil
}
| 54 |
eks-anywhere-build-tooling | aws | Go | package utils
import (
"context"
"crypto/tls"
"fmt"
"io/ioutil"
"net/http"
"os"
"os/exec"
"strconv"
"strings"
"time"
systemd "github.com/coreos/go-systemd/v22/dbus"
"github.com/godbus/dbus/v5"
"github.com/pkg/errors"
v1 "k8s.io/api/core/v1"
)
const (
KubeletService = "kubelet.service"
MultiUserTarget = "multi-user.target"
)
func WaitForSystemdService(service string, timeout time.Duration) error {
fmt.Printf("Waiting for %s to come up\n", service)
conn, err := systemd.NewConnection(func() (*dbus.Conn, error) {
dbusConn, err := dbus.Dial("unix:path=/.bottlerocket/rootfs/run/dbus/system_bus_socket")
if err != nil {
return nil, errors.Wrap(err, "Error dialing br systemd")
}
err = dbusConn.Auth([]dbus.Auth{dbus.AuthExternal(strconv.Itoa(os.Getuid()))})
if err != nil {
dbusConn.Close()
return nil, errors.Wrap(err, "Error running auth on dbus connection")
}
err = dbusConn.Hello()
if err != nil {
dbusConn.Close()
return nil, errors.Wrap(err, "Error running hello handshake on dbus connection")
}
return dbusConn, nil
})
if err != nil {
return errors.Wrap(err, "Error creating systemd dbus connection")
}
fmt.Println("Created dbus connection to talk to systemd")
defer conn.Close()
// The filter function here is an inverse filter, it will filter any included units and hence nil is provided
statusChan, errChan := conn.SubscribeUnitsCustom(time.Second*1, 1, func(u1, u2 *systemd.UnitStatus) bool {
return *u1 != *u2
}, nil)
for {
select {
case unitStatus := <-statusChan:
fmt.Printf("Received status change: %+v\n", unitStatus)
if _, ok := unitStatus[service]; ok {
if unitStatus[service].ActiveState == "active" {
if strings.HasSuffix(service, ".service") {
if unitStatus[service].SubState == "running" {
fmt.Printf("%s service is active and running\n", service)
return nil
}
} else if strings.HasSuffix(service, ".target") {
if unitStatus[service].SubState == "active" {
fmt.Printf("%s service is active and running\n", service)
return nil
}
}
}
}
case err = <-errChan:
fmt.Printf("Error received while checking for unit status: %v\n", err)
return errors.Wrap(err, "Error while checking for kubelet status")
// Timeout after timeout duration
case <-time.After(timeout):
return errors.New("Timeout checking for kubelet status")
}
}
return nil
}
func WaitFor200(url string, timeout time.Duration) error {
fmt.Printf("Waiting for 200: OK on url %s\n", url)
counter := 0
timeoutSignal := time.After(timeout)
for {
counter++
select {
case <-timeoutSignal:
return errors.New("Timeout occurred while waiting for 200 OK")
default:
fmt.Printf("****** Try %d, hitting url %s ****** \n", counter, url)
tr := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
client := &http.Client{
Transport: tr,
// Each call attempt will have a timeout of 1 minute
Timeout: 1 * time.Minute,
}
resp, err := client.Get(url)
if err != nil {
fmt.Printf("Error occured while hitting url: %v\n", err)
time.Sleep(time.Second * 10)
continue
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return errors.Wrap(err, "Error reading body from response of http get call")
}
fmt.Println(string(body))
if resp.StatusCode != 200 {
time.Sleep(time.Second * 10)
} else {
return nil
}
}
}
return nil
}
func KillCmdAfterFilesGeneration(cmd *exec.Cmd, checkFiles []string) error {
// Check for files written and send ok signal back on channel
// ctx is used here to cancel the goroutine if the timeout has occurred
okChan := make(chan bool)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go func(ctx context.Context, okChan chan bool) {
for {
time.Sleep(2 * time.Second)
select {
case <-ctx.Done():
return
default:
allFilesExist := true
for _, file := range checkFiles {
if fileInfo, err := os.Stat(file); err == nil {
fmt.Printf("File %s exists with size: %d\n", file, fileInfo.Size())
if fileInfo.Size() == 0 {
fmt.Printf("File %s doesnt not have any size yet\n", file)
}
} else if os.IsNotExist(err) {
fmt.Printf("File %s doest not exist yet\n", file)
allFilesExist = false
}
}
// Send ok on the channel
if allFilesExist {
okChan <- true
return
}
}
}
}(ctx, okChan)
timeout := time.After(40 * time.Second)
select {
case <-okChan:
fmt.Println("All files were created, exiting kubeadm command")
cmd.Process.Kill()
return nil
case <-timeout:
cmd.Process.Kill()
cancel()
return errors.New("Kubeadm join kubelet-start killed after timeout")
}
return nil
}
func waitForPodLiveness(podDefinition *v1.Pod) error {
for _, container := range podDefinition.Spec.Containers {
// Validate if liveness probe exists on the definition
if container.LivenessProbe != nil {
livenessProbeHandler := container.LivenessProbe.HTTPGet
scheme := ""
if livenessProbeHandler.Scheme != "" {
scheme = string(livenessProbeHandler.Scheme)
} else {
scheme = "http"
}
url := fmt.Sprintf("%s://%s:%d%s", scheme, livenessProbeHandler.Host, livenessProbeHandler.Port.IntVal, livenessProbeHandler.Path)
fmt.Printf("Waiting for probe check on pod: %s\n", podDefinition.Name)
err := WaitFor200(url, 5*time.Minute)
if err != nil {
return errors.Wrap(err, "Error waiting for 200 OK")
}
}
}
return nil
}
func WaitForPods(podDefinitions []*v1.Pod) error {
for _, pod := range podDefinitions {
err := waitForPodLiveness(pod)
if err != nil {
return errors.Wrapf(err, "Error checking liveness probe for pod: %s", pod.Name)
}
}
return nil
}
| 214 |
eks-anywhere-build-tooling | aws | Go | package main
import (
"os"
"github.com/aws/eks-anywhere-build-tooling/image-builder/cmd"
)
func main() {
if cmd.Execute() == nil {
os.Exit(0)
}
os.Exit(-1)
}
| 15 |
eks-anywhere-build-tooling | aws | Go | package builder
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"os"
"path/filepath"
)
const (
buildToolingRepoUrl = "https://github.com/aws/eks-anywhere-build-tooling.git"
)
var codebuild = os.Getenv("CODEBUILD_CI")
func (b *BuildOptions) BuildImage() {
// Clone build tooling repo
cwd, err := os.Getwd()
if err != nil {
log.Fatalf("error retrieving current working directory: %v", err)
}
buildToolingRepoPath := getBuildToolingPath(cwd)
if b.Force && codebuild != "true" {
// Clean up build tooling repo in cwd
cleanup(buildToolingRepoPath)
}
if codebuild != "true" {
err = cloneRepo(buildToolingRepoUrl, buildToolingRepoPath)
if err != nil {
log.Fatalf("Error cloning build tooling repo")
}
log.Println("Cloned eks-anywhere-build-tooling repo")
gitCommitFromBundle, err := getGitCommitFromBundle(buildToolingRepoPath)
if err != nil {
log.Fatalf("Error getting git commit from bundle: %v", err)
}
err = checkoutRepo(buildToolingRepoPath, gitCommitFromBundle)
if err != nil {
log.Fatalf("Error checking out build tooling repo at commit %s", gitCommitFromBundle)
}
log.Printf("Checked out eks-anywhere-build-tooling repo at commit %s\n", gitCommitFromBundle)
} else {
buildToolingRepoPath = os.Getenv("CODEBUILD_SRC_DIR")
log.Println("Using repo checked out from code commit")
}
supportedReleaseBranches := GetSupportedReleaseBranches()
if !SliceContains(supportedReleaseBranches, b.ReleaseChannel) {
if codebuild != "true" {
cleanup(buildToolingRepoPath)
}
log.Fatalf("release-channel should be one of %v", supportedReleaseBranches)
}
imageBuilderProjectPath := filepath.Join(buildToolingRepoPath, "projects/kubernetes-sigs/image-builder")
upstreamImageBuilderProjectPath := filepath.Join(imageBuilderProjectPath, "image-builder/images/capi")
var outputArtifactPath string
var outputImageGlob []string
commandEnvVars := []string{fmt.Sprintf("RELEASE_BRANCH=%s", b.ReleaseChannel)}
log.Printf("Initiating Image Build\n Image OS: %s\n Image OS Version: %s\n Hypervisor: %s\n", b.Os, b.OsVersion, b.Hypervisor)
if b.Hypervisor == VSphere {
// Read and set the vsphere connection data
vsphereConfigData, err := json.Marshal(b.VsphereConfig)
if err != nil {
log.Fatalf("Error marshalling vsphere config data")
}
err = ioutil.WriteFile(filepath.Join(imageBuilderProjectPath, "packer/ova/vsphere.json"), vsphereConfigData, 0o644)
if err != nil {
log.Fatalf("Error writing vsphere config file to packer")
}
var buildCommand string
switch b.Os {
case Ubuntu:
buildCommand = fmt.Sprintf("make -C %s local-build-ova-ubuntu-%s", imageBuilderProjectPath, b.OsVersion)
case RedHat:
buildCommand = fmt.Sprintf("make -C %s local-build-ova-redhat-%s", imageBuilderProjectPath, b.OsVersion)
commandEnvVars = append(commandEnvVars,
fmt.Sprintf("RHSM_USERNAME=%s", b.VsphereConfig.RhelUsername),
fmt.Sprintf("RHSM_PASSWORD=%s", b.VsphereConfig.RhelPassword),
)
}
err = executeMakeBuildCommand(buildCommand, commandEnvVars...)
if err != nil {
log.Fatalf("Error executing image-builder for vsphere hypervisor: %v", err)
}
// Move the output ova to cwd
outputImageGlob, err = filepath.Glob(filepath.Join(upstreamImageBuilderProjectPath, "output/*.ova"))
if err != nil {
log.Fatalf("Error getting glob for output files: %v", err)
}
outputArtifactPath = filepath.Join(cwd, fmt.Sprintf("%s.ova", b.Os))
log.Printf("Image Build Successful\n Please find the output artifact at %s\n", outputArtifactPath)
} else if b.Hypervisor == Baremetal {
baremetalConfigFile := filepath.Join(imageBuilderProjectPath, "packer/config/baremetal.json")
if b.BaremetalConfig != nil {
baremetalConfigData, err := json.Marshal(b.BaremetalConfig)
if err != nil {
log.Fatalf("Error marshalling baremetal config data")
}
err = ioutil.WriteFile(baremetalConfigFile, baremetalConfigData, 0o644)
if err != nil {
log.Fatalf("Error writing baremetal config file to packer")
}
}
var buildCommand string
switch b.Os {
case Ubuntu:
buildCommand = fmt.Sprintf("make -C %s local-build-raw-ubuntu-%s", imageBuilderProjectPath, b.OsVersion)
case RedHat:
buildCommand = fmt.Sprintf("make -C %s local-build-raw-redhat-%s", imageBuilderProjectPath, b.OsVersion)
commandEnvVars = append(commandEnvVars,
fmt.Sprintf("RHSM_USERNAME=%s", b.BaremetalConfig.RhelUsername),
fmt.Sprintf("RHSM_PASSWORD=%s", b.BaremetalConfig.RhelPassword),
)
}
if b.BaremetalConfig != nil {
commandEnvVars = append(commandEnvVars, fmt.Sprintf("PACKER_RAW_VAR_FILES=%s", baremetalConfigFile))
}
err = executeMakeBuildCommand(buildCommand, commandEnvVars...)
if err != nil {
log.Fatalf("Error executing image-builder for raw hypervisor: %v", err)
}
outputImageGlob, err = filepath.Glob(filepath.Join(upstreamImageBuilderProjectPath, "output/*.gz"))
if err != nil {
log.Fatalf("Error getting glob for output files: %v", err)
}
outputArtifactPath = filepath.Join(cwd, fmt.Sprintf("%s.gz", b.Os))
} else if b.Hypervisor == Nutanix {
// Patch firmware config for tool
upstreamPatchCommand := fmt.Sprintf("make -C %s patch-repo", imageBuilderProjectPath)
if err = executeMakeBuildCommand(upstreamPatchCommand, commandEnvVars...); err != nil {
log.Fatalf("Error executing upstream patch command")
}
// Read and set the nutanix connection data
nutanixConfigData, err := json.Marshal(b.NutanixConfig)
if err != nil {
log.Fatalf("Error marshalling nutanix config data")
}
err = ioutil.WriteFile(filepath.Join(upstreamImageBuilderProjectPath, "packer/nutanix/nutanix.json"), nutanixConfigData, 0o644)
if err != nil {
log.Fatalf("Error writing nutanix config file to packer: %v", err)
}
buildCommand := fmt.Sprintf("make -C %s local-build-nutanix-ubuntu-%s", imageBuilderProjectPath, b.OsVersion)
err = executeMakeBuildCommand(buildCommand, commandEnvVars...)
if err != nil {
log.Fatalf("Error executing image-builder for nutanix hypervisor: %v", err)
}
log.Printf("Image Build Successful\n Please find the image uploaded under Nutanix Image Service with name %s\n", b.NutanixConfig.ImageName)
} else if b.Hypervisor == CloudStack {
// Create config file
cloudstackConfigFile := filepath.Join(imageBuilderProjectPath, "packer/config/cloudstack.json")
// Assign ansible user var for cloudstack provider
b.CloudstackConfig.AnsibleUserVars = "provider=cloudstack"
if b.CloudstackConfig != nil {
cloudstackConfigData, err := json.Marshal(b.CloudstackConfig)
if err != nil {
log.Fatalf("Error marshalling cloudstack config data")
}
err = ioutil.WriteFile(cloudstackConfigFile, cloudstackConfigData, 0o644)
if err != nil {
log.Fatalf("Error writing cloudstack config file to packer")
}
}
var buildCommand string
var outputImageGlobPattern string
switch b.Os {
case RedHat:
outputImageGlobPattern = "output/rhel-*/rhel-*"
buildCommand = fmt.Sprintf("make -C %s local-build-cloudstack-redhat-%s", imageBuilderProjectPath, b.OsVersion)
commandEnvVars = append(commandEnvVars,
fmt.Sprintf("RHSM_USERNAME=%s", b.CloudstackConfig.RhelUsername),
fmt.Sprintf("RHSM_PASSWORD=%s", b.CloudstackConfig.RhelPassword),
)
}
if b.CloudstackConfig != nil {
commandEnvVars = append(commandEnvVars, fmt.Sprintf("PACKER_CLOUDSTACK_VAR_FILES=%s", cloudstackConfigFile))
}
err = executeMakeBuildCommand(buildCommand, commandEnvVars...)
if err != nil {
log.Fatalf("Error executing image-builder for raw hypervisor: %v", err)
}
outputImageGlob, err = filepath.Glob(filepath.Join(upstreamImageBuilderProjectPath, outputImageGlobPattern))
if err != nil {
log.Fatalf("Error getting glob for output files: %v", err)
}
outputArtifactPath = filepath.Join(cwd, fmt.Sprintf("%s.qcow2", b.Os))
} else if b.Hypervisor == AMI {
amiConfigFile := filepath.Join(imageBuilderProjectPath, "packer/ami/ami.json")
upstreamPatchCommand := fmt.Sprintf("make -C %s patch-repo", imageBuilderProjectPath)
if err = executeMakeBuildCommand(upstreamPatchCommand, commandEnvVars...); err != nil {
log.Fatalf("Error executing upstream patch command")
}
if b.AMIConfig != nil {
amiConfigData, err := json.Marshal(b.AMIConfig)
if err != nil {
log.Fatalf("Error marshalling AMI config data")
}
err = ioutil.WriteFile(amiConfigFile, amiConfigData, 0o644)
if err != nil {
log.Fatalf("Error writing AMI config file to packer")
}
}
buildCommand := fmt.Sprintf("make -C %s local-build-ami-ubuntu-%s", imageBuilderProjectPath, b.OsVersion)
err = executeMakeBuildCommand(buildCommand, commandEnvVars...)
if err != nil {
log.Fatalf("Error executing image-builder for AMI hypervisor: %v", err)
}
}
if outputArtifactPath != "" {
// Moving artifacts from upstream directory to cwd
log.Println("Moving artifacts from build directory to current working directory")
err = os.Rename(outputImageGlob[0], outputArtifactPath)
if err != nil {
log.Fatalf("Error moving output file to current working directory")
}
}
if codebuild != "true" {
cleanup(buildToolingRepoPath)
}
log.Print("Build Successful. Output artifacts located at current working directory\n")
}
| 252 |
eks-anywhere-build-tooling | aws | Go | package builder
const (
DefaultUbuntu2004AMIFilterName string = "ubuntu/images/*ubuntu-focal-20.04-amd64-server-*"
DefaultUbuntu2204AMIFilterName string = "ubuntu/images/*ubuntu-jammy-22.04-amd64-server-*"
DefaultUbuntuAMIFilterOwners string = "679593333241"
DefaultAMIBuildRegion string = "us-west-2"
DefaultAMIBuilderInstanceType string = "t3.small"
DefaultAMIRootDeviceName string = "/dev/sda1"
DefaultAMIVolumeSize string = "25"
DefaultAMIVolumeType string = "gp3"
DefaultAMIAnsibleExtraVars string = "@/home/image-builder/eks-anywhere-build-tooling/projects/kubernetes-sigs/image-builder/packer/ami/ansible_extra_vars.yaml"
DefaultAMIManifestOutput string = "/home/image-builder/manifest.json"
)
| 15 |
eks-anywhere-build-tooling | aws | Go | package builder
const (
Ubuntu string = "ubuntu"
RedHat string = "redhat"
VSphere string = "vsphere"
Baremetal string = "baremetal"
Nutanix string = "nutanix"
CloudStack string = "cloudstack"
AMI string = "ami"
)
var SupportedHypervisors = []string{
VSphere,
Baremetal,
Nutanix,
CloudStack,
AMI,
}
var SupportedUbuntuVersions = []string{
"20.04",
"22.04",
}
var SupportedRedHatVersions = []string{
"8",
}
type BuildOptions struct {
Os string
OsVersion string
Hypervisor string
VsphereConfig *VsphereConfig
BaremetalConfig *BaremetalConfig
NutanixConfig *NutanixConfig
CloudstackConfig *CloudstackConfig
AMIConfig *AMIConfig
ReleaseChannel string
artifactsBucket string
Force bool
}
type VsphereConfig struct {
Cluster string `json:"cluster"`
ConvertToTemplate string `json:"convert_to_template"`
CreateSnapshot string `json:"create_snapshot"`
Datacenter string `json:"datacenter"`
Datastore string `json:"datastore"`
Folder string `json:"folder"`
InsecureConnection string `json:"insecure_connection"`
LinkedClone string `json:"linked_clone"`
Network string `json:"network"`
ResourcePool string `json:"resource_pool"`
Template string `json:"template"`
VcenterServer string `json:"vcenter_server"`
VsphereLibraryName string `json:"vsphere_library_name"`
Username string `json:"username"`
Password string `json:"password"`
IsoConfig
RhelConfig
ExtraPackagesConfig
}
type BaremetalConfig struct {
IsoConfig
RhelConfig
ExtraPackagesConfig
}
type CloudstackConfig struct {
AnsibleUserVars string `json:"ansible_user_vars"`
IsoConfig
RhelConfig
ExtraPackagesConfig
}
type IsoConfig struct {
IsoUrl string `json:"iso_url,omitempty"`
IsoChecksum string `json:"iso_checksum,omitempty"`
IsoChecksumType string `json:"iso_checksum_type,omitempty"`
}
type RhelConfig struct {
RhelUsername string `json:"rhel_username"`
RhelPassword string `json:"rhel_password"`
}
type NutanixConfig struct {
ClusterName string `json:"nutanix_cluster_name"`
ImageName string `json:"image_name"`
SourceImageName string `json:"source_image_name"`
NutanixEndpoint string `json:"nutanix_endpoint"`
NutanixInsecure string `json:"nutanix_insecure"`
NutanixPort string `json:"nutanix_port"`
NutanixUserName string `json:"nutanix_username"`
NutanixPassword string `json:"nutanix_password"`
NutanixSubnetName string `json:"nutanix_subnet_name"`
ExtraPackagesConfig
}
type AMIConfig struct {
AMIFilterName string `json:"ami_filter_name"`
AMIFilterOwners string `json:"ami_filter_owners"`
AMIRegions string `json:"ami_regions"`
AWSRegion string `json:"aws_region"`
AnsibleExtraVars string `json:"ansible_extra_vars"`
BuilderInstanceType string `json:"builder_instance_type"`
CustomRole string `json:"custom_role"`
CustomRoleNameList []string `json:"custom_role_name_list,omitempty"`
CustomRoleNames string `json:"custom_role_names"`
ManifestOutput string `json:"manifest_output"`
RootDeviceName string `json:"root_device_name"`
SubnetID string `json:"subnet_id"`
VolumeSize string `json:"volume_size"`
VolumeType string `json:"volume_type"`
ExtraPackagesConfig
}
type ExtraPackagesConfig struct {
ExtraDebs string `json:"extra_debs,omitempty"`
ExtraRepos string `json:"extra_repos,omitempty"`
ExtraRpms string `json:"extra_rpms,omitempty"`
} | 124 |
eks-anywhere-build-tooling | aws | Go | package builder
import (
"fmt"
"log"
"os"
"os/exec"
"path/filepath"
"strings"
releasev1 "github.com/aws/eks-anywhere/release/api/v1alpha1"
"sigs.k8s.io/yaml"
)
func cloneRepo(cloneUrl, destination string) error {
log.Println("Cloning eks-anywhere-build-tooling...")
cloneRepoCommandSequence := fmt.Sprintf("git clone %s %s", cloneUrl, destination)
cmd := exec.Command("bash", "-c", cloneRepoCommandSequence)
return execCommandWithStreamOutput(cmd)
}
func checkoutRepo(gitRoot, commit string) error {
log.Println("Checking out commit %s for build...", commit)
checkoutRepoCommandSequence := fmt.Sprintf("git -C %s checkout %s", gitRoot, commit)
cmd := exec.Command("bash", "-c", checkoutRepoCommandSequence)
return execCommandWithStreamOutput(cmd)
}
func execCommandWithStreamOutput(cmd *exec.Cmd) error {
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
log.Printf("Executing command: %v\n", cmd)
err := cmd.Run()
if err != nil {
return fmt.Errorf("failed to run command: %v", err)
}
return nil
}
func executeMakeBuildCommand(buildCommand string, envVars ...string) error {
cmd := exec.Command("bash", "-c", buildCommand)
cmd.Env = os.Environ()
for _, envVar := range envVars {
cmd.Env = append(cmd.Env, envVar)
}
return execCommandWithStreamOutput(cmd)
}
func cleanup(buildToolingDir string) {
log.Print("Cleaning up cache build files")
err := os.RemoveAll(buildToolingDir)
if err != nil {
log.Fatalf("Error cleaning up build tooling dir: %v", err)
}
}
func GetSupportedReleaseBranches() []string {
buildToolingPath, err := getRepoRoot()
if err != nil {
log.Fatalf(err.Error())
}
supportedBranchesFile := filepath.Join(buildToolingPath, "release/SUPPORTED_RELEASE_BRANCHES")
supportedBranchesFileData, err := os.ReadFile(supportedBranchesFile)
supportReleaseBranches := strings.Split(string(supportedBranchesFileData), "\n")
return supportReleaseBranches
}
func getBuildToolingPath(cwd string) string {
buildToolingRepoPath := filepath.Join(cwd, "eks-anywhere-build-tooling")
if codebuild == "true" {
buildToolingRepoPath = os.Getenv("CODEBUILD_SRC_DIR")
}
return buildToolingRepoPath
}
func getRepoRoot() (string, error) {
cwd, err := os.Getwd()
if err != nil {
return "", fmt.Errorf("error retrieving current working directory: %v", err)
}
buildToolingPath := getBuildToolingPath(cwd)
cmd := exec.Command("git", "-C", buildToolingPath, "rev-parse", "--show-toplevel")
commandOut, err := execCommand(cmd)
if err != nil {
return "", err
}
return commandOut, nil
}
func SliceContains(s []string, str string) bool {
for _, elem := range s {
if elem == str {
return true
}
}
return false
}
func execCommand(cmd *exec.Cmd) (string, error) {
log.Printf("Executing command: %v\n", cmd)
commandOutput, err := cmd.CombinedOutput()
commandOutputStr := strings.TrimSpace(string(commandOutput))
if err != nil {
return commandOutputStr, fmt.Errorf("failed to run command: %v", err)
}
return commandOutputStr, nil
}
func getGitCommitFromBundle(repoPath string) (string, error) {
log.Println("Getting git commit from bundle")
loadBundleManifestCommandSequence := fmt.Sprintf("source %s/build/lib/eksa_releases.sh && build::eksa_releases::load_bundle_manifest", repoPath, repoPath)
cmd := exec.Command("bash", "-c", fmt.Sprintf("%s", loadBundleManifestCommandSequence))
commandOut, err := execCommand(cmd)
if err != nil {
return commandOut, err
}
bundles := &releasev1.Bundles{}
if err = yaml.Unmarshal([]byte(commandOut), bundles); err != nil {
return "", fmt.Errorf("failed to unmarshal bundles manifest: %v", err)
}
return bundles.Spec.VersionsBundles[0].EksD.GitCommit, nil
}
| 128 |
eks-anywhere-build-tooling | aws | Go | package builder
import (
"testing"
)
func TestGetSupportedReleaseBranchesSuccess(t *testing.T) {
b := BuildOptions{
ReleaseChannel: "1-24",
}
supportedReleaseBranches := GetSupportedReleaseBranches()
if !SliceContains(supportedReleaseBranches, b.ReleaseChannel) {
t.Fatalf("GetSupportedReleaseBranches error: supported branches does not contain the release channel"+
": %s", b.ReleaseChannel)
}
}
func TestGetSupportedReleaseBranchesFailure(t *testing.T) {
b := BuildOptions{
ReleaseChannel: "1-16",
}
supportedReleaseBranches := GetSupportedReleaseBranches()
if SliceContains(supportedReleaseBranches, b.ReleaseChannel) {
t.Fatalf("GetSupportedReleaseBranches error: supported branches does not contain the release channel"+
": %s", b.ReleaseChannel)
}
}
| 30 |
eks-anywhere-build-tooling | aws | Go | package cmd
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"path/filepath"
"strings"
"github.com/spf13/cobra"
"github.com/aws/eks-anywhere-build-tooling/image-builder/builder"
)
var (
bo = &builder.BuildOptions{}
vSphereConfigFile string
baremetalConfigFile string
nutanixConfigFile string
cloudstackConfigFile string
amiConfigFile string
err error
)
var buildCmd = &cobra.Command{
Use: "build --os <image os> --hypervisor <target hypervisor>",
Short: "Build EKS Anywhere Node Image",
Long: "This command is used to build EKS Anywhere node images",
Run: func(cmd *cobra.Command, args []string) {
fmt.Println("Creating builder config")
err = ValidateInputs(bo)
if err != nil {
log.Fatalf(err.Error())
}
bo.BuildImage()
},
}
func init() {
rootCmd.AddCommand(buildCmd)
buildCmd.Flags().StringVar(&bo.Os, "os", "", "Operating system to use for EKS-A node image")
buildCmd.Flags().StringVar(&bo.OsVersion, "os-version", "", "Operating system version to use for EKS-A node image. Can be 20.04 or 22.04 for Ubuntu or 8 for Redhat. ")
buildCmd.Flags().StringVar(&bo.Hypervisor, "hypervisor", "", "Target hypervisor EKS-A node image")
buildCmd.Flags().StringVar(&baremetalConfigFile, "baremetal-config", "", "Path to Baremetal Config file")
buildCmd.Flags().StringVar(&vSphereConfigFile, "vsphere-config", "", "Path to vSphere Config file")
buildCmd.Flags().StringVar(&nutanixConfigFile, "nutanix-config", "", "Path to Nutanix Config file")
buildCmd.Flags().StringVar(&cloudstackConfigFile, "cloudstack-config", "", "Path to CloudStack Config file")
buildCmd.Flags().StringVar(&amiConfigFile, "ami-config", "", "Path to AMI Config file")
buildCmd.Flags().StringVar(&bo.ReleaseChannel, "release-channel", "1-27", "EKS-D Release channel for node image. Can be 1-23, 1-24, 1-25, 1-26 or 1-27")
buildCmd.Flags().BoolVar(&bo.Force, "force", false, "Force flag to clean up leftover files from previous execution")
if err := buildCmd.MarkFlagRequired("os"); err != nil {
log.Fatalf("Error marking flag as required: %v", err)
}
if err := buildCmd.MarkFlagRequired("hypervisor"); err != nil {
log.Fatalf("Error marking flag as required: %v", err)
}
if err := buildCmd.MarkFlagRequired("release-channel"); err != nil {
log.Fatalf("Error marking flag as required: %v", err)
}
}
func ValidateInputs(bo *builder.BuildOptions) error {
if bo.Os != builder.Ubuntu && bo.Os != builder.RedHat {
log.Fatalf("Invalid OS type. Please choose ubuntu or redhat")
}
if err = validateSupportedHypervisors(bo.Hypervisor); err != nil {
log.Fatal(err.Error())
}
if err = validateOSHypervisorCombinations(bo.Os, bo.Hypervisor); err != nil {
log.Fatal(err.Error())
}
if bo.Os == builder.Ubuntu && bo.OsVersion == "" {
// maintain previous default
bo.OsVersion = "20.04"
}
if bo.Os == builder.RedHat && bo.OsVersion == "" {
// maintain previous default
bo.OsVersion = "8"
}
if err = validateOSVersion(bo.Os, bo.OsVersion); err != nil {
log.Fatal(err.Error())
}
configPath := ""
switch bo.Hypervisor {
case builder.VSphere:
configPath = vSphereConfigFile
case builder.Baremetal:
configPath = baremetalConfigFile
case builder.Nutanix:
configPath = nutanixConfigFile
case builder.CloudStack:
configPath = cloudstackConfigFile
case builder.AMI:
configPath = amiConfigFile
}
bo.Os = strings.ToLower(bo.Os)
bo.Hypervisor = strings.ToLower(bo.Hypervisor)
if bo.OsVersion != "" {
// From this point forward use 2004 instead of 20.04 for Ubuntu versions to upstream image-builder
bo.OsVersion = strings.ReplaceAll(bo.OsVersion, ".", "")
}
if configPath == "" {
if bo.Hypervisor == builder.VSphere ||
(bo.Hypervisor == builder.Baremetal && bo.Os == builder.RedHat) ||
(bo.Hypervisor == builder.Nutanix) ||
(bo.Hypervisor == builder.CloudStack) {
return fmt.Errorf("%s-config is a required flag for %s hypervisor or when os is redhat", bo.Hypervisor, bo.Hypervisor)
}
} else {
configPath, err = filepath.Abs(configPath)
if err != nil {
return fmt.Errorf("Error converting %s config file path to absolute path", bo.Hypervisor)
}
config, err := ioutil.ReadFile(configPath)
if err != nil {
return fmt.Errorf("Error reading %s config file", bo.Hypervisor)
}
switch bo.Hypervisor {
case builder.VSphere:
if err = json.Unmarshal(config, &bo.VsphereConfig); err != nil {
return err
}
if bo.Os == builder.RedHat {
if err = validateRedhat(bo.VsphereConfig.RhelUsername, bo.VsphereConfig.RhelPassword, bo.VsphereConfig.IsoUrl); err != nil {
return err
}
}
if bo.VsphereConfig.IsoUrl != "" {
if err = validateCustomIso(bo.VsphereConfig.IsoChecksum, bo.VsphereConfig.IsoChecksumType); err != nil {
return err
}
}
case builder.Baremetal:
if err = json.Unmarshal(config, &bo.BaremetalConfig); err != nil {
return err
}
if bo.Os == builder.RedHat {
if err = validateRedhat(bo.BaremetalConfig.RhelUsername, bo.BaremetalConfig.RhelPassword, bo.BaremetalConfig.IsoUrl); err != nil {
return err
}
}
if bo.BaremetalConfig != nil && bo.BaremetalConfig.IsoUrl != "" {
if err = validateCustomIso(bo.BaremetalConfig.IsoChecksum, bo.BaremetalConfig.IsoChecksumType); err != nil {
return err
}
}
case builder.Nutanix:
if err = json.Unmarshal(config, &bo.NutanixConfig); err != nil {
return err
}
if bo.NutanixConfig.NutanixUserName == "" || bo.NutanixConfig.NutanixPassword == "" {
log.Fatalf("\"nutanix_username\" and \"nutanix_password\" are required fields in nutanix-config")
}
// TODO Validate other fields as well
case builder.CloudStack:
if err = json.Unmarshal(config, &bo.CloudstackConfig); err != nil {
return err
}
if bo.Os == builder.RedHat {
if err = validateRedhat(bo.CloudstackConfig.RhelUsername, bo.CloudstackConfig.RhelPassword, bo.CloudstackConfig.IsoUrl); err != nil {
return err
}
}
if bo.CloudstackConfig.IsoUrl != "" {
if err = validateCustomIso(bo.CloudstackConfig.IsoChecksum, bo.CloudstackConfig.IsoChecksumType); err != nil {
return err
}
}
case builder.AMI:
// Default configuration for AMI builds
amiFilter := builder.DefaultUbuntu2004AMIFilterName
if bo.OsVersion == "2204" {
amiFilter = builder.DefaultUbuntu2204AMIFilterName
}
amiConfig := &builder.AMIConfig{
AMIFilterName: amiFilter,
AMIFilterOwners: builder.DefaultUbuntuAMIFilterOwners,
AMIRegions: builder.DefaultAMIBuildRegion,
AWSRegion: builder.DefaultAMIBuildRegion,
BuilderInstanceType: builder.DefaultAMIBuilderInstanceType,
CustomRole: "true",
AnsibleExtraVars: builder.DefaultAMIAnsibleExtraVars,
ManifestOutput: builder.DefaultAMIManifestOutput,
RootDeviceName: builder.DefaultAMIRootDeviceName,
VolumeSize: builder.DefaultAMIVolumeSize,
VolumeType: builder.DefaultAMIVolumeType,
}
if err = json.Unmarshal(config, amiConfig); err != nil {
return err
}
if amiConfig.CustomRole == "true" {
if (amiConfig.CustomRoleNameList == nil && amiConfig.CustomRoleNames == "") ||
(amiConfig.CustomRoleNameList != nil && amiConfig.CustomRoleNames != "") {
log.Fatalf("Exactly one of \"custom_role_name_list\" or \"custom_role_names\" must be provided")
}
if amiConfig.CustomRoleNameList != nil {
amiConfig.CustomRoleNames = strings.Join(amiConfig.CustomRoleNameList, " ")
amiConfig.CustomRoleNameList = nil
}
}
bo.AMIConfig = amiConfig
}
}
return nil
}
func validateOSHypervisorCombinations(os, hypervisor string) error {
if hypervisor == builder.CloudStack && os != builder.RedHat {
return fmt.Errorf("Invalid OS type. Only redhat OS is supported for CloudStack")
}
if hypervisor == builder.Nutanix && os != builder.Ubuntu {
return fmt.Errorf("Invalid OS type. Only ubuntu OS is supported for Nutanix")
}
if hypervisor == builder.AMI && os != builder.Ubuntu {
return fmt.Errorf("Invalid OS type. Only ubuntu OS is supported for AMI")
}
return nil
}
func validateRedhat(rhelUsername, rhelPassword, isoUrl string) error {
if rhelUsername == "" || rhelPassword == "" {
return fmt.Errorf("\"rhel_username\" and \"rhel_password\" are required fields in config when os is redhat")
}
if isoUrl == "" {
return fmt.Errorf("\"iso_url\" is a required field in config when os is redhat")
}
return nil
}
func validateCustomIso(isoChecksum, isoChecksumType string) error {
if isoChecksum == "" {
return fmt.Errorf("Please provide a valid checksum for \"iso_checksum\" when providing \"iso_url\"")
}
if isoChecksumType != "sha256" && isoChecksumType != "sha512" {
return fmt.Errorf("\"iso_checksum_type\" is a required field when providing iso_checksum. Checksum type can be sha256 or sha512")
}
return nil
}
func validateSupportedHypervisors(hypervisor string) error {
if builder.SliceContains(builder.SupportedHypervisors, hypervisor) {
return nil
}
return fmt.Errorf("%s is not supported yet. Please select one of %s", hypervisor, strings.Join(builder.SupportedHypervisors, ","))
}
func validateOSVersion(os string, osVersion string) error {
if os != builder.RedHat && os != builder.Ubuntu {
return fmt.Errorf("%s is not a supported OS.", os)
}
if os == builder.Ubuntu && !builder.SliceContains(builder.SupportedUbuntuVersions,osVersion) {
return fmt.Errorf("%s is not a supported version of Ubuntu. Please select one of %s", osVersion, strings.Join(builder.SupportedUbuntuVersions, ","))
}
if os == builder.RedHat && !builder.SliceContains(builder.SupportedRedHatVersions,osVersion) {
return fmt.Errorf("%s is not a supported version of Redhat. Please select one of %s", osVersion, strings.Join(builder.SupportedRedHatVersions, ","))
}
return nil
}
| 279 |
eks-anywhere-build-tooling | aws | Go | package cmd
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/aws/eks-anywhere-build-tooling/image-builder/builder"
)
func TestValidateSupportedHypervisor(t *testing.T) {
testCases := []struct {
testName string
buildOptions builder.BuildOptions
wantErr string
}{
{
testName: "vSphere hypervisor",
buildOptions: builder.BuildOptions{
Hypervisor: "vsphere",
},
wantErr: "",
},
{
testName: "AMI hypervisor",
buildOptions: builder.BuildOptions{
Hypervisor: "ami",
},
wantErr: "",
},
{
testName: "Unknown hypervisor",
buildOptions: builder.BuildOptions{
Hypervisor: "unknown-hypervisor",
},
wantErr: "unknown-hypervisor is not supported yet. Please select one of vsphere,baremetal,nutanix,cloudstack,ami",
},
}
for _, tt := range testCases {
t.Run(tt.testName, func(t *testing.T) {
err := validateSupportedHypervisors(tt.buildOptions.Hypervisor)
if tt.wantErr == "" {
assert.NoError(t, err)
} else {
assert.Equal(t, tt.wantErr, err.Error())
}
})
}
}
func TestValidateOSHypervisorCombinations(t *testing.T) {
testCases := []struct {
testName string
buildOptions builder.BuildOptions
wantErr string
}{
{
testName: "Cloudstack hypervisor with Redhat OS",
buildOptions: builder.BuildOptions{
Hypervisor: "cloudstack",
Os: "redhat",
},
wantErr: "",
},
{
testName: "AMI hypervisor with Ubuntu OS",
buildOptions: builder.BuildOptions{
Hypervisor: "ami",
Os: "ubuntu",
},
wantErr: "",
},
{
testName: "Nutanix hypervisor with Redhat OS",
buildOptions: builder.BuildOptions{
Hypervisor: "nutanix",
Os: "redhat",
},
wantErr: "Invalid OS type. Only ubuntu OS is supported for Nutanix",
},
}
for _, tt := range testCases {
t.Run(tt.testName, func(t *testing.T) {
err := validateOSHypervisorCombinations(tt.buildOptions.Os, tt.buildOptions.Hypervisor)
if tt.wantErr == "" {
assert.NoError(t, err)
} else {
assert.NotNil(t, err)
assert.Equal(t, tt.wantErr, err.Error())
}
})
}
}
func TestValidateOSVersionCombinations(t *testing.T) {
testCases := []struct {
testName string
buildOptions builder.BuildOptions
wantErr string
}{
{
testName: "Ubuntu 20.04",
buildOptions: builder.BuildOptions{
Os: "ubuntu",
OsVersion: "20.04",
},
wantErr: "",
},
{
testName: "Ubuntu 22.04",
buildOptions: builder.BuildOptions{
Os: "ubuntu",
OsVersion: "22.04",
},
wantErr: "",
},
{
testName: "Ubuntu 24.04",
buildOptions: builder.BuildOptions{
Os: "ubuntu",
OsVersion: "24.04",
},
wantErr: "24.04 is not a supported version of Ubuntu. Please select one of 20.04,22.04",
},
{
testName: "Redhat 8",
buildOptions: builder.BuildOptions{
Os: "redhat",
OsVersion: "8",
},
wantErr: "",
},
{
testName: "Redhat 9",
buildOptions: builder.BuildOptions{
Os: "redhat",
OsVersion: "9",
},
wantErr: "9 is not a supported version of Redhat. Please select one of 8",
},
{
testName: "Rockylinux 1",
buildOptions: builder.BuildOptions{
Os: "rocky",
OsVersion: "1",
},
wantErr: "rocky is not a supported OS.",
},
}
for _, tt := range testCases {
t.Run(tt.testName, func(t *testing.T) {
err := validateOSVersion(tt.buildOptions.Os, tt.buildOptions.OsVersion)
if tt.wantErr == "" {
assert.NoError(t, err)
} else {
assert.NotNil(t, err)
assert.Equal(t, tt.wantErr, err.Error())
}
})
}
}
| 165 |
eks-anywhere-build-tooling | aws | Go | package cmd
import (
"log"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
var rootCmd = &cobra.Command{
Use: "image-builder",
Short: "Amazon EKS Anywhere Image Builder",
Long: `Use image-builder to build your own EKS Anywhere node image`,
}
func init() {
rootCmd.PersistentFlags().IntP("verbosity", "v", 0, "Set the log level verbosity")
if err := viper.BindPFlags(rootCmd.PersistentFlags()); err != nil {
log.Fatalf("failed to bind flags for root: %v", err)
}
}
func Execute() error {
return rootCmd.Execute()
}
| 26 |
eks-anywhere-build-tooling | aws | Go | package cmd
import (
"fmt"
"github.com/spf13/cobra"
)
var version string
var versionCmd = &cobra.Command{
Use: "version",
Short: "Get the image-builder cli version",
Long: "This command prints the version of image-builder cli",
RunE: func(cmd *cobra.Command, args []string) error {
return printVersion()
},
}
func init() {
rootCmd.AddCommand(versionCmd)
}
func printVersion() error {
fmt.Println(version)
return nil
}
| 28 |
eks-anywhere-packages | aws | Go | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package main
import (
"os"
_ "github.com/joho/godotenv/autoload"
"github.com/aws/eks-anywhere-packages/cmd"
)
func main() {
err := cmd.Execute()
if err != nil {
os.Exit(-1)
}
os.Exit(0)
}
| 31 |
eks-anywhere-packages | aws | Go | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Package v1alpha1 contains API Schema definitions for the packages v1alpha1 API group
// +kubebuilder:object:generate=true
// +groupName=packages.eks.amazonaws.com
package v1alpha1
import (
"k8s.io/apimachinery/pkg/runtime/schema"
"sigs.k8s.io/controller-runtime/pkg/scheme"
)
var (
// GroupVersion is group version used to register these objects
GroupVersion = schema.GroupVersion{Group: "packages.eks.amazonaws.com", Version: "v1alpha1"}
// SchemeBuilder is used to add go types to the GroupVersionKind scheme
SchemeBuilder = &scheme.Builder{GroupVersion: GroupVersion}
// AddToScheme adds the types in this group-version to the given scheme.
AddToScheme = SchemeBuilder.AddToScheme
)
| 35 |
eks-anywhere-packages | aws | Go | package v1alpha1
import (
"os"
"strings"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"sigs.k8s.io/yaml"
)
const (
PackageKind = "Package"
PackageNamespace = "eksa-packages"
namespacePrefix = PackageNamespace + "-"
clusterNameEnvVar = "CLUSTER_NAME"
)
func (config *Package) MetaKind() string {
return config.TypeMeta.Kind
}
func (config *Package) ExpectedKind() string {
return PackageKind
}
func NewPackage(packageName string, name, namespace string, config string) Package {
return Package{
TypeMeta: metav1.TypeMeta{
Kind: PackageKind,
},
ObjectMeta: metav1.ObjectMeta{
Name: name,
Namespace: namespace,
},
Spec: PackageSpec{
PackageName: packageName,
Config: config,
},
}
}
// GetValues convert spec values into generic values map
func (config *Package) GetValues() (values map[string]interface{}, err error) {
mapInterfaces := make(map[string]interface{})
err = yaml.Unmarshal([]byte(config.Spec.Config), &mapInterfaces)
return mapInterfaces, err
}
func (config *Package) GetClusterName() string {
if strings.HasPrefix(config.Namespace, namespacePrefix) {
clusterName := strings.TrimPrefix(config.Namespace, namespacePrefix)
return clusterName
}
return ""
}
func (config *Package) IsOldNamespace() bool {
return config.GetClusterName() == ""
}
func (config *Package) IsValidNamespace() bool {
if !strings.HasPrefix(config.Namespace, namespacePrefix) {
if config.Namespace != PackageNamespace {
return false
}
}
return true
}
// IsInstalledOnWorkload returns true if the package is being installed on a workload cluster
// returns false otherwise
func (config *Package) IsInstalledOnWorkload() bool {
clusterName := config.GetClusterName()
managementClusterName := os.Getenv(clusterNameEnvVar)
return managementClusterName != clusterName
}
| 78 |
eks-anywhere-packages | aws | Go | package v1alpha1
import (
"bytes"
"compress/gzip"
"encoding/base64"
"fmt"
"io"
"path"
"strconv"
"strings"
"k8s.io/apimachinery/pkg/version"
)
const (
PackageBundleKind = "PackageBundle"
Latest = "latest"
)
func (config *PackageBundle) MetaKind() string {
return config.TypeMeta.Kind
}
func (config *PackageBundle) ExpectedKind() string {
return PackageBundleKind
}
func (config *PackageBundle) FindPackage(pkgName string) (retPkg BundlePackage, err error) {
for _, pkg := range config.Spec.Packages {
if strings.EqualFold(pkg.Name, pkgName) {
return pkg, nil
}
}
return retPkg, fmt.Errorf("package not found in bundle (%s): %s", config.Name, pkgName)
}
func (config *PackageBundle) GetDependencies(version SourceVersion) (dependencies []BundlePackage, err error) {
for _, dep := range version.Dependencies {
pkg, err := config.FindPackage(dep)
if err != nil {
return nil, err
}
dependencies = append(dependencies, pkg)
}
return dependencies, nil
}
func (config *PackageBundle) FindVersion(pkg BundlePackage, pkgVersion string) (ret SourceVersion, err error) {
source := pkg.Source
for _, packageVersion := range source.Versions {
// We do not sort before getting `latest` because there will be only a single packageVersion per release in normal cases. For edge cases which may require multiple
// versions, the order in the file will be ordered according to what we want `latest` to point to
if packageVersion.Name == pkgVersion || packageVersion.Digest == pkgVersion || pkgVersion == Latest {
return packageVersion, nil
}
}
return ret, fmt.Errorf("package version not found in bundle (%s): %s @ %s", config.Name, pkg.Name, pkgVersion)
}
func (config *PackageBundle) FindOCISourceByName(pkgName string, pkgVersion string) (retSource PackageOCISource, err error) {
pkg, err := config.FindPackage(pkgName)
if err != nil {
return retSource, err
}
return config.FindOCISource(pkg, pkgVersion)
}
func (config *PackageBundle) FindOCISource(pkg BundlePackage, pkgVersion string) (retSource PackageOCISource, err error) {
packageVersion, err := config.FindVersion(pkg, pkgVersion)
if err != nil {
return retSource, err
}
return config.GetOCISource(pkg, packageVersion), nil
}
func (config *PackageBundle) GetOCISource(pkg BundlePackage, packageVersion SourceVersion) (retSource PackageOCISource) {
source := pkg.Source
return PackageOCISource{Registry: source.Registry, Repository: source.Repository, Digest: packageVersion.Digest, Version: packageVersion.Name}
}
// LessThan evaluates if the left calling bundle is less than the supplied parameter
//
// If the left hand side bundle is older than the right hand side, this
// method returns true. If it is newer (greater) it returns false. If they are
// the same it returns false.
func (config PackageBundle) LessThan(rhsBundle *PackageBundle) bool {
lhsMajor, lhsMinor, lhsBuild, _ := config.getMajorMinorBuild()
rhsMajor, rhsMinor, rhsBuild, _ := rhsBundle.getMajorMinorBuild()
return lhsMajor < rhsMajor || lhsMinor < rhsMinor || lhsBuild < rhsBuild
}
// BundlesByVersion implements sort.Interface for PackageBundles.
type BundlesByVersion []PackageBundle
func (b BundlesByVersion) Len() int {
return len(b)
}
func (b BundlesByVersion) Less(i, j int) bool {
return b[i].LessThan(&b[j])
}
func (b BundlesByVersion) Swap(i, j int) {
b[i], b[j] = b[j], b[i]
}
// getMajorMinorBuild returns the Kubernetes major version, Kubernetes minor
// version, and bundle build version.
func (config *PackageBundle) getMajorMinorBuild() (major int, minor int, build int, err error) {
s := strings.Split(config.Name, "-")
s = append(s, "", "", "")
s[0] = strings.TrimPrefix(s[0], "v")
build = 0
minor = 0
major, err = strconv.Atoi(s[0])
if err != nil {
return major, minor, build, fmt.Errorf("invalid major number <%s>", config.Name)
} else {
minor, err = strconv.Atoi(s[1])
if err != nil {
return major, minor, build, fmt.Errorf("invalid minor number <%s>", config.Name)
} else {
build, err = strconv.Atoi(s[2])
if err != nil {
return major, minor, build, fmt.Errorf("invalid build number <%s>", config.Name)
}
}
}
return major, minor, build, err
}
// getMajorMinorFromString returns the Kubernetes major and minor version.
//
// It returns 0, 0 for empty string.
func getMajorMinorFromString(kubeVersion string) (major int, minor int) {
s := strings.Split(kubeVersion, "-")
s = append(s, "", "", "")
s[0] = strings.TrimPrefix(s[0], "v")
major, _ = strconv.Atoi(s[0])
minor, _ = strconv.Atoi(s[1])
return major, minor
}
// KubeVersionMatches returns true if the target Kubernetes matches the
// current bundle's Kubernetes version.
//
// Note the method only compares the major and minor versions of Kubernetes, and
// ignore the patch numbers.
func (config *PackageBundle) KubeVersionMatches(targetKubeVersion *version.Info) (matches bool, err error) {
currKubeMajor, currKubeMinor, _, err := config.getMajorMinorBuild()
if err != nil {
return false, err
}
return fmt.Sprint(currKubeMajor) == targetKubeVersion.Major && fmt.Sprint(currKubeMinor) == targetKubeVersion.Minor, nil
}
// IsValidVersion returns true if the bundle version is valid
func (config *PackageBundle) IsValidVersion() bool {
_, _, _, err := config.getMajorMinorBuild()
return err == nil
}
func (s PackageOCISource) GetChartUri() string {
return "oci://" + path.Join(s.Registry, s.Repository)
}
// PackageMatches returns true if the given source locations match one another.
func (s BundlePackageSource) PackageMatches(other BundlePackageSource) bool {
if s.Registry != other.Registry {
return false
}
if s.Repository != other.Repository {
return false
}
myVersions := make(map[string]struct{})
for _, packageVersion := range s.Versions {
myVersions[packageVersion.Key()] = struct{}{}
}
for _, packageVersion := range other.Versions {
if _, ok := myVersions[packageVersion.Key()]; !ok {
return false
}
}
otherVersions := make(map[string]struct{})
for _, packageVersion := range other.Versions {
otherVersions[packageVersion.Key()] = struct{}{}
}
for key := range myVersions {
if _, ok := otherVersions[key]; !ok {
return false
}
}
return true
}
func (bp *BundlePackage) GetJsonSchema(pkgVersion *SourceVersion) ([]byte, error) {
// The package configuration is gzipped and base64 encoded
// When processing the configuration, the reverse occurs: base64 decode, then unzip
configuration := pkgVersion.Schema
decodedConfiguration, err := base64.StdEncoding.DecodeString(configuration)
if err != nil {
return nil, fmt.Errorf("error decoding configurations %v", err)
}
reader := bytes.NewReader(decodedConfiguration)
gzreader, err := gzip.NewReader(reader)
if err != nil {
return nil, fmt.Errorf("error when uncompressing configurations %v", err)
}
output, err := io.ReadAll(gzreader)
if err != nil {
return nil, fmt.Errorf("error reading configurations %v", err)
}
return output, nil
}
func (v SourceVersion) Key() string {
return v.Name + " " + v.Digest
}
| 226 |
eks-anywhere-packages | aws | Go | package v1alpha1
import "path"
const PackageBundleControllerKind = "PackageBundleController"
func (config *PackageBundleController) MetaKind() string {
return config.TypeMeta.Kind
}
func (config *PackageBundleController) ExpectedKind() string {
return PackageBundleControllerKind
}
func (config *PackageBundleController) IsIgnored() bool {
return config.Namespace != PackageNamespace
}
func (config *PackageBundleController) GetDefaultRegistry() string {
if config.Spec.DefaultRegistry != "" {
return config.Spec.DefaultRegistry
}
return defaultRegistry
}
func (config *PackageBundleController) GetDefaultImageRegistry() string {
if config.Spec.DefaultImageRegistry != "" {
return config.Spec.DefaultImageRegistry
}
return defaultImageRegistry
}
func (config *PackageBundleController) GetBundleURI() (uri string) {
return path.Join(config.GetDefaultRegistry(), config.Spec.BundleRepository)
}
func (config *PackageBundleController) GetActiveBundleURI() (uri string) {
return config.GetBundleURI() + ":" + config.Spec.ActiveBundle
}
| 40 |
eks-anywhere-packages | aws | Go | package v1alpha1_test
import (
"testing"
"github.com/stretchr/testify/assert"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
api "github.com/aws/eks-anywhere-packages/api/v1alpha1"
)
const TestBundleName = "v1-21-1003"
func TestPackageBundleController_IsValid(t *testing.T) {
givenBundleController := func(name string, namespace string) *api.PackageBundleController {
return &api.PackageBundleController{
ObjectMeta: metav1.ObjectMeta{
Name: name,
Namespace: namespace,
},
}
}
assert.False(t, givenBundleController("eksa-packaages-bundle-controller", api.PackageNamespace).IsIgnored())
assert.False(t, givenBundleController("billy", api.PackageNamespace).IsIgnored())
assert.True(t, givenBundleController("eksa-packages-bundle-controller", "default").IsIgnored())
}
func GivenPackageBundleController() *api.PackageBundleController {
return &api.PackageBundleController{
ObjectMeta: metav1.ObjectMeta{
Name: "eksa-packages-bundle-controller",
Namespace: api.PackageNamespace,
},
Spec: api.PackageBundleControllerSpec{
ActiveBundle: TestBundleName,
DefaultRegistry: "public.ecr.aws/l0g8r8j6",
DefaultImageRegistry: "783794618700.dkr.ecr.us-west-2.amazonaws.com",
BundleRepository: "eks-anywhere-packages-bundles",
},
Status: api.PackageBundleControllerStatus{
State: api.BundleControllerStateActive,
},
}
}
func TestPackageBundleController_GetBundleURI(t *testing.T) {
sut := GivenPackageBundleController()
assert.Equal(t, "public.ecr.aws/l0g8r8j6/eks-anywhere-packages-bundles", sut.GetBundleURI())
}
func TestPackageBundleController_GetActiveBundleURI(t *testing.T) {
sut := GivenPackageBundleController()
assert.Equal(t, "public.ecr.aws/l0g8r8j6/eks-anywhere-packages-bundles:v1-21-1003", sut.GetActiveBundleURI())
}
| 56 |
eks-anywhere-packages | aws | Go | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package v1alpha1
import (
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
const (
defaultRegistry = "public.ecr.aws/eks-anywhere"
defaultImageRegistry = "783794618700.dkr.ecr.us-west-2.amazonaws.com"
)
// EDIT THIS FILE! THIS IS SCAFFOLDING FOR YOU TO OWN!
// NOTE: json tags are required. Any new fields you add must have json tags for the fields to be serialized.
// +kubebuilder:object:root=true
// +kubebuilder:subresource:status
// +kubebuilder:webhook:path=/validate-packages-eks-amazonaws-com-v1alpha1-packagebundlecontroller,mutating=false,failurePolicy=fail,sideEffects=None,groups=packages.eks.amazonaws.com,resources=packagebundlecontrollers,verbs=create;update,versions=v1alpha1,name=vpackagebundlecontroller.kb.io,admissionReviewVersions=v1
// +kubebuilder:resource:shortName=pbc,path=packagebundlecontrollers
// +kubebuilder:printcolumn:name="ActiveBundle",type=string,JSONPath=`.spec.activeBundle`
// +kubebuilder:printcolumn:name="State",type=string,JSONPath=`.status.state`
// +kubebuilder:printcolumn:name="Detail",type=string,JSONPath=`.status.detail`
// PackageBundleController is the Schema for the packagebundlecontroller API.
type PackageBundleController struct {
metav1.TypeMeta `json:",inline"`
metav1.ObjectMeta `json:"metadata,omitempty"`
Spec PackageBundleControllerSpec `json:"spec,omitempty"`
Status PackageBundleControllerStatus `json:"status,omitempty"`
}
// PackageBundleControllerSpec defines the desired state of
// PackageBundleController.
type PackageBundleControllerSpec struct {
// LogLevel controls the verbosity of logging in the controller.
// +optional
LogLevel *int32 `json:"logLevel,omitempty"`
// +kubebuilder:default:="24h"
// UpgradeCheckInterval is the time between upgrade checks.
//
// The format is that of time's ParseDuration.
// +optional
UpgradeCheckInterval metav1.Duration `json:"upgradeCheckInterval,omitempty"`
// +kubebuilder:default:="1h"
// UpgradeCheckShortInterval time between upgrade checks if there is a problem.
//
// The format is that of time's ParseDuration.
// +optional
UpgradeCheckShortInterval metav1.Duration `json:"upgradeCheckShortInterval,omitempty"`
// ActiveBundle is name of the bundle from which packages should be sourced.
// +optional
ActiveBundle string `json:"activeBundle"`
// PrivateRegistry is the registry being used for all images, charts and bundles
// +optional
PrivateRegistry string `json:"privateRegistry"`
// +kubebuilder:default:="public.ecr.aws/eks-anywhere"
// DefaultRegistry for pulling helm charts and the bundle
// +optional
DefaultRegistry string `json:"defaultRegistry"`
// +kubebuilder:default:="783794618700.dkr.ecr.us-west-2.amazonaws.com"
// DefaultImageRegistry for pulling images
// +optional
DefaultImageRegistry string `json:"defaultImageRegistry"`
// +kubebuilder:default:="eks-anywhere-packages-bundles"
// Repository portion of an OCI address to the bundle
// +optional
BundleRepository string `json:"bundleRepository"`
// +kubebuilder:default:=false
// Allow target namespace creation by the controller
// +optional
CreateNamespace bool `json:"createNamespace"`
}
// +kubebuilder:validation:Enum=ignored;active;disconnected;upgrade available
type BundleControllerStateEnum string
const (
BundleControllerStateIgnored BundleControllerStateEnum = "ignored"
BundleControllerStateActive BundleControllerStateEnum = "active"
BundleControllerStateUpgradeAvailable BundleControllerStateEnum = "upgrade available"
BundleControllerStateDisconnected BundleControllerStateEnum = "disconnected"
)
// PackageBundleControllerStatus defines the observed state of
// PackageBundleController.
type PackageBundleControllerStatus struct {
// State of the bundle controller.
State BundleControllerStateEnum `json:"state,omitempty"`
// Detail of the state.
Detail string `json:"detail,omitempty"`
// Spec previous settings
Spec PackageBundleControllerSpec `json:"spec,omitempty"`
}
// +kubebuilder:object:root=true
// PackageBundleControllerList contains a list of PackageBundleController.
type PackageBundleControllerList struct {
metav1.TypeMeta `json:",inline"`
metav1.ListMeta `json:"metadata,omitempty"`
Items []PackageBundleController `json:"items"`
}
func init() {
SchemeBuilder.Register(&PackageBundleController{}, &PackageBundleControllerList{})
}
| 129 |
eks-anywhere-packages | aws | Go | package v1alpha1
import (
"sort"
"testing"
"github.com/stretchr/testify/assert"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/version"
)
func TestPackageBundle_Find(t *testing.T) {
var err error
givenBundle := func(versions []SourceVersion) PackageBundle {
return PackageBundle{
Spec: PackageBundleSpec{
Packages: []BundlePackage{
{
Name: "hello-eks-anywhere",
Source: BundlePackageSource{
Registry: "public.ecr.aws/l0g8r8j6",
Repository: "hello-eks-anywhere",
Versions: versions,
},
},
},
},
}
}
sut := givenBundle(
[]SourceVersion{
{
Name: "0.1.0",
Digest: "sha256:eaa07ae1c06ffb563fe3c16cdb317f7ac31c8f829d5f1f32442f0e5ab982c3e7",
},
},
)
expected := PackageOCISource{
Registry: "public.ecr.aws/l0g8r8j6",
Repository: "hello-eks-anywhere",
Digest: "sha256:eaa07ae1c06ffb563fe3c16cdb317f7ac31c8f829d5f1f32442f0e5ab982c3e7",
Version: "0.1.0",
}
actual, err := sut.FindOCISourceByName("hello-eks-anywhere", "0.1.0")
assert.NoError(t, err)
assert.Equal(t, expected, actual)
actual, err = sut.FindOCISourceByName("hello-eks-anywhere", "sha256:eaa07ae1c06ffb563fe3c16cdb317f7ac31c8f829d5f1f32442f0e5ab982c3e7")
assert.NoError(t, err)
assert.Equal(t, expected, actual)
expectedPkgNotFoundErr := "package not found in bundle (fake bundle): Bogus"
sut.ObjectMeta.Name = "fake bundle"
_, err = sut.FindPackage("Bogus")
assert.EqualError(t, err, expectedPkgNotFoundErr)
expectedPkgVersionNotFoundErr := "package version not found in bundle (fake bundle): hello-eks-anywhere @ 9.9.9"
_, err = sut.FindOCISourceByName("hello-eks-anywhere", "9.9.9")
assert.EqualError(t, err, expectedPkgVersionNotFoundErr)
t.Run("Get latest version returns the first item", func(t *testing.T) {
latest := givenBundle(
[]SourceVersion{
{
Name: "0.1.1",
Digest: "sha256:deadbeef",
},
{
Name: "0.1.0",
Digest: "sha256:eaa07ae1c06ffb563fe3c16cdb317f7ac31c8f829d5f1f32442f0e5ab982c3e7",
},
},
)
expected := PackageOCISource{
Registry: "public.ecr.aws/l0g8r8j6",
Repository: "hello-eks-anywhere",
Digest: "sha256:deadbeef",
Version: "0.1.1",
}
actual, err = latest.FindOCISourceByName("hello-eks-anywhere", Latest)
assert.NoError(t, err)
assert.Equal(t, expected, actual)
})
t.Run("Get latest version returns the first item even if the name describes a later version", func(t *testing.T) {
latest := givenBundle(
[]SourceVersion{
{
Name: "0.1.0",
Digest: "sha256:eaa07ae1c06ffb563fe3c16cdb317f7ac31c8f829d5f1f32442f0e5ab982c3e7",
},
{
Name: "0.1.1",
Digest: "sha256:deadbeef",
},
},
)
expected := PackageOCISource{
Registry: "public.ecr.aws/l0g8r8j6",
Repository: "hello-eks-anywhere",
Digest: "sha256:eaa07ae1c06ffb563fe3c16cdb317f7ac31c8f829d5f1f32442f0e5ab982c3e7",
Version: "0.1.0",
}
actual, err = latest.FindOCISourceByName("hello-eks-anywhere", Latest)
assert.NoError(t, err)
assert.Equal(t, expected, actual)
})
}
func TestGetMajorMinorFromString(t *testing.T) {
t.Run("Parse from default Kubernetes version name", func(t *testing.T) {
targetVersion := "v1-21-1"
major, minor := getMajorMinorFromString(targetVersion)
assert.Equal(t, 1, major)
assert.Equal(t, 21, minor)
})
t.Run("Parse from Kubernetes version name without patch number", func(
t *testing.T) {
targetVersion := "v1-21"
major, minor := getMajorMinorFromString(targetVersion)
assert.Equal(t, 1, major)
assert.Equal(t, 21, minor)
})
t.Run("Parse from Kubernetes version name without v perfix", func(
t *testing.T) {
targetVersion := "1-21-1"
major, minor := getMajorMinorFromString(targetVersion)
assert.Equal(t, 1, major)
assert.Equal(t, 21, minor)
})
t.Run("Parse from empty Kubernetes version name", func(t *testing.T) {
targetVersion := ""
major, minor := getMajorMinorFromString(targetVersion)
assert.Equal(t, 0, major)
assert.Equal(t, 0, minor)
})
}
func TestKubeVersionMatches(t *testing.T) {
bundle := PackageBundle{ObjectMeta: metav1.ObjectMeta{
Name: "v1-21-1001"}}
t.Run("Kubernetes version matches", func(t *testing.T) {
var targetVersion = &version.Info{Major: "1", Minor: "21"}
result, err := bundle.KubeVersionMatches(targetVersion)
assert.True(t, result)
assert.NoError(t, err)
})
t.Run("Kubernetes major version doesn't match", func(t *testing.T) {
var targetVersion = &version.Info{Major: "2", Minor: "21"}
result, err := bundle.KubeVersionMatches(targetVersion)
assert.False(t, result)
assert.NoError(t, err)
})
t.Run("Kubernetes minor version doesn't match", func(t *testing.T) {
var targetVersion = &version.Info{Major: "1", Minor: "22"}
result, err := bundle.KubeVersionMatches(targetVersion)
assert.False(t, result)
assert.NoError(t, err)
})
t.Run("bogus major", func(t *testing.T) {
bundle := PackageBundle{ObjectMeta: metav1.ObjectMeta{
Name: "vx-21-1001"}}
var targetVersion = &version.Info{Major: "1", Minor: "21"}
result, err := bundle.KubeVersionMatches(targetVersion)
assert.False(t, result)
assert.EqualError(t, err, "invalid major number <vx-21-1001>")
})
t.Run("bogus minor", func(t *testing.T) {
bundle := PackageBundle{ObjectMeta: metav1.ObjectMeta{
Name: "v1-x-1001"}}
var targetVersion = &version.Info{Major: "1", Minor: "21"}
result, err := bundle.KubeVersionMatches(targetVersion)
assert.False(t, result)
assert.EqualError(t, err, "invalid minor number <v1-x-1001>")
})
t.Run("bogus build", func(t *testing.T) {
bundle := PackageBundle{ObjectMeta: metav1.ObjectMeta{
Name: "v1-21-x"}}
var targetVersion = &version.Info{Major: "1", Minor: "21"}
result, err := bundle.KubeVersionMatches(targetVersion)
assert.False(t, result)
assert.EqualError(t, err, "invalid build number <v1-21-x>")
})
}
func TestIsValidVersion(t *testing.T) {
t.Run("valid version", func(t *testing.T) {
bundle := PackageBundle{ObjectMeta: metav1.ObjectMeta{Name: "v1-21-1001"}}
assert.True(t, bundle.IsValidVersion())
})
t.Run("invalid version", func(t *testing.T) {
bundle := PackageBundle{ObjectMeta: metav1.ObjectMeta{Name: "v1-21-oops"}}
assert.False(t, bundle.IsValidVersion())
})
}
func TestPackageMatches(t *testing.T) {
orig := BundlePackageSource{
Registry: "registry",
Repository: "repository",
Versions: []SourceVersion{
{Name: "v1", Digest: "sha256:deadbeef"},
{Name: "v2", Digest: "sha256:cafebabe"},
},
}
t.Run("package matches", func(t *testing.T) {
other := BundlePackageSource{
Registry: "registry",
Repository: "repository",
Versions: []SourceVersion{
{Name: "v1", Digest: "sha256:deadbeef"},
{Name: "v2", Digest: "sha256:cafebabe"},
},
}
result := orig.PackageMatches(other)
assert.True(t, result)
})
t.Run("package registries must match", func(t *testing.T) {
other := BundlePackageSource{
Registry: "registry2",
Repository: "repository",
Versions: []SourceVersion{
{Name: "v1", Digest: "sha256:deadbeef"},
{Name: "v2", Digest: "sha256:cafebabe"},
},
}
result := orig.PackageMatches(other)
assert.False(t, result)
})
t.Run("package repositories must match", func(t *testing.T) {
other := BundlePackageSource{
Registry: "registry",
Repository: "repository2",
Versions: []SourceVersion{
{Name: "v1", Digest: "sha256:deadbeef"},
{Name: "v2", Digest: "sha256:cafebabe"},
},
}
result := orig.PackageMatches(other)
assert.False(t, result)
})
t.Run("package added versions cause mismatch", func(t *testing.T) {
other := BundlePackageSource{
Registry: "registry",
Repository: "repository",
Versions: []SourceVersion{
{Name: "v1", Digest: "sha256:deadbeef"},
{Name: "v2", Digest: "sha256:cafebabe"},
{Name: "v3", Digest: "sha256:deadf00d"},
},
}
result := orig.PackageMatches(other)
assert.False(t, result)
})
t.Run("package removed versions cause mismatch", func(t *testing.T) {
other := BundlePackageSource{
Registry: "registry",
Repository: "repository",
Versions: []SourceVersion{
{Name: "v2", Digest: "sha256:cafebabe"},
},
}
result := orig.PackageMatches(other)
assert.False(t, result)
})
t.Run("package changed tags cause mismatch", func(t *testing.T) {
other := BundlePackageSource{
Registry: "registry",
Repository: "repository",
Versions: []SourceVersion{
{Name: "v1", Digest: "sha256:feedface"},
{Name: "v2", Digest: "sha256:cafebabe"},
},
}
result := orig.PackageMatches(other)
assert.False(t, result)
})
}
func TestSourceVersionKey(t *testing.T) {
t.Parallel()
s := SourceVersion{
Name: "v1", Digest: "sha256:blah",
}
t.Run("smoke test", func(t *testing.T) {
t.Parallel()
assert.Equal(t, s.Key(), "v1 sha256:blah")
})
t.Run("includes the name", func(t *testing.T) {
t.Parallel()
got := s.Key()
assert.Contains(t, got, "v1")
})
t.Run("includes the tag", func(t *testing.T) {
t.Parallel()
got := s.Key()
assert.Contains(t, got, "sha256:blah")
})
}
func TestIsNewer(t *testing.T) {
t.Parallel()
givenBundle := func(name string) PackageBundle {
return PackageBundle{ObjectMeta: metav1.ObjectMeta{Name: name}}
}
t.Run("less than", func(t *testing.T) {
t.Parallel()
current := givenBundle("v1-21-10002")
candidate := givenBundle("v1-21-10003")
assert.True(t, current.LessThan(&candidate))
})
t.Run("greater than", func(t *testing.T) {
t.Parallel()
current := givenBundle("v1-21-10002")
candidate := givenBundle("v1-21-10001")
assert.False(t, current.LessThan(&candidate))
})
t.Run("equal returns false", func(t *testing.T) {
t.Parallel()
current := givenBundle("v1-21-10002")
candidate := givenBundle("v1-21-10002")
assert.False(t, current.LessThan(&candidate))
})
t.Run("newer kube major version", func(t *testing.T) {
t.Parallel()
current := givenBundle("v1-21-10002")
candidate := givenBundle("v2-21-10002")
assert.True(t, current.LessThan(&candidate))
})
t.Run("newer kube minor version", func(t *testing.T) {
t.Parallel()
current := givenBundle("v1-21-10002")
candidate := givenBundle("v1-22-10002")
assert.True(t, current.LessThan(&candidate))
})
}
func TestGetPackageFromBundle(t *testing.T) {
givenBundle := func(versions []SourceVersion) PackageBundle {
return PackageBundle{
Spec: PackageBundleSpec{
Packages: []BundlePackage{
{
Name: "hello-eks-anywhere",
Source: BundlePackageSource{
Registry: "public.ecr.aws/l0g8r8j6",
Repository: "hello-eks-anywhere",
Versions: versions,
},
},
},
},
}
}
t.Run("Get Package from bundle succeeds", func(t *testing.T) {
bundle := givenBundle(
[]SourceVersion{
{
Name: "0.1.0",
Digest: "sha256:eaa07ae1c06ffb563fe3c16cdb317f7ac31c8f829d5f1f32442f0e5ab982c3e7",
},
},
)
result, err := bundle.FindPackage("hello-eks-anywhere")
assert.NoError(t, err)
assert.Equal(t, bundle.Spec.Packages[0].Name, result.Name)
})
t.Run("Get Package from bundle fails", func(t *testing.T) {
bundle := givenBundle(
[]SourceVersion{
{
Name: "0.1.0",
Digest: "sha256:eaa07ae1c06ffb563fe3c16cdb317f7ac31c8f829d5f1f32442f0e5ab982c3e7",
},
},
)
_, err := bundle.FindPackage("harbor")
assert.NotNil(t, err)
})
}
func TestGetJsonSchemFromBundlePackage(t *testing.T) {
givenBundle := func(versions []SourceVersion) PackageBundle {
return PackageBundle{
Spec: PackageBundleSpec{
Packages: []BundlePackage{
{
Name: "hello-eks-anywhere",
Source: BundlePackageSource{
Versions: versions,
},
},
},
},
}
}
t.Run("Get json schema from bundle succeeds", func(t *testing.T) {
bundle := givenBundle(
[]SourceVersion{
{
Schema: "H4sIAAAAAAAAA5VQvW7DIBDe/RQIdawh9ZgtqjplqZonuOCzTYIBHViRG+XdizGNImWoun7/d9eKMf6iW75lfIjRh62UAxrjajyHGux8GZBQeFBn6DGIhAoY4dtZuASh3CiDGnAEcQrO8tectiKPiQtZF6GjXrYEXZTNptnUb01JWM1RR4PZ+jSiCGafeXc8oYor5sl5pKgxJOaakIQFN5HCL+x1iDTf8YeEhGvb54SMt9jBZOJC+elotBKoSKQz5dOKog+KtI86HZ48h1zIqDSyzhErbxM8e26r9X7jfxbt8s/Zx/7Adn8teXc2grZILDf9tldlAYe21YsWzOfj4zowAatb9QNC+U5rEwIAAA==",
},
},
)
expected := "{\n \"$id\": \"https://hello-eks-anywhere.packages.eks.amazonaws.com/schema.json\",\n \"$schema\": \"https://json-schema.org/draft/2020-12/schema\",\n \"title\": \"hello-eks-anywhere\",\n \"type\": \"object\",\n \"properties\": {\n \"sourceRegistry\": {\n \"type\": \"string\",\n \"default\": \"public.ecr.aws/eks-anywhere\",\n \"description\": \"Source registry for package.\"\n },\n \"title\": {\n \"type\": \"string\",\n \"default\": \"Amazon EKS Anywhere\",\n \"description\": \"Container title.\"\n }\n },\n \"additionalProperties\": false\n}\n"
packageBundle := bundle.Spec.Packages[0]
version := packageBundle.Source.Versions[0]
schema, err := packageBundle.GetJsonSchema(&version)
assert.NoError(t, err)
assert.Equal(t, expected, string(schema))
})
t.Run("Get json schema from bundle fails when not compressed", func(t *testing.T) {
bundle := givenBundle(
[]SourceVersion{
{
Schema: "ewogICIkaWQiOiAiaHR0cHM6Ly9oZWxsby1la3MtYW55d2hlcmUucGFja2FnZXMuZWtzLmFtYXpvbmF3cy5jb20vc2NoZW1hLmpzb24iLAogICIkc2NoZW1hIjogImh0dHBzOi8vanNvbi1zY2hlbWEub3JnL2RyYWZ0LzIwMjAtMTIvc2NoZW1hIiwKICAidGl0bGUiOiAiaGVsbG8tZWtzLWFueXdoZXJlIiwKICAidHlwZSI6ICJvYmplY3QiLAogICJwcm9wZXJ0aWVzIjogewogICAgInNvdXJjZVJlZ2lzdHJ5IjogewogICAgICAidHlwZSI6ICJzdHJpbmciLAogICAgICAiZGVmYXVsdCI6ICJwdWJsaWMuZWNyLmF3cy9la3MtYW55d2hlcmUiLAogICAgICAiZGVzY3JpcHRpb24iOiAiU291cmNlIHJlZ2lzdHJ5IGZvciBwYWNrYWdlLiIKICAgIH0sCiAgICAidGl0bGUiOiB7CiAgICAgICJ0eXBlIjogInN0cmluZyIsCiAgICAgICJkZWZhdWx0IjogIkFtYXpvbiBFS1MgQW55d2hlcmUiLAogICAgICAiZGVzY3JpcHRpb24iOiAiQ29udGFpbmVyIHRpdGxlLiIKICAgIH0KICB9LAp9Cg==",
},
},
)
packageBundle := bundle.Spec.Packages[0]
version := packageBundle.Source.Versions[0]
_, err := packageBundle.GetJsonSchema(&version)
assert.NotNil(t, err)
})
}
func TestBundlesByVersion(t *testing.T) {
t.Run("sort.Interface is implemented", func(t *testing.T) {
bundles := []PackageBundle{
{ObjectMeta: metav1.ObjectMeta{Name: "v1-21-003"}},
{ObjectMeta: metav1.ObjectMeta{Name: "v1-21-001"}},
{ObjectMeta: metav1.ObjectMeta{Name: "v1-21-002"}},
}
sort.Sort(BundlesByVersion(bundles))
assert.Equal(t, bundles[0].Name, "v1-21-001")
assert.Equal(t, bundles[1].Name, "v1-21-002")
assert.Equal(t, bundles[2].Name, "v1-21-003")
})
}
| 514 |
eks-anywhere-packages | aws | Go | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package v1alpha1
import (
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
// +kubebuilder:object:root=true
// +kubebuilder:subresource:status
// +kubebuilder:webhook:path=/validate-packages-eks-amazonaws-com-v1alpha1-packagebundle,mutating=false,failurePolicy=fail,sideEffects=None,groups=packages.eks.amazonaws.com,resources=packagebundles,verbs=create;update,versions=v1alpha1,name=vpackagebundle.kb.io,admissionReviewVersions=v1
// +kubebuilder:printcolumn:name="State",type=string,JSONPath=`.status.state`
// PackageBundle is the Schema for the packagebundle API.
type PackageBundle struct {
metav1.TypeMeta `json:",inline"`
metav1.ObjectMeta `json:"metadata,omitempty"`
Spec PackageBundleSpec `json:"spec,omitempty"`
Status PackageBundleStatus `json:"status,omitempty"`
}
// PackageBundleSpec defines the desired state of PackageBundle.
type PackageBundleSpec struct {
// +kubebuilder:validation:Required
// Packages supported by this bundle.
Packages []BundlePackage `json:"packages"`
// +kubebuilder:validation:Optional
// Minimum required packages controller version
MinVersion string `json:"minControllerVersion"`
}
// BundlePackage specifies a package within a bundle.
type BundlePackage struct {
// +kubebuilder:validation:Required
// Name of the package.
Name string `json:"name,omitempty"`
// +kubebuilder:validation:Required
// Source location for the package (probably a helm chart).
Source BundlePackageSource `json:"source"`
// WorkloadOnly specifies if the package should be installed
// only on the workload cluster
WorkloadOnly bool `json:"workloadonly,omitempty"`
}
// BundlePackageSource identifies the location of a package.
type BundlePackageSource struct {
// +kubebuilder:validation:Optional
// Registry in which the package is found.
Registry string `json:"registry,omitempty"`
// +kubebuilder:validation:Required
// Repository within the Registry where the package is found.
Repository string `json:"repository"`
// +kubebuilder:validation:MinItems=1
// Versions of the package supported by this bundle.
Versions []SourceVersion `json:"versions"`
}
// SourceVersion describes a version of a package within a repository.
type SourceVersion struct {
// +kubebuilder:validation:Required
// Name is a human-friendly description of the version, e.g. "v1.0".
Name string `json:"name"`
// +kubebuilder:validation:Required
// Digest is a checksum value identifying the version of the package and its contents.
Digest string `json:"digest"`
// Images is a list of images used by this version of the package.
Images []VersionImages `json:"images,omitempty"`
// Schema is a base64 encoded, gzipped json schema used to validate package configurations.
Schema string `json:"schema,omitempty"`
// +kubebuilder:validation:Optional
// Dependencies to be installed before the package
Dependencies []string `json:"dependencies,omitempty"`
}
// VersionImages is an image used by a version of a package.
type VersionImages struct {
// +kubebuilder:validation:Required
// Repository within the Registry where the package is found.
Repository string `json:"repository"`
// +kubebuilder:validation:Required
// Digest is a checksum value identifying the version of the package and its contents.
Digest string `json:"digest"`
}
// PackageBundleStatus defines the observed state of PackageBundle.
type PackageBundleStatus struct {
Spec PackageBundleSpec `json:"spec,omitempty"`
State PackageBundleStateEnum `json:"state"`
}
// +kubebuilder:validation:Enum={"available","ignored","invalid","controller upgrade required"}
// PackageBundleStateEnum defines the observed state of PackageBundle.
type PackageBundleStateEnum string
const (
PackageBundleStateAvailable PackageBundleStateEnum = "available"
PackageBundleStateIgnored PackageBundleStateEnum = "ignored"
PackageBundleStateInvalid PackageBundleStateEnum = "invalid"
PackageBundleStateUpgradeRequired PackageBundleStateEnum = "controller upgrade required"
)
// +kubebuilder:object:root=true
// PackageBundleList contains a list of PackageBundle.
type PackageBundleList struct {
metav1.TypeMeta `json:",inline"`
metav1.ListMeta `json:"metadata,omitempty"`
Items []PackageBundle `json:"items"`
}
func init() {
SchemeBuilder.Register(&PackageBundle{}, &PackageBundleList{})
}
| 135 |
eks-anywhere-packages | aws | Go | package v1alpha1_test
import (
"testing"
"github.com/stretchr/testify/assert"
api "github.com/aws/eks-anywhere-packages/api/v1alpha1"
)
func givenPackage(config string) api.Package {
return api.Package{
Spec: api.PackageSpec{Config: config},
}
}
func TestPackage_GetValues(t *testing.T) {
provided := `
make: willys
models:
- mb: "41"
- cj2a:
year: "45"
test: 12
`
expected := map[string]interface{}{
"make": "willys",
"models": []interface{}{
map[string]interface{}{"mb": "41"},
map[string]interface{}{
"cj2a": map[string]interface{}{"year": "45"},
"test": 12.0,
},
},
}
ao := givenPackage(provided)
actual, err := ao.GetValues()
assert.NoError(t, err)
assert.Equal(t, expected, actual)
}
func TestPackage_GetValuesError(t *testing.T) {
provided := `
notactuallyyaml
`
ao := givenPackage(provided)
_, err := ao.GetValues()
assert.EqualError(t, err, "error unmarshaling JSON: while decoding JSON: json: cannot unmarshal string into Go value of type map[string]interface {}")
assert.Contains(t, err.Error(), "error unmarshaling JSON: while decoding JSON: json: cannot unmarshal string into Go value of type map[string]interface {}")
}
func TestPackage_GetClusterName(t *testing.T) {
sut := api.NewPackage("hello-eks-anywhere", "my-hello", "eksa-packages-maggie", "")
assert.Equal(t, "maggie", sut.GetClusterName())
sut.Namespace = "eksa-packages"
assert.Equal(t, "", sut.GetClusterName())
}
func TestPackage_IsOldNamespace(t *testing.T) {
sut := api.NewPackage("hello-eks-anywhere", "my-hello", "eksa-packages-maggie", "")
assert.False(t, sut.IsOldNamespace())
sut.Namespace = "eksa-packages"
assert.True(t, sut.IsOldNamespace())
}
func TestPackage_IsValidNamespace(t *testing.T) {
sut := api.NewPackage("hello-eks-anywhere", "my-hello", "eksa-packages-maggie", "")
assert.True(t, sut.IsValidNamespace())
sut.Namespace = "eksa-packages"
assert.True(t, sut.IsValidNamespace())
sut.Namespace = "default"
assert.False(t, sut.IsValidNamespace())
}
func TestPackage_IsInstalledOnWorkload(t *testing.T) {
t.Setenv("CLUSTER_NAME", "maggie")
sut := api.NewPackage("hello-eks-anywhere", "my-hello", "eksa-packages-maggie", "")
assert.False(t, sut.IsInstalledOnWorkload())
sut.Namespace = "eksa-packages"
assert.True(t, sut.IsInstalledOnWorkload())
sut.Namespace = "default"
assert.True(t, sut.IsInstalledOnWorkload())
sut.Namespace = "eksa-packages-pharrell"
assert.True(t, sut.IsInstalledOnWorkload())
}
| 87 |
eks-anywhere-packages | aws | Go | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package v1alpha1
import (
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
// +kubebuilder:object:root=true
// +kubebuilder:subresource:status
// +kubebuilder:webhook:path=/validate-packages-eks-amazonaws-com-v1alpha1-package,mutating=false,failurePolicy=fail,sideEffects=None,groups=packages.eks.amazonaws.com,resources=packages,verbs=create;update,versions=v1alpha1,name=vpackage.kb.io,admissionReviewVersions=v1
// +kubebuilder:printcolumn:name="Package",type=string,JSONPath=`.spec.packageName`
// +kubebuilder:printcolumn:name="Age",type="date",JSONPath=".metadata.creationTimestamp"
// +kubebuilder:printcolumn:name="State",type=string,JSONPath=`.status.state`
// +kubebuilder:printcolumn:name="CurrentVersion",type=string,JSONPath=`.status.currentVersion`
// +kubebuilder:printcolumn:name="TargetVersion",type=string,JSONPath=`.status.targetVersion`
// +kubebuilder:printcolumn:name="Detail",type=string,JSONPath=`.status.detail`
// Package is the Schema for the package API.
type Package struct {
metav1.TypeMeta `json:",inline"`
metav1.ObjectMeta `json:"metadata,omitempty"`
Spec PackageSpec `json:"spec,omitempty"`
Status PackageStatus `json:"status,omitempty"`
}
// PackageSpec defines the desired state of an package.
type PackageSpec struct {
// PackageName is the name of the package as specified in the bundle.
PackageName string `json:"packageName"`
// PackageVersion is a human-friendly version name or sha256 checksum for the
// package, as specified in the bundle.
PackageVersion string `json:"packageVersion,omitempty"`
// Config for the package.
Config string `json:"config,omitempty"`
// TargetNamespace defines where package resources will be deployed.
TargetNamespace string `json:"targetNamespace,omitempty"`
}
// +kubebuilder:validation:Enum=initializing;installing;installing dependencies;installed;updating;uninstalling;unknown
type StateEnum string
const (
StateInitializing StateEnum = "initializing"
StateInstalling StateEnum = "installing"
StateInstallingDependencies StateEnum = "installing dependencies"
StateInstalled StateEnum = "installed"
StateUpdating StateEnum = "updating"
StateUninstalling StateEnum = "uninstalling"
StateUnknown StateEnum = "unknown"
)
// PackageStatus defines the observed state of Package.
type PackageStatus struct {
// +kubebuilder:validation:Required
// Source associated with the installation.
Source PackageOCISource `json:"source"`
// +kubebuilder:validation:Required
// Version currently installed.
CurrentVersion string `json:"currentVersion"`
// +kubebuilder:validation:Required
// Version to be installed.
TargetVersion string `json:"targetVersion,omitempty"`
// State of the installation.
State StateEnum `json:"state,omitempty"`
// Detail of the state.
Detail string `json:"detail,omitempty"`
// UpgradesAvailable indicates upgraded versions in the bundle.
UpgradesAvailable []PackageAvailableUpgrade `json:"upgradesAvailable,omitempty"`
// Spec previous settings
Spec PackageSpec `json:"spec,omitempty"`
}
type PackageOCISource struct {
// +kubebuilder:validation:Required
// Versions of the package supported.
Version string `json:"version"`
// +kubebuilder:validation:Required
// Registry in which the package is found.
Registry string `json:"registry"`
// +kubebuilder:validation:Required
// Repository within the Registry where the package is found.
Repository string `json:"repository"`
// +kubebuilder:validation:Required
// Digest is a checksum value identifying the version of the package and its contents.
Digest string `json:"digest"`
}
// PackageAvailableUpgrade details the package's available upgrade versions.
type PackageAvailableUpgrade struct {
// +kubebuilder:validation:Required
// Version is a human-friendly version name for the package upgrade.
Version string `json:"version"`
// +kubebuilder:validation:Required
// Tag is a specific version number or sha256 checksum for the package
// upgrade.
Tag string `json:"tag"`
}
// +kubebuilder:object:root=true
// PackageList contains a list of Package.
type PackageList struct {
metav1.TypeMeta `json:",inline"`
metav1.ListMeta `json:"metadata,omitempty"`
Items []Package `json:"items"`
}
func init() {
SchemeBuilder.Register(&Package{}, &PackageList{})
}
| 133 |
eks-anywhere-packages | aws | Go | //go:build !ignore_autogenerated
// +build !ignore_autogenerated
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Code generated by controller-gen. DO NOT EDIT.
package v1alpha1
import (
runtime "k8s.io/apimachinery/pkg/runtime"
)
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *BundlePackage) DeepCopyInto(out *BundlePackage) {
*out = *in
in.Source.DeepCopyInto(&out.Source)
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new BundlePackage.
func (in *BundlePackage) DeepCopy() *BundlePackage {
if in == nil {
return nil
}
out := new(BundlePackage)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *BundlePackageSource) DeepCopyInto(out *BundlePackageSource) {
*out = *in
if in.Versions != nil {
in, out := &in.Versions, &out.Versions
*out = make([]SourceVersion, len(*in))
for i := range *in {
(*in)[i].DeepCopyInto(&(*out)[i])
}
}
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new BundlePackageSource.
func (in *BundlePackageSource) DeepCopy() *BundlePackageSource {
if in == nil {
return nil
}
out := new(BundlePackageSource)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in BundlesByVersion) DeepCopyInto(out *BundlesByVersion) {
{
in := &in
*out = make(BundlesByVersion, len(*in))
for i := range *in {
(*in)[i].DeepCopyInto(&(*out)[i])
}
}
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new BundlesByVersion.
func (in BundlesByVersion) DeepCopy() BundlesByVersion {
if in == nil {
return nil
}
out := new(BundlesByVersion)
in.DeepCopyInto(out)
return *out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *Package) DeepCopyInto(out *Package) {
*out = *in
out.TypeMeta = in.TypeMeta
in.ObjectMeta.DeepCopyInto(&out.ObjectMeta)
out.Spec = in.Spec
in.Status.DeepCopyInto(&out.Status)
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Package.
func (in *Package) DeepCopy() *Package {
if in == nil {
return nil
}
out := new(Package)
in.DeepCopyInto(out)
return out
}
// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
func (in *Package) DeepCopyObject() runtime.Object {
if c := in.DeepCopy(); c != nil {
return c
}
return nil
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *PackageAvailableUpgrade) DeepCopyInto(out *PackageAvailableUpgrade) {
*out = *in
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PackageAvailableUpgrade.
func (in *PackageAvailableUpgrade) DeepCopy() *PackageAvailableUpgrade {
if in == nil {
return nil
}
out := new(PackageAvailableUpgrade)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *PackageBundle) DeepCopyInto(out *PackageBundle) {
*out = *in
out.TypeMeta = in.TypeMeta
in.ObjectMeta.DeepCopyInto(&out.ObjectMeta)
in.Spec.DeepCopyInto(&out.Spec)
in.Status.DeepCopyInto(&out.Status)
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PackageBundle.
func (in *PackageBundle) DeepCopy() *PackageBundle {
if in == nil {
return nil
}
out := new(PackageBundle)
in.DeepCopyInto(out)
return out
}
// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
func (in *PackageBundle) DeepCopyObject() runtime.Object {
if c := in.DeepCopy(); c != nil {
return c
}
return nil
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *PackageBundleController) DeepCopyInto(out *PackageBundleController) {
*out = *in
out.TypeMeta = in.TypeMeta
in.ObjectMeta.DeepCopyInto(&out.ObjectMeta)
in.Spec.DeepCopyInto(&out.Spec)
in.Status.DeepCopyInto(&out.Status)
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PackageBundleController.
func (in *PackageBundleController) DeepCopy() *PackageBundleController {
if in == nil {
return nil
}
out := new(PackageBundleController)
in.DeepCopyInto(out)
return out
}
// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
func (in *PackageBundleController) DeepCopyObject() runtime.Object {
if c := in.DeepCopy(); c != nil {
return c
}
return nil
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *PackageBundleControllerList) DeepCopyInto(out *PackageBundleControllerList) {
*out = *in
out.TypeMeta = in.TypeMeta
in.ListMeta.DeepCopyInto(&out.ListMeta)
if in.Items != nil {
in, out := &in.Items, &out.Items
*out = make([]PackageBundleController, len(*in))
for i := range *in {
(*in)[i].DeepCopyInto(&(*out)[i])
}
}
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PackageBundleControllerList.
func (in *PackageBundleControllerList) DeepCopy() *PackageBundleControllerList {
if in == nil {
return nil
}
out := new(PackageBundleControllerList)
in.DeepCopyInto(out)
return out
}
// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
func (in *PackageBundleControllerList) DeepCopyObject() runtime.Object {
if c := in.DeepCopy(); c != nil {
return c
}
return nil
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *PackageBundleControllerSpec) DeepCopyInto(out *PackageBundleControllerSpec) {
*out = *in
if in.LogLevel != nil {
in, out := &in.LogLevel, &out.LogLevel
*out = new(int32)
**out = **in
}
out.UpgradeCheckInterval = in.UpgradeCheckInterval
out.UpgradeCheckShortInterval = in.UpgradeCheckShortInterval
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PackageBundleControllerSpec.
func (in *PackageBundleControllerSpec) DeepCopy() *PackageBundleControllerSpec {
if in == nil {
return nil
}
out := new(PackageBundleControllerSpec)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *PackageBundleControllerStatus) DeepCopyInto(out *PackageBundleControllerStatus) {
*out = *in
in.Spec.DeepCopyInto(&out.Spec)
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PackageBundleControllerStatus.
func (in *PackageBundleControllerStatus) DeepCopy() *PackageBundleControllerStatus {
if in == nil {
return nil
}
out := new(PackageBundleControllerStatus)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *PackageBundleList) DeepCopyInto(out *PackageBundleList) {
*out = *in
out.TypeMeta = in.TypeMeta
in.ListMeta.DeepCopyInto(&out.ListMeta)
if in.Items != nil {
in, out := &in.Items, &out.Items
*out = make([]PackageBundle, len(*in))
for i := range *in {
(*in)[i].DeepCopyInto(&(*out)[i])
}
}
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PackageBundleList.
func (in *PackageBundleList) DeepCopy() *PackageBundleList {
if in == nil {
return nil
}
out := new(PackageBundleList)
in.DeepCopyInto(out)
return out
}
// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
func (in *PackageBundleList) DeepCopyObject() runtime.Object {
if c := in.DeepCopy(); c != nil {
return c
}
return nil
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *PackageBundleSpec) DeepCopyInto(out *PackageBundleSpec) {
*out = *in
if in.Packages != nil {
in, out := &in.Packages, &out.Packages
*out = make([]BundlePackage, len(*in))
for i := range *in {
(*in)[i].DeepCopyInto(&(*out)[i])
}
}
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PackageBundleSpec.
func (in *PackageBundleSpec) DeepCopy() *PackageBundleSpec {
if in == nil {
return nil
}
out := new(PackageBundleSpec)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *PackageBundleStatus) DeepCopyInto(out *PackageBundleStatus) {
*out = *in
in.Spec.DeepCopyInto(&out.Spec)
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PackageBundleStatus.
func (in *PackageBundleStatus) DeepCopy() *PackageBundleStatus {
if in == nil {
return nil
}
out := new(PackageBundleStatus)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *PackageList) DeepCopyInto(out *PackageList) {
*out = *in
out.TypeMeta = in.TypeMeta
in.ListMeta.DeepCopyInto(&out.ListMeta)
if in.Items != nil {
in, out := &in.Items, &out.Items
*out = make([]Package, len(*in))
for i := range *in {
(*in)[i].DeepCopyInto(&(*out)[i])
}
}
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PackageList.
func (in *PackageList) DeepCopy() *PackageList {
if in == nil {
return nil
}
out := new(PackageList)
in.DeepCopyInto(out)
return out
}
// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
func (in *PackageList) DeepCopyObject() runtime.Object {
if c := in.DeepCopy(); c != nil {
return c
}
return nil
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *PackageOCISource) DeepCopyInto(out *PackageOCISource) {
*out = *in
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PackageOCISource.
func (in *PackageOCISource) DeepCopy() *PackageOCISource {
if in == nil {
return nil
}
out := new(PackageOCISource)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *PackageSpec) DeepCopyInto(out *PackageSpec) {
*out = *in
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PackageSpec.
func (in *PackageSpec) DeepCopy() *PackageSpec {
if in == nil {
return nil
}
out := new(PackageSpec)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *PackageStatus) DeepCopyInto(out *PackageStatus) {
*out = *in
out.Source = in.Source
if in.UpgradesAvailable != nil {
in, out := &in.UpgradesAvailable, &out.UpgradesAvailable
*out = make([]PackageAvailableUpgrade, len(*in))
copy(*out, *in)
}
out.Spec = in.Spec
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new PackageStatus.
func (in *PackageStatus) DeepCopy() *PackageStatus {
if in == nil {
return nil
}
out := new(PackageStatus)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *SourceVersion) DeepCopyInto(out *SourceVersion) {
*out = *in
if in.Images != nil {
in, out := &in.Images, &out.Images
*out = make([]VersionImages, len(*in))
copy(*out, *in)
}
if in.Dependencies != nil {
in, out := &in.Dependencies, &out.Dependencies
*out = make([]string, len(*in))
copy(*out, *in)
}
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new SourceVersion.
func (in *SourceVersion) DeepCopy() *SourceVersion {
if in == nil {
return nil
}
out := new(SourceVersion)
in.DeepCopyInto(out)
return out
}
// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (in *VersionImages) DeepCopyInto(out *VersionImages) {
*out = *in
}
// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new VersionImages.
func (in *VersionImages) DeepCopy() *VersionImages {
if in == nil {
return nil
}
out := new(VersionImages)
in.DeepCopyInto(out)
return out
}
| 444 |
eks-anywhere-packages | aws | Go | package cmd
import (
"context"
"log"
"github.com/go-logr/logr"
"github.com/go-logr/zapr"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
var packageLog logr.Logger
var rootCmd = &cobra.Command{
Use: "package-manager",
Short: "Amazon EKS Anywhere Package Manager",
Long: "Manage Kubernetes packages with EKS Anywhere Curated Packages",
PersistentPreRun: rootPersistentPreRun,
}
func init() {
rootCmd.PersistentFlags().IntP("verbosity", "v", 0, "Set the log level verbosity")
if err := viper.BindPFlags(rootCmd.PersistentFlags()); err != nil {
log.Fatalf("failed to bind flags for root: %v", err)
}
}
func rootPersistentPreRun(_ *cobra.Command, _ []string) {
level := viper.GetInt("verbosity")
cfg := zap.NewDevelopmentConfig()
cfg.Level = zap.NewAtomicLevelAt(zapcore.Level(-1 * level))
cfg.EncoderConfig.EncodeLevel = nil
cfg.DisableCaller = true
cfg.DisableStacktrace = false
cfg.EncoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder
zapLog, err := cfg.Build()
if err != nil {
log.Fatalf("Error initializing logging: %v", err)
}
packageLog = zapr.NewLogger(zapLog)
}
func Execute() error {
return rootCmd.ExecuteContext(context.Background())
}
| 49 |
eks-anywhere-packages | aws | Go | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cmd
import (
"context"
"fmt"
"os"
"github.com/spf13/cobra"
"k8s.io/apimachinery/pkg/runtime"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
clientgoscheme "k8s.io/client-go/kubernetes/scheme"
_ "k8s.io/client-go/plugin/pkg/client/auth"
"sigs.k8s.io/cli-utils/pkg/flowcontrol"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/healthz"
"github.com/aws/eks-anywhere-packages/api/v1alpha1"
"github.com/aws/eks-anywhere-packages/controllers"
pkgConfig "github.com/aws/eks-anywhere-packages/pkg/config"
"github.com/aws/eks-anywhere-packages/pkg/webhook"
)
var scheme = runtime.NewScheme()
type serverContext struct {
metricsAddr string
enableLeaderElection bool
probeAddr string
}
var serverCommandContext = &serverContext{}
func init() {
ctrl.Log.WithName("server")
utilruntime.Must(clientgoscheme.AddToScheme(scheme))
utilruntime.Must(v1alpha1.AddToScheme(scheme))
rootCmd.AddCommand(serverCommand)
serverCommand.Flags().StringVar(&serverCommandContext.metricsAddr, "metrics-bind-address", ":8080",
"The address the metric endpoint binds to.")
serverCommand.Flags().StringVar(&serverCommandContext.probeAddr, "health-probe-bind-address", ":8081",
"The address the probe endpoint binds to.")
serverCommand.Flags().BoolVar(&serverCommandContext.enableLeaderElection, "leader-elect", false,
"Enable leader election for controller manager. "+
"Enabling this will ensure there is only one active controller manager.")
}
func server() error {
ctrl.SetLogger(packageLog)
config := ctrl.GetConfigOrDie()
// Upping the defaults of 20/30 to 75/150 when flowcontrol filter is not enabled.
config.QPS = 75.0
config.Burst = 150
enabled, err := flowcontrol.IsEnabled(context.Background(), config)
packageLog.Info("Starting package controller", "config", pkgConfig.GetGlobalConfig())
if err == nil && enabled {
// Checks if the Kubernetes apiserver has PriorityAndFairness flow control filter enabled
// A negative QPS and Burst indicates that the client should not have a rate limiter.
// Ref: https://github.com/kubernetes/kubernetes/blob/v1.24.0/staging/src/k8s.io/client-go/rest/config.go#L354-L364
config.QPS = -1
config.Burst = -1
}
mgr, err := ctrl.NewManager(config, ctrl.Options{
Scheme: scheme,
MetricsBindAddress: serverCommandContext.metricsAddr,
Port: 9443,
HealthProbeBindAddress: serverCommandContext.probeAddr,
LeaderElection: serverCommandContext.enableLeaderElection,
LeaderElectionID: "6ef7a950.eks.amazonaws.com",
})
if err != nil {
return fmt.Errorf("unable to start manager: %v", err)
}
if err = controllers.RegisterPackageBundleReconciler(mgr); err != nil {
return fmt.Errorf("unable to register package bundle controller: %v", err)
}
if err = controllers.RegisterPackageBundleControllerReconciler(mgr); err != nil {
return fmt.Errorf("unable to register package bundle controller controller: %v", err)
}
if err = controllers.RegisterPackageReconciler(mgr); err != nil {
return fmt.Errorf("unable to register package controller: %v", err)
}
if os.Getenv("ENABLE_WEBHOOKS") == "true" {
if err := webhook.InitPackageBundleValidator(mgr); err != nil {
return fmt.Errorf("unable to create package bundle webhook: %v", err)
}
if err := webhook.InitPackageBundleControllerValidator(mgr); err != nil {
return fmt.Errorf("unable to create package bundle controller webhook: %v", err)
}
if err = webhook.InitPackageValidator(mgr); err != nil {
return fmt.Errorf("unable to create package webhook: %v", err)
}
}
if err := mgr.AddHealthzCheck("healthz", healthz.Ping); err != nil {
return fmt.Errorf("unable to set up health check")
}
if err := mgr.AddReadyzCheck("readyz", healthz.Ping); err != nil {
return fmt.Errorf("unable to set up ready check")
}
packageLog.Info("starting manager")
if err := mgr.Start(ctrl.SetupSignalHandler()); err != nil {
return fmt.Errorf("problem running manager: %v", err)
}
return nil
}
func runServer(_ *cobra.Command, _ []string) {
err := server()
if err != nil {
packageLog.Error(err, "server")
}
}
var serverCommand = &cobra.Command{
Use: "server",
Short: "Run package controller server",
Long: "Run package controller server",
Run: runServer,
}
| 140 |
eks-anywhere-packages | aws | Go | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package controllers
import (
"context"
"fmt"
"time"
"github.com/go-logr/logr"
"k8s.io/apimachinery/pkg/runtime"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
api "github.com/aws/eks-anywhere-packages/api/v1alpha1"
"github.com/aws/eks-anywhere-packages/pkg/artifacts"
"github.com/aws/eks-anywhere-packages/pkg/authenticator"
"github.com/aws/eks-anywhere-packages/pkg/bundle"
"github.com/aws/eks-anywhere-packages/pkg/config"
)
//go:generate mockgen -destination=mocks/client.go -package=mocks sigs.k8s.io/controller-runtime/pkg/client Client,StatusWriter
//go:generate mockgen -destination=mocks/manager.go -package=mocks sigs.k8s.io/controller-runtime/pkg/manager Manager
const (
DefaultUpgradeCheckInterval = time.Hour * 24
packageBundleControllerName = "PackageBundleController"
webhookInitializationRequeueInterval = 10 * time.Second
)
// PackageBundleControllerReconciler reconciles a PackageBundleController object
type PackageBundleControllerReconciler struct {
client.Client
Scheme *runtime.Scheme
bundleManager bundle.Manager
Log logr.Logger
// webhookInitialized allows for faster requeues when the webhook isn't
// yet online.
webhookInitialized bool
}
func NewPackageBundleControllerReconciler(client client.Client,
scheme *runtime.Scheme, bundleManager bundle.Manager,
log logr.Logger) *PackageBundleControllerReconciler {
return &PackageBundleControllerReconciler{
Client: client,
Scheme: scheme,
bundleManager: bundleManager,
Log: log,
}
}
func RegisterPackageBundleControllerReconciler(mgr ctrl.Manager) error {
log := ctrl.Log.WithName(packageBundleControllerName)
bundleClient := bundle.NewManagerClient(mgr.GetClient())
tcc := authenticator.NewTargetClusterClient(log, mgr.GetConfig(), mgr.GetClient())
puller := artifacts.NewRegistryPuller(log)
registryClient := bundle.NewRegistryClient(puller)
bm := bundle.NewBundleManager(log, registryClient, bundleClient, tcc, config.GetGlobalConfig())
reconciler := NewPackageBundleControllerReconciler(mgr.GetClient(),
mgr.GetScheme(), bm, log)
return ctrl.NewControllerManagedBy(mgr).
For(&api.PackageBundleController{}).
Complete(reconciler)
}
//+kubebuilder:rbac:groups=packages.eks.amazonaws.com,resources=packagebundlecontrollers,verbs=get;list;watch;create;update;patch;delete
//+kubebuilder:rbac:groups=packages.eks.amazonaws.com,resources=packagebundlecontrollers/status,verbs=get;update;patch
//+kubebuilder:rbac:groups=packages.eks.amazonaws.com,resources=packagebundlecontrollers/finalizers,verbs=update
// Reconcile is part of the main kubernetes reconciliation loop which aims to
// move the current state of the cluster closer to the desired state.
// the PackageBundleController object against the actual cluster state, and then
// perform operations to make the cluster state reflect the state specified by
// the user.
//
// For more details, check Reconcile and its Result here:
// - https://pkg.go.dev/sigs.k8s.io/[email protected]/pkg/reconcile
func (r *PackageBundleControllerReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
r.Log.V(6).Info("Reconcile:", "PackageBundleController", req.NamespacedName)
result := ctrl.Result{
Requeue: true,
RequeueAfter: DefaultUpgradeCheckInterval,
}
pbc := &api.PackageBundleController{}
err := r.Client.Get(ctx, req.NamespacedName, pbc)
if err != nil {
if client.IgnoreNotFound(err) != nil {
return result, fmt.Errorf("retrieving package bundle controller: %s", err)
}
r.Log.Info("Bundle controller deleted (ignoring)", "bundle controller", req.NamespacedName)
return withoutRequeue(result), nil
}
if pbc.Spec.UpgradeCheckInterval.Duration > 0 {
result.RequeueAfter = pbc.Spec.UpgradeCheckInterval.Duration
}
if pbc.IsIgnored() {
if pbc.Status.State != api.BundleControllerStateIgnored {
pbc.Status.State = api.BundleControllerStateIgnored
r.Log.V(6).Info("update", "PackageBundleController", pbc.Name, "state", pbc.Status.State)
err = r.Client.Status().Update(ctx, pbc, &client.SubResourceUpdateOptions{})
if err != nil {
r.Log.Error(err, "updating ignored status")
return withoutRequeue(result), nil
}
}
return withoutRequeue(result), nil
}
err = r.bundleManager.ProcessBundleController(ctx, pbc)
if err != nil {
if !r.webhookInitialized {
r.Log.Info("delaying reconciliation until webhook is initialized")
result.RequeueAfter = webhookInitializationRequeueInterval
return result, nil
}
r.Log.Error(err, "processing bundle controller")
if pbc.Spec.UpgradeCheckShortInterval.Duration > 0 {
result.RequeueAfter = pbc.Spec.UpgradeCheckShortInterval.Duration
}
return result, nil
}
r.webhookInitialized = true
r.Log.V(6).Info("Reconciled:", "PackageBundleController", req.NamespacedName)
return result, nil
}
// SetupWithManager sets up the controller with the Manager.
func (r *PackageBundleControllerReconciler) SetupWithManager(mgr ctrl.Manager) error {
return ctrl.NewControllerManagedBy(mgr).
For(&api.PackageBundleController{}).
Complete(r)
}
func withoutRequeue(result ctrl.Result) ctrl.Result {
result.Requeue = false
return result
}
| 158 |
eks-anywhere-packages | aws | Go | package controllers
import (
"context"
"fmt"
"testing"
"github.com/go-logr/logr"
"github.com/golang/mock/gomock"
"github.com/stretchr/testify/assert"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/types"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
api "github.com/aws/eks-anywhere-packages/api/v1alpha1"
"github.com/aws/eks-anywhere-packages/controllers/mocks"
mocks2 "github.com/aws/eks-anywhere-packages/pkg/authenticator/mocks"
"github.com/aws/eks-anywhere-packages/pkg/bundle"
bundleMocks "github.com/aws/eks-anywhere-packages/pkg/bundle/mocks"
"github.com/aws/eks-anywhere-packages/pkg/config"
)
const testBundleName = "v1.21-1001"
func givenPackageBundleController() api.PackageBundleController {
return api.PackageBundleController{
ObjectMeta: metav1.ObjectMeta{
Name: "eksa-packages-cluster01",
Namespace: api.PackageNamespace,
},
Spec: api.PackageBundleControllerSpec{
ActiveBundle: testBundleName,
},
Status: api.PackageBundleControllerStatus{
State: api.BundleControllerStateActive,
},
}
}
func TestPackageBundleControllerReconcilerReconcile(t *testing.T) {
t.Parallel()
cfg := config.GetConfig()
tcc := mocks2.NewMockTargetClusterClient(gomock.NewController(t))
rc := bundleMocks.NewMockRegistryClient(gomock.NewController(t))
bc := bundleMocks.NewMockClient(gomock.NewController(t))
bm := bundle.NewBundleManager(logr.Discard(), rc, bc, tcc, cfg)
controllerNN := types.NamespacedName{
Namespace: api.PackageNamespace,
Name: "eksa-packages-cluster01",
}
req := ctrl.Request{
NamespacedName: controllerNN,
}
setMockPBC := func(src *api.PackageBundleController) func(ctx context.Context,
name types.NamespacedName, pbc *api.PackageBundleController, _ ...client.GetOption) error {
return func(ctx context.Context, name types.NamespacedName,
target *api.PackageBundleController, _ ...client.GetOption) error {
src.DeepCopyInto(target)
return nil
}
}
t.Run("happy path", func(t *testing.T) {
t.Parallel()
ctx := context.Background()
mockClient := mocks.NewMockClient(gomock.NewController(t))
pbc := givenPackageBundleController()
mockClient.EXPECT().Get(ctx, req.NamespacedName, gomock.Any()).
DoAndReturn(setMockPBC(&pbc))
mockBundleManager := bundleMocks.NewMockManager(gomock.NewController(t))
mockBundleManager.EXPECT().ProcessBundleController(ctx, &pbc).Return(nil)
r := NewPackageBundleControllerReconciler(mockClient, nil, mockBundleManager,
logr.Discard())
result, err := r.Reconcile(ctx, req)
assert.NoError(t, err)
assert.True(t, result.Requeue)
})
t.Run("bundle manager process bundle controller error", func(t *testing.T) {
t.Parallel()
ctx := context.Background()
mockClient := mocks.NewMockClient(gomock.NewController(t))
pbc := givenPackageBundleController()
mockClient.EXPECT().Get(ctx, req.NamespacedName, gomock.Any()).
DoAndReturn(setMockPBC(&pbc))
mockBundleManager := bundleMocks.NewMockManager(gomock.NewController(t))
mockBundleManager.EXPECT().ProcessBundleController(ctx, &pbc).Return(fmt.Errorf("oops"))
r := NewPackageBundleControllerReconciler(mockClient, nil, mockBundleManager,
logr.Discard())
result, err := r.Reconcile(ctx, req)
assert.NoError(t, err)
assert.True(t, result.Requeue)
})
t.Run("marks status ignored for bogus package bundle controller namespace", func(t *testing.T) {
t.Parallel()
ctx := context.Background()
mockClient := mocks.NewMockClient(gomock.NewController(t))
pbc := givenPackageBundleController()
pbc.Namespace = "bogus"
ignoredController := types.NamespacedName{
Namespace: api.PackageNamespace,
Name: "bogus",
}
mockClient.EXPECT().Get(ctx, ignoredController, gomock.Any()).
DoAndReturn(setMockPBC(&pbc))
mockStatusClient := mocks.NewMockStatusWriter(gomock.NewController(t))
mockClient.EXPECT().Status().Return(mockStatusClient)
mockStatusClient.EXPECT().Update(ctx, gomock.Any(), gomock.Any()).
DoAndReturn(func(ctx context.Context, pbc *api.PackageBundleController,
opts *client.SubResourceUpdateOptions) error {
assert.Equal(t, pbc.Status.State, api.BundleControllerStateIgnored)
return nil
})
r := NewPackageBundleControllerReconciler(mockClient, nil, bm,
logr.Discard())
result, err := r.Reconcile(ctx, ctrl.Request{NamespacedName: ignoredController})
assert.NoError(t, err)
assert.False(t, result.Requeue)
})
t.Run("error marking status ignored for bogus package bundle controller namespace", func(t *testing.T) {
t.Parallel()
ctx := context.Background()
mockClient := mocks.NewMockClient(gomock.NewController(t))
pbc := givenPackageBundleController()
pbc.Namespace = "bogus"
ignoredController := types.NamespacedName{
Namespace: api.PackageNamespace,
Name: "bogus",
}
mockClient.EXPECT().Get(ctx, ignoredController, gomock.Any()).
DoAndReturn(setMockPBC(&pbc))
mockStatusClient := mocks.NewMockStatusWriter(gomock.NewController(t))
mockClient.EXPECT().Status().Return(mockStatusClient)
mockStatusClient.EXPECT().Update(ctx, gomock.Any(), gomock.Any()).Return(fmt.Errorf("oops"))
r := NewPackageBundleControllerReconciler(mockClient, nil, bm,
logr.Discard())
result, err := r.Reconcile(ctx, ctrl.Request{NamespacedName: ignoredController})
assert.NoError(t, err)
assert.False(t, result.Requeue)
})
t.Run("ignore already ignored bogus package bundle controller", func(t *testing.T) {
t.Parallel()
ctx := context.Background()
mockClient := mocks.NewMockClient(gomock.NewController(t))
pbc := givenPackageBundleController()
pbc.Status.State = api.BundleControllerStateIgnored
pbc.Namespace = "bogus"
ignoredController := types.NamespacedName{
Namespace: api.PackageNamespace,
Name: "bogus",
}
mockClient.EXPECT().Get(ctx, ignoredController, gomock.Any()).
DoAndReturn(setMockPBC(&pbc))
r := NewPackageBundleControllerReconciler(mockClient, nil, bm,
logr.Discard())
result, err := r.Reconcile(ctx, ctrl.Request{NamespacedName: ignoredController})
assert.NoError(t, err)
assert.False(t, result.Requeue)
})
t.Run("handles deleted package bundle controllers", func(t *testing.T) {
t.Parallel()
ctx := context.Background()
mockClient := mocks.NewMockClient(gomock.NewController(t))
groupResource := schema.GroupResource{
Group: req.Namespace,
Resource: req.Name,
}
notFoundError := errors.NewNotFound(groupResource, req.Name)
mockClient.EXPECT().Get(ctx, req.NamespacedName, gomock.Any()).
Return(notFoundError)
r := NewPackageBundleControllerReconciler(mockClient, nil, bm,
logr.Discard())
result, err := r.Reconcile(ctx, req)
assert.NoError(t, err)
assert.False(t, result.Requeue)
})
t.Run("get error", func(t *testing.T) {
t.Parallel()
ctx := context.Background()
mockClient := mocks.NewMockClient(gomock.NewController(t))
mockClient.EXPECT().Get(ctx, req.NamespacedName, gomock.Any()).
Return(fmt.Errorf("oops"))
r := NewPackageBundleControllerReconciler(mockClient, nil, bm,
logr.Discard())
result, err := r.Reconcile(ctx, req)
assert.EqualError(t, err, "retrieving package bundle controller: oops")
assert.True(t, result.Requeue)
})
}
| 218 |
eks-anywhere-packages | aws | Go | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package controllers
import (
"context"
"fmt"
"github.com/go-logr/logr"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/builder"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/event"
"sigs.k8s.io/controller-runtime/pkg/handler"
"sigs.k8s.io/controller-runtime/pkg/predicate"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
"sigs.k8s.io/controller-runtime/pkg/source"
api "github.com/aws/eks-anywhere-packages/api/v1alpha1"
"github.com/aws/eks-anywhere-packages/pkg/artifacts"
"github.com/aws/eks-anywhere-packages/pkg/authenticator"
"github.com/aws/eks-anywhere-packages/pkg/bundle"
"github.com/aws/eks-anywhere-packages/pkg/config"
)
const packageBundleName = "PackageBundle"
// PackageBundleReconciler reconciles a PackageBundle object
type PackageBundleReconciler struct {
client.Client
Log logr.Logger
Scheme *runtime.Scheme
bundleClient bundle.Client
registryClient bundle.RegistryClient
bundleManager bundle.Manager
}
func NewPackageBundleReconciler(client client.Client, scheme *runtime.Scheme,
bundleClient bundle.Client, bundleManager bundle.Manager, registryClient bundle.RegistryClient, log logr.Logger) *PackageBundleReconciler {
return &(PackageBundleReconciler{
Client: client,
Scheme: scheme,
Log: log,
bundleClient: bundleClient,
registryClient: registryClient,
bundleManager: bundleManager,
})
}
func RegisterPackageBundleReconciler(mgr ctrl.Manager) error {
log := ctrl.Log.WithName(packageBundleName)
bundleClient := bundle.NewManagerClient(mgr.GetClient())
tcc := authenticator.NewTargetClusterClient(mgr.GetLogger(), mgr.GetConfig(), mgr.GetClient())
puller := artifacts.NewRegistryPuller(log)
registryClient := bundle.NewRegistryClient(puller)
bundleManager := bundle.NewBundleManager(log, registryClient, bundleClient, tcc, config.GetGlobalConfig())
r := NewPackageBundleReconciler(mgr.GetClient(), mgr.GetScheme(), bundleClient, bundleManager, registryClient, log)
return ctrl.NewControllerManagedBy(mgr).
For(&api.PackageBundle{}).
// Watch for changes in the PackageBundleController, and reconcile
// bundles to update state when active bundle changes.
Watches(&source.Kind{Type: &api.PackageBundleController{}},
handler.EnqueueRequestsFromMapFunc(r.mapBundleReconcileRequests)).
// Watch for creation or deletion of other bundles, so bundles can update
// their states accordingly.
Watches(&source.Kind{Type: &api.PackageBundle{}},
handler.EnqueueRequestsFromMapFunc(r.mapBundleReconcileRequests),
builder.WithPredicates(predicate.Funcs{
CreateFunc: func(e event.CreateEvent) bool { return true },
DeleteFunc: func(e event.DeleteEvent) bool { return true },
})).
Complete(r)
}
//+kubebuilder:rbac:groups=packages.eks.amazonaws.com,resources=packagebundles,verbs=get;list;watch;create;update;patch;delete
//+kubebuilder:rbac:groups=packages.eks.amazonaws.com,resources=packagebundles/status,verbs=get;update;patch
//+kubebuilder:rbac:groups=packages.eks.amazonaws.com,resources=packagebundles/finalizers,verbs=update
// Reconcile is part of the main kubernetes reconciliation loop which aims to
// move the current state of the cluster closer to the desired state.
// the PackageBundle object against the actual cluster state, and then perform
// operations to make the cluster state reflect the state specified by the user.
//
// For more details, check Reconcile and its Result here:
// - https://pkg.go.dev/sigs.k8s.io/[email protected]/pkg/reconcile
func (r *PackageBundleReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
r.Log.V(6).Info("Reconcile:", "bundle", req.NamespacedName)
pkgBundle := &api.PackageBundle{}
if err := r.Get(ctx, req.NamespacedName, pkgBundle); err != nil {
if client.IgnoreNotFound(err) != nil {
return ctrl.Result{}, err
}
// ignore deletes
return ctrl.Result{}, nil
}
r.Log.Info("Add/ProcessBundle:", "bundle", req.NamespacedName)
change, err := r.bundleManager.ProcessBundle(ctx, pkgBundle)
if err != nil {
return ctrl.Result{}, fmt.Errorf("package bundle update: %s", err)
}
if change {
err = r.Status().Update(ctx, pkgBundle)
if err != nil {
return ctrl.Result{}, err
}
}
return ctrl.Result{}, nil
}
// mapBundleReconcileRequests generates a reconcile Request for each package bundle in the system.
func (r *PackageBundleReconciler) mapBundleReconcileRequests(_ client.Object) (
requests []reconcile.Request) {
ctx := context.Background()
bundles := &api.PackageBundleList{}
err := r.List(ctx, bundles, &client.ListOptions{Namespace: api.PackageNamespace})
if err != nil {
r.Log.Error(err, "listing package bundles")
return []reconcile.Request{}
}
requests = []reconcile.Request{}
for _, bundle := range bundles.Items {
requests = append(requests, reconcile.Request{
NamespacedName: types.NamespacedName{
Name: bundle.GetName(),
Namespace: bundle.GetNamespace(),
},
})
}
return requests
}
| 151 |
eks-anywhere-packages | aws | Go | package controllers
import (
"context"
"fmt"
"testing"
"github.com/go-logr/logr"
"github.com/golang/mock/gomock"
"github.com/stretchr/testify/assert"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/types"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
api "github.com/aws/eks-anywhere-packages/api/v1alpha1"
"github.com/aws/eks-anywhere-packages/controllers/mocks"
bundleMocks "github.com/aws/eks-anywhere-packages/pkg/bundle/mocks"
"github.com/aws/eks-anywhere-packages/pkg/testutil"
)
func givenRequest() ctrl.Request {
return ctrl.Request{
NamespacedName: types.NamespacedName{
Name: "some-bundle",
Namespace: api.PackageNamespace,
},
}
}
func GivenBundle() *api.PackageBundle {
return &api.PackageBundle{
ObjectMeta: metav1.ObjectMeta{
Name: "v1-22-1001",
Namespace: api.PackageNamespace,
},
Status: api.PackageBundleStatus{
State: api.PackageBundleStateAvailable,
},
}
}
func doAndReturnBundle(src *api.PackageBundle) func(ctx context.Context, name types.NamespacedName, pb *api.PackageBundle, _ ...client.GetOption) error {
return func(ctx context.Context, name types.NamespacedName, target *api.PackageBundle, _ ...client.GetOption) error {
src.DeepCopyInto(target)
return nil
}
}
func TestPackageBundleReconciler_ReconcileAddUpdate(t *testing.T) {
ctx := context.Background()
request := givenRequest()
statusWriter := mocks.NewMockStatusWriter(gomock.NewController(t))
mockClient := mocks.NewMockClient(gomock.NewController(t))
mockBundleClient := bundleMocks.NewMockClient(gomock.NewController(t))
bm := bundleMocks.NewMockManager(gomock.NewController(t))
myBundle := GivenBundle()
mockClient.EXPECT().Get(ctx, request.NamespacedName, gomock.Any()).DoAndReturn(doAndReturnBundle(myBundle))
mockClient.EXPECT().Status().Return(statusWriter)
statusWriter.EXPECT().Update(ctx, gomock.Any(), gomock.Any()).Return(nil)
bm.EXPECT().ProcessBundle(ctx, myBundle).Return(true, nil)
sut := NewPackageBundleReconciler(mockClient, nil, mockBundleClient, bm, nil, logr.Discard())
_, actualError := sut.Reconcile(ctx, request)
assert.Nil(t, actualError)
}
func TestPackageBundleReconciler_ReconcileError(t *testing.T) {
ctx := context.Background()
request := givenRequest()
mockClient := mocks.NewMockClient(gomock.NewController(t))
mockBundleClient := bundleMocks.NewMockClient(gomock.NewController(t))
expectedError := fmt.Errorf("error reading")
mockClient.EXPECT().Get(ctx, request.NamespacedName, gomock.Any()).Return(expectedError)
bm := bundleMocks.NewMockManager(gomock.NewController(t))
sut := NewPackageBundleReconciler(mockClient, nil, mockBundleClient, bm, nil, logr.Discard())
_, actualError := sut.Reconcile(ctx, request)
assert.EqualError(t, actualError, "error reading")
}
func TestPackageBundleReconciler_ReconcileIgnored(t *testing.T) {
ctx := context.Background()
request := givenRequest()
request.Name = "bogus"
mockClient := mocks.NewMockClient(gomock.NewController(t))
mockBundleClient := bundleMocks.NewMockClient(gomock.NewController(t))
bm := bundleMocks.NewMockManager(gomock.NewController(t))
myBundle := GivenBundle()
mockClient.EXPECT().Get(ctx, request.NamespacedName, gomock.Any()).DoAndReturn(doAndReturnBundle(myBundle))
bm.EXPECT().ProcessBundle(ctx, myBundle).Return(false, nil)
sut := NewPackageBundleReconciler(mockClient, nil, mockBundleClient, bm, nil, logr.Discard())
_, actualError := sut.Reconcile(ctx, request)
assert.Nil(t, actualError)
}
func TestPackageBundleReconciler_ReconcileDelete(t *testing.T) {
ctx := context.Background()
request := givenRequest()
groupResource := schema.GroupResource{
Group: request.Namespace,
Resource: request.Name,
}
notFoundError := errors.NewNotFound(groupResource, request.Name)
mockClient := mocks.NewMockClient(gomock.NewController(t))
mockBundleClient := bundleMocks.NewMockClient(gomock.NewController(t))
bm := bundleMocks.NewMockManager(gomock.NewController(t))
mockRegistryClient := bundleMocks.NewMockRegistryClient(gomock.NewController(t))
sut := NewPackageBundleReconciler(mockClient, nil, mockBundleClient, bm, mockRegistryClient, logr.Discard())
mockClient.EXPECT().Get(ctx, request.NamespacedName, gomock.Any()).Return(notFoundError)
_, actualError := sut.Reconcile(ctx, request)
assert.Nil(t, actualError)
}
func TestPackageBundleReconciler_mapBundleReconcileRequests(t *testing.T) {
ctx := context.Background()
bundleOne, err := testutil.GivenPackageBundle("../api/testdata/bundle_one.yaml")
assert.NoError(t, err)
bundleTwo, err := testutil.GivenPackageBundle("../api/testdata/bundle_two.yaml")
assert.NoError(t, err)
mockClient := mocks.NewMockClient(gomock.NewController(t))
mockBundleClient := bundleMocks.NewMockClient(gomock.NewController(t))
mockClient.EXPECT().
List(ctx, gomock.Any(), gomock.Any()).
DoAndReturn(func(ctx context.Context, bundles *api.PackageBundleList,
_ ...*client.ListOptions,
) error {
bundles.Items = []api.PackageBundle{*bundleOne, *bundleTwo}
return nil
})
bm := bundleMocks.NewMockManager(gomock.NewController(t))
sut := NewPackageBundleReconciler(mockClient, nil, mockBundleClient, bm, nil, logr.Discard())
requests := sut.mapBundleReconcileRequests(&api.PackageBundleController{})
assert.Equal(t, 2, len(requests))
}
| 146 |
eks-anywhere-packages | aws | Go | // Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package controllers
import (
"context"
"fmt"
"time"
"github.com/go-logr/logr"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/handler"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
"sigs.k8s.io/controller-runtime/pkg/source"
api "github.com/aws/eks-anywhere-packages/api/v1alpha1"
"github.com/aws/eks-anywhere-packages/pkg/artifacts"
auth "github.com/aws/eks-anywhere-packages/pkg/authenticator"
"github.com/aws/eks-anywhere-packages/pkg/bundle"
"github.com/aws/eks-anywhere-packages/pkg/config"
"github.com/aws/eks-anywhere-packages/pkg/driver"
"github.com/aws/eks-anywhere-packages/pkg/packages"
)
const (
packageName = "Package"
retryLong = time.Second * time.Duration(60)
)
// PackageReconciler reconciles a Package object
type PackageReconciler struct {
client.Client
Log logr.Logger
Scheme *runtime.Scheme
PackageDriver driver.PackageDriver
Manager packages.Manager
bundleManager bundle.Manager
managerClient bundle.Client
}
func NewPackageReconciler(client client.Client, scheme *runtime.Scheme,
driver driver.PackageDriver, manager packages.Manager,
bundleManager bundle.Manager, managerClient bundle.Client,
log logr.Logger) *PackageReconciler {
return &PackageReconciler{
Client: client,
Scheme: scheme,
PackageDriver: driver,
Manager: manager,
bundleManager: bundleManager,
managerClient: managerClient,
Log: log,
}
}
func RegisterPackageReconciler(mgr ctrl.Manager) (err error) {
log := ctrl.Log.WithName(packageName)
manager := packages.NewManager()
cfg := mgr.GetConfig()
secretAuth, err := auth.NewECRSecret(cfg)
if err != nil {
return err
}
tcc := auth.NewTargetClusterClient(log, cfg, mgr.GetClient())
helmDriver := driver.NewHelm(log, secretAuth, tcc)
puller := artifacts.NewRegistryPuller(log)
registryClient := bundle.NewRegistryClient(puller)
managerClient := bundle.NewManagerClient(mgr.GetClient())
bundleManager := bundle.NewBundleManager(log, registryClient, managerClient, tcc, config.GetGlobalConfig())
reconciler := NewPackageReconciler(
mgr.GetClient(),
mgr.GetScheme(),
helmDriver,
manager,
bundleManager,
managerClient,
log,
)
return ctrl.NewControllerManagedBy(mgr).
For(&api.Package{}).
Watches(&source.Kind{Type: &api.PackageBundle{}},
handler.EnqueueRequestsFromMapFunc(reconciler.mapBundleChangesToPackageUpdate)).
Complete(reconciler)
}
func (r *PackageReconciler) mapBundleChangesToPackageUpdate(_ client.Object) (req []reconcile.Request) {
ctx := context.Background()
objs := &api.PackageList{}
err := r.List(ctx, objs, &client.ListOptions{Namespace: api.PackageNamespace})
if err != nil {
return req
}
for _, o := range objs.Items {
req = append(req, reconcile.Request{
NamespacedName: types.NamespacedName{
Namespace: o.GetNamespace(),
Name: o.GetName(),
}})
}
return req
}
//+kubebuilder:rbac:groups=packages.eks.amazonaws.com,resources=packages,verbs=get;list;watch;create;update;patch;delete
//+kubebuilder:rbac:groups=packages.eks.amazonaws.com,resources=packages/status,verbs=get;update;patch
//+kubebuilder:rbac:groups=packages.eks.amazonaws.com,resources=packages/finalizers,verbs=update
//+kubebuilder:rbac:groups="*",resources="*",verbs="*"
// Reconcile is part of the main kubernetes reconciliation loop which aims to
// move the current state of the cluster closer to the desired state.
func (r *PackageReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
r.Log.V(6).Info("Reconcile:", "NamespacedName", req.NamespacedName)
managerContext := packages.NewManagerContext(ctx, r.Log, r.PackageDriver)
managerContext.ManagerClient = r.managerClient
// Get the CRD object from the k8s API.
var err error
if err = r.Get(ctx, req.NamespacedName, &managerContext.Package); err != nil {
if !apierrors.IsNotFound(err) {
return ctrl.Result{}, err
}
managerContext.SetUninstalling(req.Namespace, req.Name)
} else {
pbc, err := r.managerClient.GetPackageBundleController(ctx, managerContext.Package.GetClusterName())
if err != nil {
r.Log.Error(err, "Getting package bundle controller")
managerContext.Package.Status.Detail = err.Error()
if err = r.Status().Update(ctx, &managerContext.Package); err != nil {
return ctrl.Result{RequeueAfter: retryLong}, err
}
return ctrl.Result{RequeueAfter: retryLong}, nil
}
managerContext.PBC = *pbc
bundle, err := r.managerClient.GetActiveBundle(ctx, managerContext.Package.GetClusterName())
if err != nil {
r.Log.Error(err, "Getting active bundle")
managerContext.Package.Status.Detail = err.Error()
if err = r.Status().Update(ctx, &managerContext.Package); err != nil {
return ctrl.Result{RequeueAfter: retryLong}, err
}
return ctrl.Result{RequeueAfter: retryLong}, nil
}
managerContext.Bundle = bundle
targetVersion := managerContext.Package.Spec.PackageVersion
if targetVersion == "" {
targetVersion = api.Latest
}
pkgName := managerContext.Package.Spec.PackageName
pkg, err := bundle.FindPackage(pkgName)
if err != nil {
managerContext.Package.Status.Detail = fmt.Sprintf("Package %s is not in the active bundle (%s).", pkgName, bundle.Name)
r.Log.Info(managerContext.Package.Status.Detail)
if err = r.Status().Update(ctx, &managerContext.Package); err != nil {
return ctrl.Result{RequeueAfter: managerContext.RequeueAfter}, err
}
return ctrl.Result{RequeueAfter: retryLong}, err
}
managerContext.Version, err = bundle.FindVersion(pkg, targetVersion)
if err != nil {
managerContext.Package.Status.Detail = fmt.Sprintf("Package %s@%s is not in the active bundle (%s).", pkgName, targetVersion, bundle.Name)
r.Log.Info(managerContext.Package.Status.Detail)
if err = r.Status().Update(ctx, &managerContext.Package); err != nil {
return ctrl.Result{RequeueAfter: managerContext.RequeueAfter}, err
}
return ctrl.Result{RequeueAfter: retryLong}, err
}
managerContext.Source = bundle.GetOCISource(pkg, managerContext.Version)
managerContext.Package.Status.TargetVersion = printableTargetVersion(managerContext.Source, targetVersion)
}
updateNeeded := r.Manager.Process(managerContext)
if updateNeeded {
r.Log.V(6).Info("Updating status", "namespace", managerContext.Package.Namespace, "name", managerContext.Package.Name, "state", managerContext.Package.Status.State)
if err = r.Status().Update(ctx, &managerContext.Package); err != nil {
return ctrl.Result{RequeueAfter: managerContext.RequeueAfter}, err
}
}
return ctrl.Result{RequeueAfter: managerContext.RequeueAfter}, nil
}
func printableTargetVersion(source api.PackageOCISource, targetVersion string) string {
ret := targetVersion
if targetVersion == api.Latest {
ret = fmt.Sprintf("%s (%s)", source.Version, targetVersion)
}
return ret
}
// SetupWithManager sets up the controller with the Manager.
func (r *PackageReconciler) SetupWithManager(mgr ctrl.Manager) error {
return ctrl.NewControllerManagedBy(mgr).
For(&api.Package{}).
Complete(r)
}
| 221 |
eks-anywhere-packages | aws | Go | package controllers
import (
"context"
"errors"
"fmt"
"testing"
"time"
"github.com/go-logr/logr"
"github.com/golang/mock/gomock"
"github.com/stretchr/testify/assert"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
api "github.com/aws/eks-anywhere-packages/api/v1alpha1"
ctrlmocks "github.com/aws/eks-anywhere-packages/controllers/mocks"
bundleMocks "github.com/aws/eks-anywhere-packages/pkg/bundle/mocks"
drivermocks "github.com/aws/eks-anywhere-packages/pkg/driver/mocks"
"github.com/aws/eks-anywhere-packages/pkg/packages"
packageMocks "github.com/aws/eks-anywhere-packages/pkg/packages/mocks"
)
func TestReconcile(t *testing.T) {
pbc := givenPackageBundleController()
t.Run("happy path", func(t *testing.T) {
tf, ctx := newTestFixtures(t)
tf.bundleClient.EXPECT().GetPackageBundleController(gomock.Any(), "billy").Return(&pbc, nil)
tf.bundleClient.EXPECT().GetActiveBundle(gomock.Any(), "billy").Return(tf.mockBundle(), nil)
fn, pkg := tf.mockGetFnPkg()
tf.ctrlClient.EXPECT().
Get(ctx, gomock.Any(), gomock.AssignableToTypeOf(pkg)).
DoAndReturn(fn)
tf.packageManager.EXPECT().
Process(gomock.Any()).
Return(true)
status := tf.mockStatusWriter()
pkg.Status.TargetVersion = "0.1.1"
status.EXPECT().
Update(ctx, pkg).
Return(nil)
tf.ctrlClient.EXPECT().
Status().
Return(status)
sut := tf.newReconciler()
req := tf.mockRequest()
got, err := sut.Reconcile(ctx, req)
if err != nil {
t.Fatalf("expected no error, got %s", err)
}
expected := time.Duration(0)
assert.Equal(t, expected, got.RequeueAfter)
})
t.Run("happy path no status update", func(t *testing.T) {
tf, ctx := newTestFixtures(t)
tf.bundleClient.EXPECT().GetPackageBundleController(gomock.Any(), "billy").Return(&pbc, nil)
tf.bundleClient.EXPECT().GetActiveBundle(gomock.Any(), "billy").Return(tf.mockBundle(), nil)
fn, pkg := tf.mockGetFnPkg()
tf.ctrlClient.EXPECT().
Get(ctx, gomock.Any(), gomock.AssignableToTypeOf(pkg)).
DoAndReturn(fn)
tf.packageManager.EXPECT().
Process(gomock.Any()).
Return(false)
sut := tf.newReconciler()
req := tf.mockRequest()
got, err := sut.Reconcile(ctx, req)
if err != nil {
t.Fatalf("expected no error, got %s", err)
}
expected := time.Duration(0)
assert.Equal(t, expected, got.RequeueAfter)
})
t.Run("handles errors getting the package", func(t *testing.T) {
tf, ctx := newTestFixtures(t)
testErr := errors.New("getting package test error")
pkg := tf.mockPackage()
tf.ctrlClient.EXPECT().
Get(ctx, gomock.Any(), gomock.AssignableToTypeOf(pkg)).
Return(testErr)
sut := tf.newReconciler()
req := tf.mockRequest()
got, err := sut.Reconcile(ctx, req)
if err == nil || err.Error() != "getting package test error" {
t.Fatalf("expected test error, got nil")
}
expected := time.Duration(0)
assert.Equal(t, expected, got.RequeueAfter)
})
t.Run("handles errors getting the active bundle", func(t *testing.T) {
tf, ctx := newTestFixtures(t)
tf.bundleClient.EXPECT().GetPackageBundleController(gomock.Any(), "billy").Return(&pbc, nil)
testErr := errors.New("active bundle test error")
tf.bundleClient.EXPECT().GetActiveBundle(gomock.Any(), "billy").Return(nil, testErr)
status := tf.mockStatusWriter()
status.EXPECT().Update(ctx, gomock.Any()).Return(nil)
tf.ctrlClient.EXPECT().Status().Return(status)
fn, pkg := tf.mockGetFnPkg()
tf.ctrlClient.EXPECT().
Get(ctx, gomock.Any(), gomock.AssignableToTypeOf(pkg)).
DoAndReturn(fn)
sut := tf.newReconciler()
req := tf.mockRequest()
got, err := sut.Reconcile(ctx, req)
assert.NoError(t, err)
expected := retryLong
assert.Equal(t, expected, got.RequeueAfter)
})
t.Run("status error getting active bundle", func(t *testing.T) {
tf, ctx := newTestFixtures(t)
tf.bundleClient.EXPECT().GetPackageBundleController(gomock.Any(), "billy").Return(&pbc, nil)
testErr := errors.New("active bundle test error")
tf.bundleClient.EXPECT().GetActiveBundle(gomock.Any(), "billy").Return(nil, testErr)
statusErr := errors.New("status update test error")
status := tf.mockStatusWriter()
status.EXPECT().Update(ctx, gomock.Any()).Return(statusErr)
tf.ctrlClient.EXPECT().Status().Return(status)
fn, pkg := tf.mockGetFnPkg()
tf.ctrlClient.EXPECT().
Get(ctx, gomock.Any(), gomock.AssignableToTypeOf(pkg)).
DoAndReturn(fn)
sut := tf.newReconciler()
req := tf.mockRequest()
got, err := sut.Reconcile(ctx, req)
assert.EqualError(t, err, "status update test error")
expected := retryLong
assert.Equal(t, expected, got.RequeueAfter)
})
t.Run("handles errors updating status", func(t *testing.T) {
tf, ctx := newTestFixtures(t)
fn, pkg := tf.mockGetFnPkg()
tf.ctrlClient.EXPECT().
Get(ctx, gomock.Any(), gomock.AssignableToTypeOf(pkg)).
DoAndReturn(fn)
tf.bundleClient.EXPECT().GetPackageBundleController(gomock.Any(), "billy").Return(&pbc, nil)
tf.bundleClient.EXPECT().GetActiveBundle(gomock.Any(), "billy").Return(tf.mockBundle(), nil)
tf.packageManager.EXPECT().
Process(gomock.Any()).
Return(true)
testErr := errors.New("status update test error")
status := tf.mockStatusWriter()
pkg.Status.TargetVersion = "0.1.1"
status.EXPECT().
Update(ctx, pkg).
Return(testErr)
tf.ctrlClient.EXPECT().
Status().
Return(status)
sut := tf.newReconciler()
req := tf.mockRequest()
got, err := sut.Reconcile(ctx, req)
if err == nil || err.Error() != "status update test error" {
t.Fatalf("expected status update test error, got nil")
}
expected := time.Duration(0)
assert.Equal(t, expected, got.RequeueAfter)
})
t.Run("Reports error when requested package version is not in the bundle", func(t *testing.T) {
tf, ctx := newTestFixtures(t)
fn, pkg := tf.mockGetFnPkg()
tf.ctrlClient.EXPECT().
Get(ctx, gomock.Any(), gomock.AssignableToTypeOf(pkg)).
DoAndReturn(fn)
tf.bundleClient.EXPECT().GetPackageBundleController(gomock.Any(), "billy").Return(&pbc, nil)
newBundle := tf.mockBundle()
newBundle.ObjectMeta.Name = "fake bundle"
tf.bundleClient.EXPECT().GetActiveBundle(gomock.Any(), "billy").Return(newBundle, nil)
testErr := errors.New("status update test error")
status := tf.mockStatusWriter()
pkg.Spec.PackageVersion = "2.0.0"
pkg.Status.TargetVersion = "2.0.0"
pkg.Status.Detail = fmt.Sprintf("Package %s@%s is not in the active bundle (%s).", pkg.Spec.PackageName, pkg.Spec.PackageVersion, "fake bundle")
status.EXPECT().
Update(ctx, pkg).
Return(testErr)
tf.ctrlClient.EXPECT().
Status().
Return(status)
sut := tf.newReconciler()
req := tf.mockRequest()
got, err := sut.Reconcile(ctx, req)
assert.EqualError(t, err, "status update test error")
expected := time.Duration(0)
assert.Equal(t, expected, got.RequeueAfter)
})
t.Run("Packages without version hold upgrade to latest", func(t *testing.T) {
tf, ctx := newTestFixtures(t)
fn, pkg := tf.mockGetFnPkg()
tf.ctrlClient.EXPECT().
Get(ctx, gomock.Any(), gomock.Any()).
DoAndReturn(fn).Times(2)
pkg.Spec.PackageVersion = ""
tf.bundleClient.EXPECT().GetPackageBundleController(gomock.Any(), "billy").Return(&pbc, nil)
tf.bundleClient.EXPECT().GetActiveBundle(gomock.Any(), "billy").Return(tf.mockBundle(), nil)
newBundle := tf.mockBundle()
newBundle.Spec.Packages[0].Source.Versions = []api.SourceVersion{{
Name: "0.2.0",
Digest: "sha256:deadbeef020",
}}
tf.bundleClient.EXPECT().GetPackageBundleController(gomock.Any(), "billy").Return(&pbc, nil)
tf.bundleClient.EXPECT().GetActiveBundle(gomock.Any(), "billy").Return(newBundle, nil)
tf.packageManager.EXPECT().
Process(gomock.Any()).
Return(false).Do(func(mctx *packages.ManagerContext) {
assert.Equal(t,
api.PackageOCISource(api.PackageOCISource{Version: "0.1.1", Registry: "public.ecr.aws/l0g8r8j6", Repository: "hello-eks-anywhere", Digest: "sha256:deadbeef"}),
mctx.Source)
})
sut := tf.newReconciler()
req := tf.mockRequest()
got, err := sut.Reconcile(ctx, req)
assert.NoError(t, err)
expected := time.Duration(0)
assert.Equal(t, expected, got.RequeueAfter)
tf.packageManager.EXPECT().
Process(gomock.Any()).
Return(false).Do(func(mctx *packages.ManagerContext) {
assert.Equal(t,
api.PackageOCISource(api.PackageOCISource{Version: "0.2.0", Registry: "public.ecr.aws/l0g8r8j6", Repository: "hello-eks-anywhere", Digest: "sha256:deadbeef020"}),
mctx.Source)
})
got, err = sut.Reconcile(ctx, req)
assert.NoError(t, err)
expected = time.Duration(0)
assert.Equal(t, expected, got.RequeueAfter)
})
}
//
// Test helpers
//
const (
name string = "Yoda"
namespace string = "eksa-packages"
)
type testFixtures struct {
gomockController *gomock.Controller
logger logr.Logger
ctrlClient *ctrlmocks.MockClient
packageDriver *drivermocks.MockPackageDriver
packageManager *packageMocks.MockManager
bundleManager *bundleMocks.MockManager
bundleClient *bundleMocks.MockClient
}
// newTestFixtures helps remove repetition in the tests by instantiating a lot of
// commonly used structures and mocks.
func newTestFixtures(t *testing.T) (*testFixtures, context.Context) {
gomockController := gomock.NewController(t)
return &testFixtures{
gomockController: gomockController,
logger: logr.Discard(),
ctrlClient: ctrlmocks.NewMockClient(gomockController),
packageDriver: drivermocks.NewMockPackageDriver(gomockController),
packageManager: packageMocks.NewMockManager(gomockController),
bundleManager: bundleMocks.NewMockManager(gomockController),
bundleClient: bundleMocks.NewMockClient(gomockController),
}, context.Background()
}
func (tf *testFixtures) mockPackage() *api.Package {
return &api.Package{
TypeMeta: metav1.TypeMeta{
Kind: "Package",
},
ObjectMeta: metav1.ObjectMeta{
Name: "my-package",
Namespace: "eksa-packages-billy",
},
Spec: api.PackageSpec{
PackageName: "hello-eks-anywhere",
PackageVersion: "0.1.1",
Config: `
config:
foo: foo
secret:
bar: bar
`,
},
}
}
func (tf *testFixtures) mockBundle() *api.PackageBundle {
return &api.PackageBundle{
Spec: api.PackageBundleSpec{
Packages: []api.BundlePackage{
{
Name: "hello-eks-anywhere",
Source: api.BundlePackageSource{
Registry: "public.ecr.aws/l0g8r8j6",
Repository: "hello-eks-anywhere",
Versions: []api.SourceVersion{
{Name: "0.1.1", Digest: "sha256:deadbeef"},
{Name: "0.1.0", Digest: "sha256:cafebabe"},
},
},
},
},
},
}
}
func (tf *testFixtures) mockRequest() ctrl.Request {
return ctrl.Request{
NamespacedName: types.NamespacedName{
Name: name,
Namespace: namespace,
},
}
}
func (tf *testFixtures) newReconciler() *PackageReconciler {
// copy these default values
mockCtrlClient := tf.ctrlClient
mockPackageDriver := tf.packageDriver
mockPackageManager := tf.packageManager
mockBundleManager := tf.bundleManager
mockBundleClient := tf.bundleClient
return &PackageReconciler{
Client: mockCtrlClient,
Scheme: nil,
Log: tf.logger,
PackageDriver: mockPackageDriver,
Manager: mockPackageManager,
bundleManager: mockBundleManager,
managerClient: mockBundleClient,
}
}
type getFnPkg func(context.Context, types.NamespacedName, *api.Package, ...client.GetOption) error
func (tf *testFixtures) mockGetFnPkg() (getFnPkg, *api.Package) {
pkg := tf.mockPackage()
return func(ctx context.Context, name types.NamespacedName,
target *api.Package,
_ ...client.GetOption,
) error {
pkg.DeepCopyInto(target)
return nil
}, pkg
}
func (tf *testFixtures) mockStatusWriter() *ctrlmocks.MockStatusWriter {
return ctrlmocks.NewMockStatusWriter(tf.gomockController)
}
| 400 |
eks-anywhere-packages | aws | Go | // Code generated by MockGen. DO NOT EDIT.
// Source: sigs.k8s.io/controller-runtime/pkg/client (interfaces: Client,StatusWriter)
// Package mocks is a generated GoMock package.
package mocks
import (
context "context"
reflect "reflect"
gomock "github.com/golang/mock/gomock"
meta "k8s.io/apimachinery/pkg/api/meta"
runtime "k8s.io/apimachinery/pkg/runtime"
types "k8s.io/apimachinery/pkg/types"
client "sigs.k8s.io/controller-runtime/pkg/client"
)
// MockClient is a mock of Client interface.
type MockClient struct {
ctrl *gomock.Controller
recorder *MockClientMockRecorder
}
// MockClientMockRecorder is the mock recorder for MockClient.
type MockClientMockRecorder struct {
mock *MockClient
}
// NewMockClient creates a new mock instance.
func NewMockClient(ctrl *gomock.Controller) *MockClient {
mock := &MockClient{ctrl: ctrl}
mock.recorder = &MockClientMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockClient) EXPECT() *MockClientMockRecorder {
return m.recorder
}
// Create mocks base method.
func (m *MockClient) Create(arg0 context.Context, arg1 client.Object, arg2 ...client.CreateOption) error {
m.ctrl.T.Helper()
varargs := []interface{}{arg0, arg1}
for _, a := range arg2 {
varargs = append(varargs, a)
}
ret := m.ctrl.Call(m, "Create", varargs...)
ret0, _ := ret[0].(error)
return ret0
}
// Create indicates an expected call of Create.
func (mr *MockClientMockRecorder) Create(arg0, arg1 interface{}, arg2 ...interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
varargs := append([]interface{}{arg0, arg1}, arg2...)
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Create", reflect.TypeOf((*MockClient)(nil).Create), varargs...)
}
// Delete mocks base method.
func (m *MockClient) Delete(arg0 context.Context, arg1 client.Object, arg2 ...client.DeleteOption) error {
m.ctrl.T.Helper()
varargs := []interface{}{arg0, arg1}
for _, a := range arg2 {
varargs = append(varargs, a)
}
ret := m.ctrl.Call(m, "Delete", varargs...)
ret0, _ := ret[0].(error)
return ret0
}
// Delete indicates an expected call of Delete.
func (mr *MockClientMockRecorder) Delete(arg0, arg1 interface{}, arg2 ...interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
varargs := append([]interface{}{arg0, arg1}, arg2...)
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Delete", reflect.TypeOf((*MockClient)(nil).Delete), varargs...)
}
// DeleteAllOf mocks base method.
func (m *MockClient) DeleteAllOf(arg0 context.Context, arg1 client.Object, arg2 ...client.DeleteAllOfOption) error {
m.ctrl.T.Helper()
varargs := []interface{}{arg0, arg1}
for _, a := range arg2 {
varargs = append(varargs, a)
}
ret := m.ctrl.Call(m, "DeleteAllOf", varargs...)
ret0, _ := ret[0].(error)
return ret0
}
// DeleteAllOf indicates an expected call of DeleteAllOf.
func (mr *MockClientMockRecorder) DeleteAllOf(arg0, arg1 interface{}, arg2 ...interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
varargs := append([]interface{}{arg0, arg1}, arg2...)
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteAllOf", reflect.TypeOf((*MockClient)(nil).DeleteAllOf), varargs...)
}
// Get mocks base method.
func (m *MockClient) Get(arg0 context.Context, arg1 types.NamespacedName, arg2 client.Object, arg3 ...client.GetOption) error {
m.ctrl.T.Helper()
varargs := []interface{}{arg0, arg1, arg2}
for _, a := range arg3 {
varargs = append(varargs, a)
}
ret := m.ctrl.Call(m, "Get", varargs...)
ret0, _ := ret[0].(error)
return ret0
}
// Get indicates an expected call of Get.
func (mr *MockClientMockRecorder) Get(arg0, arg1, arg2 interface{}, arg3 ...interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
varargs := append([]interface{}{arg0, arg1, arg2}, arg3...)
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Get", reflect.TypeOf((*MockClient)(nil).Get), varargs...)
}
// List mocks base method.
func (m *MockClient) List(arg0 context.Context, arg1 client.ObjectList, arg2 ...client.ListOption) error {
m.ctrl.T.Helper()
varargs := []interface{}{arg0, arg1}
for _, a := range arg2 {
varargs = append(varargs, a)
}
ret := m.ctrl.Call(m, "List", varargs...)
ret0, _ := ret[0].(error)
return ret0
}
// List indicates an expected call of List.
func (mr *MockClientMockRecorder) List(arg0, arg1 interface{}, arg2 ...interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
varargs := append([]interface{}{arg0, arg1}, arg2...)
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "List", reflect.TypeOf((*MockClient)(nil).List), varargs...)
}
// Patch mocks base method.
func (m *MockClient) Patch(arg0 context.Context, arg1 client.Object, arg2 client.Patch, arg3 ...client.PatchOption) error {
m.ctrl.T.Helper()
varargs := []interface{}{arg0, arg1, arg2}
for _, a := range arg3 {
varargs = append(varargs, a)
}
ret := m.ctrl.Call(m, "Patch", varargs...)
ret0, _ := ret[0].(error)
return ret0
}
// Patch indicates an expected call of Patch.
func (mr *MockClientMockRecorder) Patch(arg0, arg1, arg2 interface{}, arg3 ...interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
varargs := append([]interface{}{arg0, arg1, arg2}, arg3...)
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Patch", reflect.TypeOf((*MockClient)(nil).Patch), varargs...)
}
// RESTMapper mocks base method.
func (m *MockClient) RESTMapper() meta.RESTMapper {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "RESTMapper")
ret0, _ := ret[0].(meta.RESTMapper)
return ret0
}
// RESTMapper indicates an expected call of RESTMapper.
func (mr *MockClientMockRecorder) RESTMapper() *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RESTMapper", reflect.TypeOf((*MockClient)(nil).RESTMapper))
}
// Scheme mocks base method.
func (m *MockClient) Scheme() *runtime.Scheme {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Scheme")
ret0, _ := ret[0].(*runtime.Scheme)
return ret0
}
// Scheme indicates an expected call of Scheme.
func (mr *MockClientMockRecorder) Scheme() *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Scheme", reflect.TypeOf((*MockClient)(nil).Scheme))
}
// Status mocks base method.
func (m *MockClient) Status() client.SubResourceWriter {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Status")
ret0, _ := ret[0].(client.SubResourceWriter)
return ret0
}
// Status indicates an expected call of Status.
func (mr *MockClientMockRecorder) Status() *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Status", reflect.TypeOf((*MockClient)(nil).Status))
}
// SubResource mocks base method.
func (m *MockClient) SubResource(arg0 string) client.SubResourceClient {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "SubResource", arg0)
ret0, _ := ret[0].(client.SubResourceClient)
return ret0
}
// SubResource indicates an expected call of SubResource.
func (mr *MockClientMockRecorder) SubResource(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SubResource", reflect.TypeOf((*MockClient)(nil).SubResource), arg0)
}
// Update mocks base method.
func (m *MockClient) Update(arg0 context.Context, arg1 client.Object, arg2 ...client.UpdateOption) error {
m.ctrl.T.Helper()
varargs := []interface{}{arg0, arg1}
for _, a := range arg2 {
varargs = append(varargs, a)
}
ret := m.ctrl.Call(m, "Update", varargs...)
ret0, _ := ret[0].(error)
return ret0
}
// Update indicates an expected call of Update.
func (mr *MockClientMockRecorder) Update(arg0, arg1 interface{}, arg2 ...interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
varargs := append([]interface{}{arg0, arg1}, arg2...)
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Update", reflect.TypeOf((*MockClient)(nil).Update), varargs...)
}
// MockStatusWriter is a mock of StatusWriter interface.
type MockStatusWriter struct {
ctrl *gomock.Controller
recorder *MockStatusWriterMockRecorder
}
// MockStatusWriterMockRecorder is the mock recorder for MockStatusWriter.
type MockStatusWriterMockRecorder struct {
mock *MockStatusWriter
}
// NewMockStatusWriter creates a new mock instance.
func NewMockStatusWriter(ctrl *gomock.Controller) *MockStatusWriter {
mock := &MockStatusWriter{ctrl: ctrl}
mock.recorder = &MockStatusWriterMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockStatusWriter) EXPECT() *MockStatusWriterMockRecorder {
return m.recorder
}
// Create mocks base method.
func (m *MockStatusWriter) Create(arg0 context.Context, arg1, arg2 client.Object, arg3 ...client.SubResourceCreateOption) error {
m.ctrl.T.Helper()
varargs := []interface{}{arg0, arg1, arg2}
for _, a := range arg3 {
varargs = append(varargs, a)
}
ret := m.ctrl.Call(m, "Create", varargs...)
ret0, _ := ret[0].(error)
return ret0
}
// Create indicates an expected call of Create.
func (mr *MockStatusWriterMockRecorder) Create(arg0, arg1, arg2 interface{}, arg3 ...interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
varargs := append([]interface{}{arg0, arg1, arg2}, arg3...)
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Create", reflect.TypeOf((*MockStatusWriter)(nil).Create), varargs...)
}
// Patch mocks base method.
func (m *MockStatusWriter) Patch(arg0 context.Context, arg1 client.Object, arg2 client.Patch, arg3 ...client.SubResourcePatchOption) error {
m.ctrl.T.Helper()
varargs := []interface{}{arg0, arg1, arg2}
for _, a := range arg3 {
varargs = append(varargs, a)
}
ret := m.ctrl.Call(m, "Patch", varargs...)
ret0, _ := ret[0].(error)
return ret0
}
// Patch indicates an expected call of Patch.
func (mr *MockStatusWriterMockRecorder) Patch(arg0, arg1, arg2 interface{}, arg3 ...interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
varargs := append([]interface{}{arg0, arg1, arg2}, arg3...)
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Patch", reflect.TypeOf((*MockStatusWriter)(nil).Patch), varargs...)
}
// Update mocks base method.
func (m *MockStatusWriter) Update(arg0 context.Context, arg1 client.Object, arg2 ...client.SubResourceUpdateOption) error {
m.ctrl.T.Helper()
varargs := []interface{}{arg0, arg1}
for _, a := range arg2 {
varargs = append(varargs, a)
}
ret := m.ctrl.Call(m, "Update", varargs...)
ret0, _ := ret[0].(error)
return ret0
}
// Update indicates an expected call of Update.
func (mr *MockStatusWriterMockRecorder) Update(arg0, arg1 interface{}, arg2 ...interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
varargs := append([]interface{}{arg0, arg1}, arg2...)
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Update", reflect.TypeOf((*MockStatusWriter)(nil).Update), varargs...)
}
| 309 |
eks-anywhere-packages | aws | Go | // Code generated by MockGen. DO NOT EDIT.
// Source: sigs.k8s.io/controller-runtime/pkg/manager (interfaces: Manager)
// Package mocks is a generated GoMock package.
package mocks
import (
context "context"
http "net/http"
reflect "reflect"
logr "github.com/go-logr/logr"
gomock "github.com/golang/mock/gomock"
meta "k8s.io/apimachinery/pkg/api/meta"
runtime "k8s.io/apimachinery/pkg/runtime"
rest "k8s.io/client-go/rest"
record "k8s.io/client-go/tools/record"
cache "sigs.k8s.io/controller-runtime/pkg/cache"
client "sigs.k8s.io/controller-runtime/pkg/client"
v1alpha1 "sigs.k8s.io/controller-runtime/pkg/config/v1alpha1"
healthz "sigs.k8s.io/controller-runtime/pkg/healthz"
manager "sigs.k8s.io/controller-runtime/pkg/manager"
webhook "sigs.k8s.io/controller-runtime/pkg/webhook"
)
// MockManager is a mock of Manager interface.
type MockManager struct {
ctrl *gomock.Controller
recorder *MockManagerMockRecorder
}
// MockManagerMockRecorder is the mock recorder for MockManager.
type MockManagerMockRecorder struct {
mock *MockManager
}
// NewMockManager creates a new mock instance.
func NewMockManager(ctrl *gomock.Controller) *MockManager {
mock := &MockManager{ctrl: ctrl}
mock.recorder = &MockManagerMockRecorder{mock}
return mock
}
// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockManager) EXPECT() *MockManagerMockRecorder {
return m.recorder
}
// Add mocks base method.
func (m *MockManager) Add(arg0 manager.Runnable) error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Add", arg0)
ret0, _ := ret[0].(error)
return ret0
}
// Add indicates an expected call of Add.
func (mr *MockManagerMockRecorder) Add(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Add", reflect.TypeOf((*MockManager)(nil).Add), arg0)
}
// AddHealthzCheck mocks base method.
func (m *MockManager) AddHealthzCheck(arg0 string, arg1 healthz.Checker) error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "AddHealthzCheck", arg0, arg1)
ret0, _ := ret[0].(error)
return ret0
}
// AddHealthzCheck indicates an expected call of AddHealthzCheck.
func (mr *MockManagerMockRecorder) AddHealthzCheck(arg0, arg1 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddHealthzCheck", reflect.TypeOf((*MockManager)(nil).AddHealthzCheck), arg0, arg1)
}
// AddMetricsExtraHandler mocks base method.
func (m *MockManager) AddMetricsExtraHandler(arg0 string, arg1 http.Handler) error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "AddMetricsExtraHandler", arg0, arg1)
ret0, _ := ret[0].(error)
return ret0
}
// AddMetricsExtraHandler indicates an expected call of AddMetricsExtraHandler.
func (mr *MockManagerMockRecorder) AddMetricsExtraHandler(arg0, arg1 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddMetricsExtraHandler", reflect.TypeOf((*MockManager)(nil).AddMetricsExtraHandler), arg0, arg1)
}
// AddReadyzCheck mocks base method.
func (m *MockManager) AddReadyzCheck(arg0 string, arg1 healthz.Checker) error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "AddReadyzCheck", arg0, arg1)
ret0, _ := ret[0].(error)
return ret0
}
// AddReadyzCheck indicates an expected call of AddReadyzCheck.
func (mr *MockManagerMockRecorder) AddReadyzCheck(arg0, arg1 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddReadyzCheck", reflect.TypeOf((*MockManager)(nil).AddReadyzCheck), arg0, arg1)
}
// Elected mocks base method.
func (m *MockManager) Elected() <-chan struct{} {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Elected")
ret0, _ := ret[0].(<-chan struct{})
return ret0
}
// Elected indicates an expected call of Elected.
func (mr *MockManagerMockRecorder) Elected() *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Elected", reflect.TypeOf((*MockManager)(nil).Elected))
}
// GetAPIReader mocks base method.
func (m *MockManager) GetAPIReader() client.Reader {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "GetAPIReader")
ret0, _ := ret[0].(client.Reader)
return ret0
}
// GetAPIReader indicates an expected call of GetAPIReader.
func (mr *MockManagerMockRecorder) GetAPIReader() *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetAPIReader", reflect.TypeOf((*MockManager)(nil).GetAPIReader))
}
// GetCache mocks base method.
func (m *MockManager) GetCache() cache.Cache {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "GetCache")
ret0, _ := ret[0].(cache.Cache)
return ret0
}
// GetCache indicates an expected call of GetCache.
func (mr *MockManagerMockRecorder) GetCache() *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetCache", reflect.TypeOf((*MockManager)(nil).GetCache))
}
// GetClient mocks base method.
func (m *MockManager) GetClient() client.Client {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "GetClient")
ret0, _ := ret[0].(client.Client)
return ret0
}
// GetClient indicates an expected call of GetClient.
func (mr *MockManagerMockRecorder) GetClient() *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetClient", reflect.TypeOf((*MockManager)(nil).GetClient))
}
// GetConfig mocks base method.
func (m *MockManager) GetConfig() *rest.Config {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "GetConfig")
ret0, _ := ret[0].(*rest.Config)
return ret0
}
// GetConfig indicates an expected call of GetConfig.
func (mr *MockManagerMockRecorder) GetConfig() *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetConfig", reflect.TypeOf((*MockManager)(nil).GetConfig))
}
// GetControllerOptions mocks base method.
func (m *MockManager) GetControllerOptions() v1alpha1.ControllerConfigurationSpec {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "GetControllerOptions")
ret0, _ := ret[0].(v1alpha1.ControllerConfigurationSpec)
return ret0
}
// GetControllerOptions indicates an expected call of GetControllerOptions.
func (mr *MockManagerMockRecorder) GetControllerOptions() *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetControllerOptions", reflect.TypeOf((*MockManager)(nil).GetControllerOptions))
}
// GetEventRecorderFor mocks base method.
func (m *MockManager) GetEventRecorderFor(arg0 string) record.EventRecorder {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "GetEventRecorderFor", arg0)
ret0, _ := ret[0].(record.EventRecorder)
return ret0
}
// GetEventRecorderFor indicates an expected call of GetEventRecorderFor.
func (mr *MockManagerMockRecorder) GetEventRecorderFor(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetEventRecorderFor", reflect.TypeOf((*MockManager)(nil).GetEventRecorderFor), arg0)
}
// GetFieldIndexer mocks base method.
func (m *MockManager) GetFieldIndexer() client.FieldIndexer {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "GetFieldIndexer")
ret0, _ := ret[0].(client.FieldIndexer)
return ret0
}
// GetFieldIndexer indicates an expected call of GetFieldIndexer.
func (mr *MockManagerMockRecorder) GetFieldIndexer() *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetFieldIndexer", reflect.TypeOf((*MockManager)(nil).GetFieldIndexer))
}
// GetLogger mocks base method.
func (m *MockManager) GetLogger() logr.Logger {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "GetLogger")
ret0, _ := ret[0].(logr.Logger)
return ret0
}
// GetLogger indicates an expected call of GetLogger.
func (mr *MockManagerMockRecorder) GetLogger() *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetLogger", reflect.TypeOf((*MockManager)(nil).GetLogger))
}
// GetRESTMapper mocks base method.
func (m *MockManager) GetRESTMapper() meta.RESTMapper {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "GetRESTMapper")
ret0, _ := ret[0].(meta.RESTMapper)
return ret0
}
// GetRESTMapper indicates an expected call of GetRESTMapper.
func (mr *MockManagerMockRecorder) GetRESTMapper() *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetRESTMapper", reflect.TypeOf((*MockManager)(nil).GetRESTMapper))
}
// GetScheme mocks base method.
func (m *MockManager) GetScheme() *runtime.Scheme {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "GetScheme")
ret0, _ := ret[0].(*runtime.Scheme)
return ret0
}
// GetScheme indicates an expected call of GetScheme.
func (mr *MockManagerMockRecorder) GetScheme() *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetScheme", reflect.TypeOf((*MockManager)(nil).GetScheme))
}
// GetWebhookServer mocks base method.
func (m *MockManager) GetWebhookServer() *webhook.Server {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "GetWebhookServer")
ret0, _ := ret[0].(*webhook.Server)
return ret0
}
// GetWebhookServer indicates an expected call of GetWebhookServer.
func (mr *MockManagerMockRecorder) GetWebhookServer() *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetWebhookServer", reflect.TypeOf((*MockManager)(nil).GetWebhookServer))
}
// SetFields mocks base method.
func (m *MockManager) SetFields(arg0 interface{}) error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "SetFields", arg0)
ret0, _ := ret[0].(error)
return ret0
}
// SetFields indicates an expected call of SetFields.
func (mr *MockManagerMockRecorder) SetFields(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetFields", reflect.TypeOf((*MockManager)(nil).SetFields), arg0)
}
// Start mocks base method.
func (m *MockManager) Start(arg0 context.Context) error {
m.ctrl.T.Helper()
ret := m.ctrl.Call(m, "Start", arg0)
ret0, _ := ret[0].(error)
return ret0
}
// Start indicates an expected call of Start.
func (mr *MockManagerMockRecorder) Start(arg0 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Start", reflect.TypeOf((*MockManager)(nil).Start), arg0)
}
| 300 |
eks-anywhere-packages | aws | Go | package main
import (
_ "embed"
"os"
"strings"
"github.com/fsnotify/fsnotify"
"github.com/aws/eks-anywhere-packages/credentialproviderpackage/pkg/awscred"
cfg "github.com/aws/eks-anywhere-packages/credentialproviderpackage/pkg/configurator"
"github.com/aws/eks-anywhere-packages/credentialproviderpackage/pkg/configurator/bottlerocket"
"github.com/aws/eks-anywhere-packages/credentialproviderpackage/pkg/configurator/linux"
"github.com/aws/eks-anywhere-packages/credentialproviderpackage/pkg/constants"
"github.com/aws/eks-anywhere-packages/credentialproviderpackage/pkg/log"
)
const (
bottleRocket = "bottlerocket"
socketPath = "/run/api.sock"
// Aws Credentials
awsProfile = "eksa-packages"
credWatchData = "/secrets/aws-creds/..data"
credWatchPath = "/secrets/aws-creds/"
)
func main() {
var configurator cfg.Configurator
var err error
osType := strings.ToLower(os.Getenv("OS_TYPE"))
if osType == "" {
log.ErrorLogger.Println("Missing Environment Variable OS_TYPE")
os.Exit(1)
}
secretPath, err := awscred.GetAwsConfigPath()
if err != nil {
log.ErrorLogger.Fatal(err)
}
profile := os.Getenv("AWS_PROFILE")
if profile == "" {
profile = awsProfile
}
config := createCredentialProviderConfigOptions()
if osType == bottleRocket {
configurator, err = bottlerocket.NewBottleRocketConfigurator(socketPath)
if err != nil {
log.ErrorLogger.Fatal(err)
}
} else {
configurator = linux.NewLinuxConfigurator()
}
configurator.Initialize(config)
err = configurator.UpdateAWSCredentials(secretPath, profile)
if err != nil {
log.ErrorLogger.Fatal(err)
}
log.InfoLogger.Println("Aws credentials configured")
err = configurator.UpdateCredentialProvider(profile)
if err != nil {
log.ErrorLogger.Fatal(err)
}
log.InfoLogger.Println("Credential Provider Configured")
err = configurator.CommitChanges()
if err != nil {
log.ErrorLogger.Fatal(err)
}
log.InfoLogger.Println("Kubelet Restarted")
// Creating watcher for credentials
watcher, err := fsnotify.NewWatcher()
if err != nil {
log.ErrorLogger.Fatal(err)
}
defer watcher.Close()
// Start listening for changes to the aws credentials
go func() {
for {
select {
case event, ok := <-watcher.Events:
if !ok {
return
}
if event.Has(fsnotify.Create) {
if event.Name == credWatchData {
secretPath, err := awscred.GetAwsConfigPath()
if err != nil {
log.ErrorLogger.Fatal(err)
}
err = configurator.UpdateAWSCredentials(secretPath, profile)
if err != nil {
log.ErrorLogger.Fatal(err)
}
log.InfoLogger.Println("Aws credentials successfully changed")
}
}
case err, ok := <-watcher.Errors:
if !ok {
return
}
log.WarningLogger.Printf("filewatcher error: %v", err)
}
}
}()
err = watcher.Add(credWatchPath)
if err != nil {
log.ErrorLogger.Fatal(err)
}
// Block main goroutine forever.
<-make(chan struct{})
}
func createCredentialProviderConfigOptions() constants.CredentialProviderConfigOptions {
imagePatternsValues := os.Getenv("MATCH_IMAGES")
if imagePatternsValues == "" {
imagePatternsValues = constants.DefaultImagePattern
}
imagePatterns := strings.Split(imagePatternsValues, ",")
defaultCacheDuration := os.Getenv("DEFAULT_CACHE_DURATION")
if defaultCacheDuration == "" {
defaultCacheDuration = constants.DefaultCacheDuration
}
return constants.CredentialProviderConfigOptions{
ImagePatterns: imagePatterns,
DefaultCacheDuration: defaultCacheDuration,
}
}
| 137 |
eks-anywhere-packages | aws | Go | package test
import (
"bytes"
"flag"
"fmt"
"io/ioutil"
"log"
"os"
"os/exec"
"regexp"
"testing"
"github.com/aws/eks-anywhere-packages/credentialproviderpackage/pkg/filewriter"
)
var UpdateGoldenFiles = flag.Bool("update", false, "update golden files")
func AssertFilesEquals(t *testing.T, gotPath, wantPath string) {
t.Helper()
gotFile := ReadFile(t, gotPath)
processUpdate(t, wantPath, gotFile)
wantFile := ReadFile(t, wantPath)
if gotFile != wantFile {
cmd := exec.Command("diff", wantPath, gotPath)
result, err := cmd.Output()
if err != nil {
if exitError, ok := err.(*exec.ExitError); ok {
if exitError.ExitCode() == 1 {
t.Fatalf("Results diff expected actual:\n%s", string(result))
}
}
}
t.Fatalf("Files are different got =\n %s \n want =\n %s\n%s", gotFile, wantFile, err)
}
}
func AssertContentToFile(t *testing.T, gotContent, wantFile string) {
t.Helper()
if wantFile == "" {
return
}
processUpdate(t, wantFile, gotContent)
fileContent := ReadFile(t, wantFile)
if gotContent != fileContent {
diff, err := computeDiffBetweenContentAndFile([]byte(gotContent), wantFile)
if err != nil {
t.Fatalf("Content doesn't match file got =\n%s\n\n\nwant =\n%s\n", gotContent, fileContent)
}
if diff != "" {
t.Fatalf("Results diff expected actual for %s:\n%s", wantFile, string(diff))
}
}
}
func contentEqualToFile(gotContent []byte, wantFile string) (bool, error) {
if wantFile == "" && len(gotContent) == 0 {
return false, nil
}
fileContent, err := ioutil.ReadFile(wantFile)
if err != nil {
return false, err
}
return bytes.Equal(gotContent, fileContent), nil
}
func computeDiffBetweenContentAndFile(content []byte, file string) (string, error) {
cmd := exec.Command("diff", "-u", file, "-")
cmd.Stdin = bytes.NewReader([]byte(content))
result, err := cmd.Output()
if err != nil {
if exitError, ok := err.(*exec.ExitError); ok && exitError.ExitCode() == 1 {
return string(result), nil
}
return "", fmt.Errorf("computing the difference between content and file %s: %v", file, err)
}
return "", nil
}
func processUpdate(t *testing.T, filePath, content string) {
if *UpdateGoldenFiles {
if err := ioutil.WriteFile(filePath, []byte(content), 0o644); err != nil {
t.Fatalf("failed to update golden file %s: %v", filePath, err)
}
log.Printf("Golden file updated: %s", filePath)
}
}
func ReadFileAsBytes(t *testing.T, file string) []byte {
bytesRead, err := ioutil.ReadFile(file)
if err != nil {
t.Fatalf("File [%s] reading error in test: %v", file, err)
}
return bytesRead
}
func ReadFile(t *testing.T, file string) string {
return string(ReadFileAsBytes(t, file))
}
func NewWriter(t *testing.T) (dir string, writer filewriter.FileWriter) {
dir, err := ioutil.TempDir(".", SanitizePath(t.Name())+"-")
if err != nil {
t.Fatalf("error setting up folder for test: %v", err)
}
t.Cleanup(cleanupDir(t, dir))
writer, err = filewriter.NewWriter(dir)
if err != nil {
t.Fatalf("error creating writer with folder for test: %v", err)
}
return dir, writer
}
func cleanupDir(t *testing.T, dir string) func() {
return func() {
if !t.Failed() {
os.RemoveAll(dir)
}
}
}
var sanitizePathChars = regexp.MustCompile(`[^\w-]`)
const sanitizePathReplacementChar = "_"
// SanitizePath sanitizes s so its usable as a path name. For safety, it assumes all characters that are not
// A-Z, a-z, 0-9, _ or - are illegal and replaces them with _.
func SanitizePath(s string) string {
return sanitizePathChars.ReplaceAllString(s, sanitizePathReplacementChar)
}
| 138 |
eks-anywhere-packages | aws | Go | package awscred
import (
"errors"
"fmt"
"io/ioutil"
"os"
"strings"
)
const (
configSecretPath = "/secrets/aws-creds/config"
accessKeySecretPath = "/secrets/aws-creds/AWS_ACCESS_KEY_ID"
secretAccessKeySecretPath = "/secrets/aws-creds/AWS_SECRET_ACCESS_KEY"
regionSecretPath = "/secrets/aws-creds/REGION"
createConfigPath = "/config"
)
func generateAwsConfigSecret(accessKeyPath string, secretAccessKeyPath string, regionPath string) (string, error) {
accessKeyByte, err := ioutil.ReadFile(accessKeyPath)
if err != nil {
return "", err
}
accessKey := strings.Trim(string(accessKeyByte), "'")
secretAccessKeyByte, err := ioutil.ReadFile(secretAccessKeyPath)
if err != nil {
return "", err
}
secretAccessKey := strings.Trim(string(secretAccessKeyByte), "'")
regionByte, err := ioutil.ReadFile(regionPath)
if err != nil {
return "", err
}
region := strings.Trim(string(regionByte), "'")
awsConfig := fmt.Sprintf(
`
[default]
aws_access_key_id=%s
aws_secret_access_key=%s
region=%s
`, accessKey, secretAccessKey, region)
return awsConfig, err
}
func GetAwsConfigPath() (string, error) {
_, err := os.Stat(configSecretPath)
if err != nil {
if errors.Is(err, os.ErrNotExist) {
awsConfig, err := generateAwsConfigSecret(accessKeySecretPath, secretAccessKeySecretPath, regionSecretPath)
err = ioutil.WriteFile(createConfigPath, []byte(awsConfig), 0400)
return createConfigPath, err
}
}
return configSecretPath, nil
}
| 58 |
eks-anywhere-packages | aws | Go | package awscred
import (
"fmt"
"io/ioutil"
"testing"
"github.com/aws/eks-anywhere-packages/credentialproviderpackage/internal/test"
)
func Test_generateAwsConfigSecret(t *testing.T) {
testDir, _ := test.NewWriter(t)
dir := testDir + "/"
err := createTestFiles(dir)
wantString := fmt.Sprintf(
`
[default]
aws_access_key_id=abc
aws_secret_access_key=def
region=us-east-3
`)
if err != nil {
t.Errorf("Failed to create test files")
}
type args struct {
accessKeyPath string
secretAccessKeyPath string
regionPath string
}
tests := []struct {
name string
args args
want string
wantErr bool
}{
{
name: "test create config",
args: args{
accessKeyPath: dir + "accessKey",
secretAccessKeyPath: dir + "secretAccessKey",
regionPath: dir + "region",
},
want: wantString,
wantErr: false,
},
{
name: "nonexistent path accesskey",
args: args{
accessKeyPath: dir + "wrongPath",
secretAccessKeyPath: dir + "secretAccessKey",
regionPath: dir + "region",
},
want: "",
wantErr: true,
},
{
name: "nonexistent path secretAccesskey",
args: args{
accessKeyPath: dir + "accessKey",
secretAccessKeyPath: dir + "wrongPath",
regionPath: dir + "region",
},
want: "",
wantErr: true,
},
{
name: "nonexistent path region",
args: args{
accessKeyPath: dir + "accessKey",
secretAccessKeyPath: dir + "secretAccessKey",
regionPath: dir + "wrongPath",
},
want: "",
wantErr: true,
},
{
name: "correctly trim secretKey",
args: args{
accessKeyPath: dir + "accessKey",
secretAccessKeyPath: dir + "secretAccessKeyWithQuote",
regionPath: dir + "region",
},
want: wantString,
wantErr: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := generateAwsConfigSecret(tt.args.accessKeyPath, tt.args.secretAccessKeyPath, tt.args.regionPath)
if (err != nil) != tt.wantErr {
t.Errorf("generateAwsConfigSecret() error = %v, wantErr %v", err, tt.wantErr)
return
}
if got != tt.want {
t.Errorf("generateAwsConfigSecret() got = %v, want %v", got, tt.want)
}
})
}
}
func createTestFiles(baseDir string) error {
writeMap := map[string]string{
"accessKey": "abc",
"secretAccessKey": "def",
"region": "us-east-3",
"secretAccessKeyWithQuote": "'def'",
}
for filePath, data := range writeMap {
err := ioutil.WriteFile(baseDir+filePath, []byte(data), 0600)
if err != nil {
return err
}
}
return nil
}
| 117 |
eks-anywhere-packages | aws | Go | package configurator
import "github.com/aws/eks-anywhere-packages/credentialproviderpackage/pkg/constants"
type Configurator interface {
// Initialize Handles node specific configuration depending on OS
Initialize(config constants.CredentialProviderConfigOptions)
// UpdateAWSCredentials Handles AWS Credential Setup
UpdateAWSCredentials(sourcePath string, profile string) error
// UpdateCredentialProvider Handles Credential Provider Setup
UpdateCredentialProvider(profile string) error
// CommitChanges Applies changes to Kubelet
CommitChanges() error
}
| 18 |
eks-anywhere-packages | aws | Go | package bottlerocket
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"fmt"
"io/fs"
"io/ioutil"
"net"
"net/http"
"os"
"strings"
"golang.org/x/mod/semver"
"github.com/aws/eks-anywhere-packages/credentialproviderpackage/pkg/configurator"
"github.com/aws/eks-anywhere-packages/credentialproviderpackage/pkg/constants"
)
type bottleRocket struct {
client http.Client
baseURL string
config constants.CredentialProviderConfigOptions
}
type awsCred struct {
Aws aws `json:"aws"`
}
type aws struct {
Config string `json:"config"`
Profile string `json:"profile"`
Region string `json:"region"`
}
type brKubernetes struct {
Kubernetes kubernetes `json:"kubernetes"`
}
type ecrCredentialProvider struct {
CacheDuration string `json:"cache-duration"`
Enabled bool `json:"enabled"`
ImagePatterns []string `json:"image-patterns"`
}
type credentialProviders struct {
EcrCredentialProvider ecrCredentialProvider `json:"ecr-credential-provider"`
}
type kubernetes struct {
CredentialProviders credentialProviders `json:"credential-providers"`
}
type brVersion struct {
Os struct {
Arch string `json:"arch"`
BuildID string `json:"build_id"`
PrettyName string `json:"pretty_name"`
VariantID string `json:"variant_id"`
VersionID string `json:"version_id"`
} `json:"os"`
}
var _ configurator.Configurator = (*bottleRocket)(nil)
func NewBottleRocketConfigurator(socketPath string) (*bottleRocket, error) {
socket, err := os.Stat(socketPath)
if err != nil {
return nil, err
}
if socket.Mode().Type() != fs.ModeSocket {
return nil, fmt.Errorf("Unexpected type %s expected socket\n", socket.Mode().Type())
}
br := &bottleRocket{
baseURL: "http://localhost/",
client: http.Client{
Transport: &http.Transport{
DialContext: func(_ context.Context, _, _ string) (net.Conn, error) {
return net.Dial("unix", socketPath)
},
},
},
}
valid, err := br.isSupportedBRVersion()
if err != nil {
return nil, fmt.Errorf("error retrieving BR version %v", err)
}
if !valid {
return nil, fmt.Errorf("unsupported BR version %v", err)
}
return br, nil
}
func (b *bottleRocket) Initialize(config constants.CredentialProviderConfigOptions) {
b.config = config
}
func (b *bottleRocket) UpdateAWSCredentials(path string, profile string) error {
data, err := ioutil.ReadFile(path)
if err != nil {
return err
}
content := base64.StdEncoding.EncodeToString(data)
payload, err := createCredentialsPayload(content, profile)
if err != nil {
return err
}
err = b.sendSettingsSetRequest(payload)
if err != nil {
return err
}
err = b.CommitChanges()
if err != nil {
return err
}
return err
}
func (b *bottleRocket) UpdateCredentialProvider(_ string) error {
payload, err := createCredentialProviderPayload(b.config)
if err != nil {
return err
}
err = b.sendSettingsSetRequest(payload)
if err != nil {
return err
}
return err
}
func (b *bottleRocket) CommitChanges() error {
// For Bottlerocket this step is committing all changes at once
commitPath := b.baseURL + "tx/commit_and_apply"
resp, err := b.client.Post(commitPath, "application/json", bytes.NewBuffer(make([]byte, 0)))
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("failed to commit changes: %s", resp.Status)
}
return nil
}
func (b *bottleRocket) sendSettingsSetRequest(payload []byte) error {
settingsPath := b.baseURL + "settings"
req, err := http.NewRequest(http.MethodPatch, settingsPath, bytes.NewBuffer(payload))
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/json")
respPatch, err := b.client.Do(req)
if err != nil {
return err
}
defer respPatch.Body.Close()
if respPatch.StatusCode != http.StatusNoContent {
return fmt.Errorf("failed patch request: %s", respPatch.Status)
}
return nil
}
func createCredentialsPayload(content string, profile string) ([]byte, error) {
aws := aws{
Config: content,
Profile: profile,
}
creds := awsCred{Aws: aws}
payload, err := json.Marshal(creds)
if err != nil {
return nil, err
}
return payload, nil
}
func createCredentialProviderPayload(config constants.CredentialProviderConfigOptions) ([]byte, error) {
providerConfig := brKubernetes{
Kubernetes: kubernetes{
credentialProviders{
ecrCredentialProvider{
Enabled: true,
ImagePatterns: config.ImagePatterns,
CacheDuration: config.DefaultCacheDuration,
},
},
},
}
payload, err := json.Marshal(providerConfig)
if err != nil {
return nil, err
}
return payload, nil
}
func (b *bottleRocket) isSupportedBRVersion() (bool, error) {
allowedVersions := "v1.11.0"
req, err := http.NewRequest(http.MethodGet, b.baseURL, nil)
if err != nil {
return false, err
}
q := req.URL.Query()
q.Add("prefix", "os")
req.URL.RawQuery = q.Encode()
respGet, err := b.client.Do(req)
if err != nil {
return false, err
}
defer respGet.Body.Close()
if respGet.StatusCode != http.StatusOK {
return false, fmt.Errorf("failed GET request: %s", respGet.Status)
}
valueBody, err := ioutil.ReadAll(respGet.Body)
if err != nil {
return false, err
}
osVersion := brVersion{}
err = json.Unmarshal(valueBody, &osVersion)
if err != nil {
return false, err
}
// Check if BR k8s version is 1.25 or greater. If so we will update allowedVersions to be >1.13.0
if osVersion.Os.VariantID != "" {
variants := strings.Split(osVersion.Os.VariantID, "-")
variantSemVar := "v" + variants[len(variants)-1]
if semver.Compare(variantSemVar, "v1.25") >= 0 {
allowedVersions = "v1.13.0"
}
}
ver := "v" + osVersion.Os.VersionID
valid := semver.Compare(ver, allowedVersions)
return valid > 0, nil
}
| 252 |
eks-anywhere-packages | aws | Go | package bottlerocket
import (
"bytes"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/http/httptest"
"os"
"testing"
"github.com/stretchr/testify/assert"
"github.com/aws/eks-anywhere-packages/credentialproviderpackage/pkg/constants"
)
type response struct {
statusCode int
expectedBody []byte
responseMsg string
}
type brFakeVersion struct {
Os struct {
Fake string `json:"fake"`
VariantID string `json:"variant_id"`
VersionID string `json:"version_id"`
} `json:"os"`
}
func Test_bottleRocket_CommitChanges(t *testing.T) {
type fields struct {
client http.Client
baseURL string
config constants.CredentialProviderConfigOptions
}
tests := []struct {
name string
fields fields
wantErr bool
response response
expected string
}{
{
name: "test success",
fields: fields{
client: http.Client{},
config: constants.CredentialProviderConfigOptions{
ImagePatterns: []string{constants.DefaultImagePattern},
DefaultCacheDuration: constants.DefaultCacheDuration,
},
},
wantErr: false,
response: response{
statusCode: http.StatusOK,
responseMsg: "",
},
},
{
name: "test fail",
fields: fields{
client: http.Client{},
config: constants.CredentialProviderConfigOptions{
ImagePatterns: []string{constants.DefaultImagePattern},
DefaultCacheDuration: constants.DefaultCacheDuration,
},
},
wantErr: true,
response: response{
statusCode: http.StatusNotFound,
responseMsg: "",
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
svr := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(tt.response.statusCode)
fmt.Fprintf(w, tt.response.responseMsg)
}))
b := &bottleRocket{
client: tt.fields.client,
baseURL: svr.URL + "/",
config: tt.fields.config,
}
if err := b.CommitChanges(); (err != nil) != tt.wantErr {
t.Errorf("UpdateAWSCredentials() error = %v, wantErr %v", err, tt.wantErr)
}
})
}
}
func Test_bottleRocket_UpdateAWSCredentials(t *testing.T) {
file, err := os.Open("testdata/testcreds")
if err != nil {
t.Errorf("Failed to open testcreds")
}
content, err := io.ReadAll(file)
if err != nil {
t.Errorf("Failed to read testcreds")
}
encodedSecret := base64.StdEncoding.EncodeToString(content)
expectedBody := fmt.Sprintf("{\"aws\":{\"config\":\"%s\",\"profile\":\"eksa-packages\",\"region\":\"\"}}", encodedSecret)
type fields struct {
client http.Client
baseURL string
config constants.CredentialProviderConfigOptions
}
type args struct {
path string
profile string
}
tests := []struct {
name string
fields fields
args args
patchResponse response
commitResponse response
wantErr bool
}{
{
name: "working credential update",
fields: fields{
client: http.Client{},
config: constants.CredentialProviderConfigOptions{},
},
args: args{
path: "testdata/testcreds",
profile: "eksa-packages",
},
patchResponse: response{
statusCode: http.StatusNoContent,
expectedBody: []byte(expectedBody),
responseMsg: "",
},
commitResponse: response{
statusCode: http.StatusOK,
responseMsg: "",
},
wantErr: false,
},
{
name: "commit credentials failed",
fields: fields{
client: http.Client{},
config: constants.CredentialProviderConfigOptions{},
},
args: args{
path: "testdata/testcreds",
profile: "eksa-packages",
},
patchResponse: response{
statusCode: http.StatusNoContent,
expectedBody: []byte(expectedBody),
responseMsg: "",
},
commitResponse: response{
statusCode: http.StatusNotFound,
responseMsg: "",
},
wantErr: true,
},
{
name: "failed to patch data",
fields: fields{
client: http.Client{},
config: constants.CredentialProviderConfigOptions{},
},
args: args{
path: "testdata/testcreds",
profile: "eksa-packages",
},
patchResponse: response{
statusCode: http.StatusNotFound,
expectedBody: []byte(expectedBody),
responseMsg: "",
},
commitResponse: response{
statusCode: http.StatusOK,
responseMsg: "",
},
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
svr := httptest.NewServer(http.HandlerFunc(
func(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodPatch {
validatePatchRequest(w, r, t, tt.patchResponse)
} else if r.Method == http.MethodPost {
w.WriteHeader(tt.commitResponse.statusCode)
fmt.Fprintf(w, tt.commitResponse.responseMsg)
} else {
t.Errorf("Recieved unexected request %v", r.Method)
}
}),
)
b := &bottleRocket{
client: tt.fields.client,
baseURL: svr.URL + "/",
config: tt.fields.config,
}
if err := b.UpdateAWSCredentials(tt.args.path, tt.args.profile); (err != nil) != tt.wantErr {
t.Errorf("UpdateAWSCredentials() error = %v, wantErr %v", err, tt.wantErr)
}
})
}
}
func Test_bottleRocket_UpdateCredentialProvider(t *testing.T) {
type fields struct {
client http.Client
baseURL string
config constants.CredentialProviderConfigOptions
}
tests := []struct {
name string
fields fields
patchResponse response
wantErr bool
}{
{
name: "default credential provider",
fields: fields{
client: http.Client{},
config: constants.CredentialProviderConfigOptions{
ImagePatterns: []string{constants.DefaultImagePattern},
DefaultCacheDuration: constants.DefaultCacheDuration,
},
},
patchResponse: response{
statusCode: http.StatusNoContent,
expectedBody: []byte("{\"kubernetes\":{\"credential-providers\":{\"ecr-credential-provider\":{\"cache-duration\":\"30m\",\"enabled\":true,\"image-patterns\":[\"*.dkr.ecr.*.amazonaws.com\"]}}}}"),
responseMsg: "",
},
wantErr: false,
},
{
name: "non default values for credential provider",
fields: fields{
client: http.Client{},
config: constants.CredentialProviderConfigOptions{
ImagePatterns: []string{"123456789.dkr.ecr.test-region.amazonaws.com"},
DefaultCacheDuration: "24h",
},
},
patchResponse: response{
statusCode: http.StatusNoContent,
expectedBody: []byte("{\"kubernetes\":{\"credential-providers\":{\"ecr-credential-provider\":{\"cache-duration\":\"24h\",\"enabled\":true,\"image-patterns\":[\"123456789.dkr.ecr.test-region.amazonaws.com\"]}}}}"),
responseMsg: "",
},
wantErr: false,
},
{
name: "multiple match images for credential provider",
fields: fields{
client: http.Client{},
config: constants.CredentialProviderConfigOptions{
ImagePatterns: []string{"123456789.dkr.ecr.test-region.amazonaws.com", "987654321.dkr.ecr.test-region.amazonaws.com"},
DefaultCacheDuration: "24h",
},
},
patchResponse: response{
statusCode: http.StatusNoContent,
expectedBody: []byte("{\"kubernetes\":{\"credential-providers\":{\"ecr-credential-provider\":{\"cache-duration\":\"24h\",\"enabled\":true,\"image-patterns\":[\"123456789.dkr.ecr.test-region.amazonaws.com\",\"987654321.dkr.ecr.test-region.amazonaws.com\"]}}}}"),
responseMsg: "",
},
wantErr: false,
},
{
name: "failed credential provider update",
fields: fields{
client: http.Client{},
config: constants.CredentialProviderConfigOptions{
ImagePatterns: []string{constants.DefaultImagePattern},
DefaultCacheDuration: constants.DefaultCacheDuration,
},
},
patchResponse: response{
statusCode: http.StatusNotFound,
expectedBody: []byte("{\"kubernetes\":{\"credential-providers\":{\"ecr-credential-provider\":{\"cache-duration\":\"30m\",\"enabled\":true,\"image-patterns\":[\"*.dkr.ecr.*.amazonaws.com\"]}}}}"),
responseMsg: "",
},
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
svr := httptest.NewServer(http.HandlerFunc(
func(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodPatch {
validatePatchRequest(w, r, t, tt.patchResponse)
} else {
t.Errorf("Recieved unexected request %v", r.Method)
}
}),
)
b := &bottleRocket{
client: tt.fields.client,
baseURL: svr.URL + "/",
config: tt.fields.config,
}
if err := b.UpdateCredentialProvider(""); (err != nil) != tt.wantErr {
t.Errorf("UpdateCredentialProvider() error = %v, wantErr %v", err, tt.wantErr)
}
})
}
}
func validatePatchRequest(w http.ResponseWriter, r *http.Request, t *testing.T, patchResponse response) {
data, err := ioutil.ReadAll(r.Body)
if err != nil {
t.Errorf("failed to read response")
}
if !bytes.Equal(data, patchResponse.expectedBody) {
t.Errorf("Patch message expcted %v got %v", patchResponse.expectedBody, data)
}
w.WriteHeader(patchResponse.statusCode)
fmt.Fprintf(w, patchResponse.responseMsg)
}
func Test_bottleRocket_Initialize(t *testing.T) {
type args struct {
config constants.CredentialProviderConfigOptions
}
tests := []struct {
name string
baseUrl string
args args
}{
{
name: "simple initialization",
baseUrl: "http://localhost/",
args: args{
config: constants.CredentialProviderConfigOptions{
ImagePatterns: []string{constants.DefaultImagePattern},
DefaultCacheDuration: constants.DefaultCacheDuration,
},
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
b := &bottleRocket{baseURL: tt.baseUrl}
b.Initialize(tt.args.config)
assert.Equal(t, tt.baseUrl, b.baseURL)
assert.Equal(t, tt.args.config, b.config)
assert.NotNil(t, b.client)
})
}
}
func Test_bottleRocket_isSupportedBRVersion(t *testing.T) {
type fields struct {
client http.Client
baseURL string
config constants.CredentialProviderConfigOptions
}
tests := []struct {
name string
fields fields
wantErr bool
brVersion string
brVariant string
statusCode int
want bool
emptyObject bool
differentFields bool
}{
{
name: "valid version",
fields: fields{client: http.Client{}},
brVersion: "1.13.1",
brVariant: "vmware-k8s-1.25",
statusCode: http.StatusOK,
wantErr: false,
want: true,
},
{
name: "invalid version",
fields: fields{client: http.Client{}},
brVersion: "1.13.0",
brVariant: "vmware-k8s-1.25",
statusCode: http.StatusOK,
wantErr: false,
want: false,
},
{
name: "very old invalid version",
fields: fields{client: http.Client{}},
brVersion: "1.10.1",
brVariant: "vmware-k8s-1.25",
statusCode: http.StatusOK,
wantErr: false,
want: false,
},
{
name: "<1.25 k8s version with old valid version",
fields: fields{client: http.Client{}},
brVersion: "1.11.1",
brVariant: "vmware-k8s-1.24",
statusCode: http.StatusOK,
wantErr: false,
want: true,
},
{
name: "<1.25 k8s version with old invalid version",
fields: fields{client: http.Client{}},
brVersion: "1.10.1",
brVariant: "vmware-k8s-1.23",
statusCode: http.StatusOK,
wantErr: false,
want: false,
},
{
name: "bad response from server",
fields: fields{client: http.Client{}},
brVersion: "1.13.1",
brVariant: "vmware-k8s-1.25",
statusCode: http.StatusNotFound,
wantErr: true,
want: false,
},
{
name: "missing from server",
fields: fields{client: http.Client{}},
brVersion: "",
brVariant: "",
statusCode: http.StatusNotFound,
wantErr: true,
want: false,
},
{
name: "empty object",
fields: fields{client: http.Client{}},
brVersion: "",
brVariant: "",
statusCode: http.StatusOK,
wantErr: true,
want: false,
emptyObject: true,
},
{
name: "different return fields",
fields: fields{client: http.Client{}},
brVersion: "",
brVariant: "",
statusCode: http.StatusOK,
wantErr: true,
want: false,
differentFields: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
svr := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(tt.statusCode)
var payload []byte
var err error
if tt.differentFields {
payload, err = createFakeBody(tt.brVersion, tt.brVariant)
if err != nil {
t.Errorf("Failed to marshall response %v", err)
}
}
if !tt.emptyObject {
payload, err = createGetBodyWithVersion(tt.brVersion, tt.brVariant)
if err != nil {
t.Errorf("Failed to marshall response %v", err)
}
}
w.Write(payload)
fmt.Fprintf(w, "")
}))
b := &bottleRocket{
client: tt.fields.client,
baseURL: svr.URL + "/",
config: tt.fields.config,
}
got, err := b.isSupportedBRVersion()
if err != nil {
if !tt.wantErr {
t.Errorf("Expected no error but got %v", err)
}
}
assert.Equalf(t, tt.want, got, "isSupportedBRVersion()")
})
}
}
func createGetBodyWithVersion(version string, variant string) ([]byte, error) {
brVer := brVersion{}
brVer.Os.VersionID = version
brVer.Os.VariantID = variant
payload, err := json.Marshal(brVer)
if err != nil {
return nil, err
}
return payload, nil
}
func createFakeBody(version string, variant string) ([]byte, error) {
brFake := brFakeVersion{}
brFake.Os.VersionID = version
brFake.Os.VariantID = variant
payload, err := json.Marshal(brFake)
if err != nil {
return nil, err
}
return payload, nil
}
| 525 |
eks-anywhere-packages | aws | Go | package linux
import (
_ "embed"
"fmt"
"io"
"io/ioutil"
"os"
"strings"
"syscall"
ps "github.com/mitchellh/go-ps"
"golang.org/x/mod/semver"
"github.com/aws/eks-anywhere-packages/credentialproviderpackage/pkg/configurator"
"github.com/aws/eks-anywhere-packages/credentialproviderpackage/pkg/constants"
"github.com/aws/eks-anywhere-packages/credentialproviderpackage/pkg/log"
"github.com/aws/eks-anywhere-packages/credentialproviderpackage/pkg/templater"
)
//go:embed templates/credential-provider-config.yaml
var credProviderTemplate string
const (
binPath = "/eksa-binaries/"
basePath = "/eksa-packages/"
credOutFile = "aws-creds"
mountedExtraArgs = "/node-files/kubelet-extra-args"
credProviderFile = "credential-provider-config.yaml"
// Binaries
ecrCredProviderBinary = "ecr-credential-provider"
iamRolesSigningBinary = "aws_signing_helper"
)
type linuxOS struct {
profile string
extraArgsPath string
basePath string
config constants.CredentialProviderConfigOptions
}
var _ configurator.Configurator = (*linuxOS)(nil)
func NewLinuxConfigurator() *linuxOS {
return &linuxOS{
profile: "",
extraArgsPath: mountedExtraArgs,
basePath: basePath,
}
}
func (c *linuxOS) Initialize(config constants.CredentialProviderConfigOptions) {
c.config = config
}
func (c *linuxOS) UpdateAWSCredentials(sourcePath string, profile string) error {
c.profile = profile
dstPath := c.basePath + credOutFile
err := copyWithPermissons(sourcePath, dstPath, 0600)
return err
}
func (c *linuxOS) UpdateCredentialProvider(_ string) error {
// Adding to KUBELET_EXTRA_ARGS in place
file, err := ioutil.ReadFile(c.extraArgsPath)
if err != nil {
return err
}
lines := strings.Split(string(file), "\n")
found := false
for i, line := range lines {
if strings.HasPrefix(line, "KUBELET_EXTRA_ARGS") {
found = true
args := c.updateKubeletArguments(line)
if args != "" {
lines[i] = line + args + "\n"
}
}
}
if !found {
line := "KUBELET_EXTRA_ARGS="
args := c.updateKubeletArguments(line)
if args != "" {
line = line + args
}
lines = append(lines, line)
}
out := strings.Join(lines, "\n")
err = ioutil.WriteFile(c.extraArgsPath, []byte(out), 0644)
return err
}
func (c *linuxOS) CommitChanges() error {
process, err := findKubeletProcess()
if err != nil {
return err
}
err = killProcess(process)
return err
}
func killProcess(process ps.Process) error {
err := syscall.Kill(process.Pid(), syscall.SIGHUP)
return err
}
func findKubeletProcess() (ps.Process, error) {
processList, err := ps.Processes()
if err != nil {
return nil, err
}
for x := range processList {
process := processList[x]
if process.Executable() == "kubelet" {
return process, nil
}
}
return nil, fmt.Errorf("cannot find Kubelet Process")
}
func getApiVersion() string {
k8sVersion := os.Getenv("K8S_VERSION")
apiVersion := "v1"
if semver.Compare(k8sVersion, "v1.25") <= 0 {
apiVersion = "v1alpha1"
}
if k8sVersion == "" {
apiVersion = "v1"
}
return apiVersion
}
func copyWithPermissons(srcpath, dstpath string, permission os.FileMode) (err error) {
r, err := os.Open(srcpath)
if err != nil {
return err
}
defer r.Close() // ok to ignore error: file was opened read-only.
w, err := os.Create(dstpath)
if err != nil {
return err
}
defer func() {
c := w.Close()
// Report the error from Close, if any.
// But do so only if there isn't already
// an outgoing error.
if c != nil && err == nil {
err = c
}
}()
_, err = io.Copy(w, r)
if err != nil {
return err
}
err = os.Chmod(dstpath, permission)
return err
}
func copyBinaries() (string, error) {
srcPath := binPath + getApiVersion() + "/" + ecrCredProviderBinary
dstPath := basePath + ecrCredProviderBinary
err := copyWithPermissons(srcPath, dstPath, 0700)
if err != nil {
return "", err
}
err = os.Chmod(dstPath, 0700)
if err != nil {
return "", err
}
srcPath = binPath + iamRolesSigningBinary
dstPath = basePath + iamRolesSigningBinary
err = copyWithPermissons(srcPath, dstPath, 0700)
if err != nil {
return "", err
}
err = os.Chmod(dstPath, 0700)
if err != nil {
return "", err
}
return fmt.Sprintf(" --image-credential-provider-bin-dir=%s", basePath), nil
}
func (c *linuxOS) createConfig() (string, error) {
values := map[string]interface{}{
"profile": c.profile,
"config": basePath + credOutFile,
"home": basePath,
"apiVersion": getApiVersion(),
"imagePattern": c.config.ImagePatterns,
"cacheDuration": c.config.DefaultCacheDuration,
}
dstPath := c.basePath + credProviderFile
bytes, err := templater.Execute(credProviderTemplate, values)
if err != nil {
return "", nil
}
err = ioutil.WriteFile(dstPath, bytes, 0600)
if err != nil {
return "", err
}
return fmt.Sprintf(" --image-credential-provider-config=%s", dstPath), nil
}
func (c *linuxOS) updateKubeletArguments(line string) string {
args := ""
if !strings.Contains(line, "KubeletCredentialProviders") {
args += " --feature-gates=KubeletCredentialProviders=true"
}
val, err := c.createConfig()
if err != nil {
log.ErrorLogger.Printf("Error creating configuration %v", err)
}
// We want to upgrade the eksa owned configuration/binaries everytime however,
// we don't want to update what configuration is being pointed to in cases of a custom config
if !strings.Contains(line, "image-credential-provider-config") {
args += val
}
val, err = copyBinaries()
if err != nil {
log.ErrorLogger.Printf("Error coping binaries %v\n", err)
}
if !strings.Contains(line, "image-credential-provider-bin-dir") {
args += val
}
return args
}
| 243 |
eks-anywhere-packages | aws | Go | package linux
import (
"fmt"
"io/ioutil"
"os"
"testing"
"github.com/stretchr/testify/assert"
"github.com/aws/eks-anywhere-packages/credentialproviderpackage/internal/test"
"github.com/aws/eks-anywhere-packages/credentialproviderpackage/pkg/constants"
)
func Test_linuxOS_updateKubeletArguments(t *testing.T) {
testDir, _ := test.NewWriter(t)
dir := testDir + "/"
type fields struct {
profile string
extraArgsPath string
basePath string
config constants.CredentialProviderConfigOptions
}
type args struct {
line string
}
tests := []struct {
name string
fields fields
args args
outputConfigPath string
configWantPath string
k8sVersion string
want string
}{
{
name: "test empty string",
fields: fields{
profile: "eksa-packages",
extraArgsPath: dir,
basePath: dir,
config: constants.CredentialProviderConfigOptions{
ImagePatterns: []string{constants.DefaultImagePattern},
DefaultCacheDuration: constants.DefaultCacheDuration,
},
},
args: args{line: ""},
outputConfigPath: dir + "/" + credProviderFile,
configWantPath: "testdata/expected-config.yaml",
want: fmt.Sprintf(" --feature-gates=KubeletCredentialProviders=true "+
"--image-credential-provider-config=%s%s", dir, credProviderFile),
},
{
name: "test multiple match patterns",
fields: fields{
profile: "eksa-packages",
extraArgsPath: dir,
basePath: dir,
config: constants.CredentialProviderConfigOptions{
ImagePatterns: []string{"1234567.dkr.ecr.us-east-1.amazonaws.com",
"7654321.dkr.ecr.us-west-2.amazonaws.com"},
DefaultCacheDuration: constants.DefaultCacheDuration,
},
},
args: args{line: ""},
outputConfigPath: dir + "/" + credProviderFile,
configWantPath: "testdata/expected-config-multiple-patterns.yaml",
want: fmt.Sprintf(" --feature-gates=KubeletCredentialProviders=true "+
"--image-credential-provider-config=%s%s", dir, credProviderFile),
},
{
name: "skip credential provider if already provided",
fields: fields{
profile: "eksa-packages",
extraArgsPath: dir,
basePath: dir,
config: constants.CredentialProviderConfigOptions{
ImagePatterns: []string{constants.DefaultImagePattern},
DefaultCacheDuration: constants.DefaultCacheDuration,
},
},
args: args{line: " --feature-gates=KubeletCredentialProviders=true"},
outputConfigPath: dir + "/" + credProviderFile,
configWantPath: "testdata/expected-config.yaml",
want: fmt.Sprintf(" --image-credential-provider-config=%s%s", dir, credProviderFile),
},
{
name: "skip both cred provider and feature gate if provided",
fields: fields{
profile: "eksa-packages",
extraArgsPath: dir,
basePath: dir,
config: constants.CredentialProviderConfigOptions{
ImagePatterns: []string{constants.DefaultImagePattern},
DefaultCacheDuration: constants.DefaultCacheDuration,
},
},
args: args{line: " --feature-gates=KubeletCredentialProviders=false --image-credential-provider-config=blah"},
outputConfigPath: dir + "/" + credProviderFile,
configWantPath: "",
want: "",
},
{
name: "test alpha api",
fields: fields{
profile: "eksa-packages",
extraArgsPath: dir,
basePath: dir,
config: constants.CredentialProviderConfigOptions{
ImagePatterns: []string{constants.DefaultImagePattern},
DefaultCacheDuration: constants.DefaultCacheDuration,
},
},
args: args{line: ""},
outputConfigPath: dir + "/" + credProviderFile,
configWantPath: "testdata/expected-config-alpha.yaml",
k8sVersion: "v1.25",
want: fmt.Sprintf(" --feature-gates=KubeletCredentialProviders=true "+
"--image-credential-provider-config=%s%s", dir, credProviderFile),
},
{
name: "test v1 api 1.27",
fields: fields{
profile: "eksa-packages",
extraArgsPath: dir,
basePath: dir,
config: constants.CredentialProviderConfigOptions{
ImagePatterns: []string{constants.DefaultImagePattern},
DefaultCacheDuration: constants.DefaultCacheDuration,
},
},
args: args{line: ""},
outputConfigPath: dir + "/" + credProviderFile,
configWantPath: "testdata/expected-config.yaml",
k8sVersion: "v1.27",
want: fmt.Sprintf(" --feature-gates=KubeletCredentialProviders=true "+
"--image-credential-provider-config=%s%s", dir, credProviderFile),
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
c := &linuxOS{
profile: tt.fields.profile,
extraArgsPath: tt.fields.extraArgsPath,
basePath: tt.fields.basePath,
config: tt.fields.config,
}
t.Setenv("K8S_VERSION", tt.k8sVersion)
if got := c.updateKubeletArguments(tt.args.line); got != tt.want {
t.Errorf("updateKubeletArguments() = %v, want %v", got, tt.want)
}
if tt.configWantPath != "" {
test.AssertFilesEquals(t, tt.outputConfigPath, tt.configWantPath)
}
})
}
}
func Test_linuxOS_UpdateAWSCredentials(t *testing.T) {
testDir, _ := test.NewWriter(t)
dir := testDir + "/"
type fields struct {
profile string
extraArgsPath string
basePath string
config constants.CredentialProviderConfigOptions
}
type args struct {
sourcePath string
profile string
}
tests := []struct {
name string
fields fields
args args
wantErr bool
}{
{
name: "simple credential move",
fields: fields{
profile: "eksa-packages",
extraArgsPath: dir,
basePath: dir,
config: constants.CredentialProviderConfigOptions{
ImagePatterns: []string{constants.DefaultImagePattern},
DefaultCacheDuration: constants.DefaultCacheDuration,
},
},
args: args{
sourcePath: "testdata/testcreds",
profile: "eksa-packages",
},
wantErr: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
dstFile := tt.fields.basePath + credOutFile
c := &linuxOS{
profile: tt.fields.profile,
extraArgsPath: tt.fields.extraArgsPath,
basePath: tt.fields.basePath,
config: tt.fields.config,
}
if err := c.UpdateAWSCredentials(tt.args.sourcePath, tt.args.profile); (err != nil) != tt.wantErr {
t.Errorf("UpdateAWSCredentials() error = %v, wantErr %v", err, tt.wantErr)
}
info, err := os.Stat(dstFile)
if err != nil {
t.Errorf("Failed to open destination file")
}
if info.Mode().Perm() != os.FileMode(0600) {
t.Errorf("Credential file not saved with correct permission")
}
if err != nil {
t.Errorf("Failed to set file back to readable")
}
expectedCreds, err := ioutil.ReadFile(tt.args.sourcePath)
if err != nil {
t.Errorf("Failed to read source credential file")
}
actualCreds, err := ioutil.ReadFile(dstFile)
if err != nil {
t.Errorf("Failed to read created credential file")
}
assert.Equal(t, expectedCreds, actualCreds)
})
}
}
func Test_linuxOS_Initialize(t *testing.T) {
type fields struct {
profile string
extraArgsPath string
basePath string
config constants.CredentialProviderConfigOptions
}
type args struct {
config constants.CredentialProviderConfigOptions
}
tests := []struct {
name string
fields fields
args args
}{
{
name: "simple initialization",
args: args{
config: constants.CredentialProviderConfigOptions{
ImagePatterns: []string{constants.DefaultImagePattern},
DefaultCacheDuration: constants.DefaultCacheDuration,
},
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
c := NewLinuxConfigurator()
c.Initialize(tt.args.config)
assert.Equal(t, c.config, tt.args.config)
})
}
}
| 268 |
eks-anywhere-packages | aws | Go | package constants
const (
// Credential Provider constants
DefaultImagePattern = "*.dkr.ecr.*.amazonaws.com"
DefaultCacheDuration = "30m"
)
type CredentialProviderConfigOptions struct {
ImagePatterns []string
DefaultCacheDuration string
}
| 13 |
eks-anywhere-packages | aws | Go | package filewriter
import (
"io"
"os"
)
type FileWriter interface {
Write(fileName string, content []byte, f ...FileOptionsFunc) (path string, err error)
WithDir(dir string) (FileWriter, error)
CleanUp()
CleanUpTemp()
Dir() string
TempDir() string
Create(name string, f ...FileOptionsFunc) (_ io.WriteCloser, path string, _ error)
}
type FileOptions struct {
IsTemp bool
Permissions os.FileMode
}
type FileOptionsFunc func(op *FileOptions)
| 24 |
eks-anywhere-packages | aws | Go | package filewriter
import (
"os"
)
const DefaultTmpFolder = "generated"
func defaultFileOptions() *FileOptions {
return &FileOptions{true, os.ModePerm}
}
func Permission0600(op *FileOptions) {
op.Permissions = 0o600
}
func PersistentFile(op *FileOptions) {
op.IsTemp = false
}
| 20 |
eks-anywhere-packages | aws | Go | package filewriter_test
import (
"io/ioutil"
"os"
"path"
"path/filepath"
"strings"
"testing"
"github.com/google/go-cmp/cmp"
"github.com/aws/eks-anywhere-packages/credentialproviderpackage/pkg/filewriter"
)
func TestTmpWriterWriteValid(t *testing.T) {
folder := "tmp_folder"
folder2 := "tmp_folder_2"
err := os.MkdirAll(folder2, os.ModePerm)
if err != nil {
t.Fatalf("error setting up test: %v", err)
}
defer os.RemoveAll(folder)
defer os.RemoveAll(folder2)
tests := []struct {
testName string
dir string
fileName string
content []byte
}{
{
testName: "dir doesn't exist",
dir: folder,
fileName: "TestTmpWriterWriteValid-success.yaml",
content: []byte(`
fake content
blablab
`),
},
{
testName: "dir exists",
dir: folder2,
fileName: "test",
content: []byte(`
fake content
blablab
`),
},
{
testName: "empty file name",
dir: folder,
fileName: "test",
content: []byte(`
fake content
blablab
`),
},
}
for _, tt := range tests {
t.Run(tt.testName, func(t *testing.T) {
tr, err := filewriter.NewWriter(tt.dir)
if err != nil {
t.Fatalf("failed creating tmpWriter error = %v", err)
}
gotPath, err := tr.Write(tt.fileName, tt.content)
if err != nil {
t.Fatalf("tmpWriter.Write() error = %v", err)
}
if !strings.HasPrefix(gotPath, tt.dir) {
t.Errorf("tmpWriter.Write() = %v, want to start with %v", gotPath, tt.dir)
}
if !strings.HasSuffix(gotPath, tt.fileName) {
t.Errorf("tmpWriter.Write() = %v, want to end with %v", gotPath, tt.fileName)
}
content, err := ioutil.ReadFile(gotPath)
if err != nil {
t.Fatalf("error reading written file: %v", err)
}
if string(content) != string(tt.content) {
t.Errorf("Write file content = %v, want %v", content, tt.content)
}
})
}
}
func TestTmpWriterWithDir(t *testing.T) {
rootFolder := "folder_root"
subFolder := "subFolder"
defer os.RemoveAll(rootFolder)
tr, err := filewriter.NewWriter(rootFolder)
if err != nil {
t.Fatalf("failed creating tmpWriter error = %v", err)
}
tr, err = tr.WithDir(subFolder)
if err != nil {
t.Fatalf("failed creating tmpWriter with subdir error = %v", err)
}
gotPath, err := tr.Write("file.txt", []byte("file content"))
if err != nil {
t.Fatalf("tmpWriter.Write() error = %v", err)
}
wantPathPrefix := filepath.Join(rootFolder, subFolder)
if !strings.HasPrefix(gotPath, wantPathPrefix) {
t.Errorf("tmpWriter.Write() = %v, want to start with %v", gotPath, wantPathPrefix)
}
}
func TestCreate(t *testing.T) {
dir := t.TempDir()
const fileName = "test.txt"
// Hard code the "generated". Its an implementation detail but we can't refactor it right now.
expectedPath := path.Join(dir, "generated", fileName)
expectedContent := []byte("test content")
fr, err := filewriter.NewWriter(dir)
if err != nil {
t.Fatal(err)
}
fh, path, err := fr.Create(fileName)
if err != nil {
t.Fatal(err)
}
// We need to validate 2 things: (1) are the paths returned correct; (2) if we write content
// to the returned io.WriteCloser, is it written to the path also returened from the function.
if path != expectedPath {
t.Fatalf("Received: %v; Expected: %v", path, expectedPath)
}
if _, err := fh.Write(expectedContent); err != nil {
t.Fatal(err)
}
if err := fh.Close(); err != nil {
t.Fatal(err)
}
content, err := os.ReadFile(expectedPath)
if err != nil {
t.Fatal(err)
}
if !cmp.Equal(content, expectedContent) {
t.Fatalf("Received: %v; Expected: %v", content, expectedContent)
}
}
| 160 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.