change: golangci-lint fix whitespaces

pull/1283/head
iwilltry42 1 year ago
parent a1c390e7c2
commit 93a67d712e
No known key found for this signature in database
GPG Key ID: FD4E78FBAD6B1550
  1. 1
      cmd/cluster/cluster.go
  2. 11
      cmd/cluster/clusterCreate.go
  3. 3
      cmd/cluster/clusterDelete.go
  4. 5
      cmd/cluster/clusterEdit.go
  5. 1
      cmd/cluster/clusterStart.go
  6. 1
      cmd/cluster/clusterStop.go
  7. 3
      cmd/config/configMigrate.go
  8. 1
      cmd/image/image.go
  9. 2
      cmd/image/imageImport.go
  10. 1
      cmd/kubeconfig/kubeconfig.go
  11. 1
      cmd/kubeconfig/kubeconfigGet.go
  12. 2
      cmd/kubeconfig/kubeconfigMerge.go
  13. 1
      cmd/node/node.go
  14. 2
      cmd/node/nodeCreate.go
  15. 3
      cmd/node/nodeDelete.go
  16. 5
      cmd/node/nodeEdit.go
  17. 1
      cmd/node/nodeStart.go
  18. 1
      cmd/node/nodeStop.go
  19. 1
      cmd/registry/registry.go
  20. 3
      cmd/registry/registryCreate.go
  21. 3
      cmd/registry/registryDelete.go
  22. 6
      cmd/root.go
  23. 4
      cmd/util/completion.go
  24. 2
      cmd/util/config/config.go
  25. 3
      cmd/util/filter.go
  26. 1
      cmd/util/plugins.go
  27. 2
      cmd/util/ports.go
  28. 2
      pkg/actions/nodehooks.go
  29. 17
      pkg/client/cluster.go
  30. 1
      pkg/client/clusterName.go
  31. 2
      pkg/client/environment.go
  32. 1
      pkg/client/hooks.go
  33. 8
      pkg/client/host.go
  34. 1
      pkg/client/ipam.go
  35. 5
      pkg/client/kubeconfig.go
  36. 3
      pkg/client/loadbalancer.go
  37. 10
      pkg/client/node.go
  38. 2
      pkg/client/ports.go
  39. 8
      pkg/client/registry.go
  40. 1
      pkg/client/registry_test.go
  41. 5
      pkg/client/tools.go
  42. 1
      pkg/config/config.go
  43. 9
      pkg/config/config_test.go
  44. 2
      pkg/config/jsonschema.go
  45. 4
      pkg/config/jsonschema_test.go
  46. 1
      pkg/config/merge.go
  47. 2
      pkg/config/migrate.go
  48. 2
      pkg/config/migrate_test.go
  49. 1
      pkg/config/process_test.go
  50. 3
      pkg/config/transform.go
  51. 1
      pkg/config/transform_test.go
  52. 2
      pkg/config/v1alpha2/types.go
  53. 2
      pkg/config/v1alpha3/migrations.go
  54. 2
      pkg/config/v1alpha3/types.go
  55. 1
      pkg/config/v1alpha4/migrations.go
  56. 2
      pkg/config/v1alpha4/types.go
  57. 2
      pkg/config/v1alpha5/types.go
  58. 4
      pkg/config/validate.go
  59. 6
      pkg/runtimes/docker/container.go
  60. 1
      pkg/runtimes/docker/docker.go
  61. 1
      pkg/runtimes/docker/host.go
  62. 4
      pkg/runtimes/docker/network.go
  63. 7
      pkg/runtimes/docker/node.go
  64. 1
      pkg/runtimes/docker/translate.go
  65. 2
      pkg/runtimes/docker/translate_test.go
  66. 1
      pkg/runtimes/docker/util.go
  67. 2
      pkg/runtimes/docker/volume.go
  68. 1
      pkg/types/node.go
  69. 2
      pkg/util/files.go
  70. 5
      pkg/util/filter.go
  71. 1
      pkg/util/infofaker.go
  72. 1
      pkg/util/randomString.go
  73. 1
      version/version.go

@ -29,7 +29,6 @@ import (
// NewCmdCluster returns a new cobra command
func NewCmdCluster() *cobra.Command {
// create new cobra command
cmd := &cobra.Command{
Use: "cluster",

@ -71,12 +71,10 @@ var (
)
func initConfig() error {
// Viper for pre-processed config options
ppViper.SetEnvPrefix("K3D")
if l.Log().GetLevel() >= logrus.DebugLevel {
c, _ := yaml.Marshal(ppViper.AllSettings())
l.Log().Debugf("Additional CLI Configuration:\n%s", c)
}
@ -86,7 +84,6 @@ func initConfig() error {
// NewCmdClusterCreate returns a new cobra command
func NewCmdClusterCreate() *cobra.Command {
// create new command
cmd := &cobra.Command{
Use: "create NAME",
@ -97,7 +94,6 @@ func NewCmdClusterCreate() *cobra.Command {
return initConfig()
},
Run: func(cmd *cobra.Command, args []string) {
/*************************
* Compute Configuration *
*************************/
@ -350,7 +346,6 @@ func NewCmdClusterCreate() *cobra.Command {
}
func applyCLIOverrides(cfg conf.SimpleConfig) (conf.SimpleConfig, error) {
/****************************
* Parse and validate flags *
****************************/
@ -407,7 +402,6 @@ func applyCLIOverrides(cfg conf.SimpleConfig) (conf.SimpleConfig, error) {
// volumeFilterMap will map volume mounts to applied node filters
volumeFilterMap := make(map[string][]string, 1)
for _, volumeFlag := range ppViper.GetStringSlice("cli.volumes") {
// split node filter from the specified volume
volume, filters, err := cliutil.SplitFiltersFromFlag(volumeFlag)
if err != nil {
@ -465,7 +459,6 @@ func applyCLIOverrides(cfg conf.SimpleConfig) (conf.SimpleConfig, error) {
// k3sNodeLabelFilterMap will add k3s node label to applied node filters
k3sNodeLabelFilterMap := make(map[string][]string, 1)
for _, labelFlag := range ppViper.GetStringSlice("cli.k3s-node-labels") {
// split node filter from the specified label
label, nodeFilters, err := cliutil.SplitFiltersFromFlag(labelFlag)
if err != nil {
@ -493,7 +486,6 @@ func applyCLIOverrides(cfg conf.SimpleConfig) (conf.SimpleConfig, error) {
// runtimeLabelFilterMap will add container runtime label to applied node filters
runtimeLabelFilterMap := make(map[string][]string, 1)
for _, labelFlag := range ppViper.GetStringSlice("cli.runtime-labels") {
// split node filter from the specified label
label, nodeFilters, err := cliutil.SplitFiltersFromFlag(labelFlag)
if err != nil {
@ -527,7 +519,6 @@ func applyCLIOverrides(cfg conf.SimpleConfig) (conf.SimpleConfig, error) {
// envFilterMap will add container env vars to applied node filters
envFilterMap := make(map[string][]string, 1)
for _, envFlag := range ppViper.GetStringSlice("cli.env") {
// split node filter from the specified env var
env, filters, err := cliutil.SplitFiltersFromFlag(envFlag)
if err != nil {
@ -554,7 +545,6 @@ func applyCLIOverrides(cfg conf.SimpleConfig) (conf.SimpleConfig, error) {
// --k3s-arg
argFilterMap := make(map[string][]string, 1)
for _, argFlag := range ppViper.GetStringSlice("cli.k3sargs") {
// split node filter from the specified arg
arg, filters, err := cliutil.SplitFiltersFromFlag(argFlag)
if err != nil {
@ -598,7 +588,6 @@ func applyCLIOverrides(cfg conf.SimpleConfig) (conf.SimpleConfig, error) {
hostAliasFlags := ppViper.GetStringSlice("hostaliases")
if len(hostAliasFlags) > 0 {
for _, ha := range hostAliasFlags {
// split on :
s := strings.Split(ha, ":")
if len(s) != 2 {

@ -45,7 +45,6 @@ var clusterDeleteCfgViper = viper.New()
// NewCmdClusterDelete returns a new cobra command
func NewCmdClusterDelete() *cobra.Command {
// create new cobra command
cmd := &cobra.Command{
Use: "delete [NAME [NAME ...] | --all]",
@ -88,7 +87,6 @@ func NewCmdClusterDelete() *cobra.Command {
l.Log().Infof("Successfully deleted cluster %s!", c.Name)
}
}
},
}
@ -112,7 +110,6 @@ func NewCmdClusterDelete() *cobra.Command {
// parseDeleteClusterCmd parses the command input into variables required to delete clusters
func parseDeleteClusterCmd(cmd *cobra.Command, args []string) []*k3d.Cluster {
var clusters []*k3d.Cluster
// --all

@ -34,7 +34,6 @@ import (
// NewCmdClusterEdit returns a new cobra command
func NewCmdClusterEdit() *cobra.Command {
// create new cobra command
cmd := &cobra.Command{
Use: "edit CLUSTER",
@ -44,7 +43,6 @@ func NewCmdClusterEdit() *cobra.Command {
Aliases: []string{"update"},
ValidArgsFunction: util.ValidArgsAvailableClusters,
Run: func(cmd *cobra.Command, args []string) {
existingCluster, changeset := parseEditClusterCmd(cmd, args)
l.Log().Debugf("===== Current =====\n%+v\n===== Changeset =====\n%+v\n", existingCluster, changeset)
@ -54,7 +52,6 @@ func NewCmdClusterEdit() *cobra.Command {
}
l.Log().Infof("Successfully updated %s", existingCluster.Name)
},
}
@ -69,7 +66,6 @@ func NewCmdClusterEdit() *cobra.Command {
// parseEditClusterCmd parses the command input into variables required to delete nodes
func parseEditClusterCmd(cmd *cobra.Command, args []string) (*k3d.Cluster, *conf.SimpleConfig) {
existingCluster, err := client.ClusterGet(cmd.Context(), runtimes.SelectedRuntime, &k3d.Cluster{Name: args[0]})
if err != nil {
l.Log().Fatalln(err)
@ -96,7 +92,6 @@ func parseEditClusterCmd(cmd *cobra.Command, args []string) (*k3d.Cluster, *conf
portFilterMap := make(map[string][]string, 1)
for _, portFlag := range portFlags {
// split node filter from the specified volume
portmap, filters, err := cliutil.SplitFiltersFromFlag(portFlag)
if err != nil {

@ -36,7 +36,6 @@ import (
// NewCmdClusterStart returns a new cobra command
func NewCmdClusterStart() *cobra.Command {
startClusterOpts := types.ClusterStartOpts{
Intent: k3d.IntentClusterStart,
}

@ -33,7 +33,6 @@ import (
// NewCmdClusterStop returns a new cobra command
func NewCmdClusterStop() *cobra.Command {
// create new command
cmd := &cobra.Command{
Use: "stop [NAME [NAME...] | --all]",

@ -35,13 +35,11 @@ import (
// NewCmdConfigMigrate returns a new cobra command
func NewCmdConfigMigrate() *cobra.Command {
cmd := &cobra.Command{
Use: "migrate INPUT [OUTPUT]",
Aliases: []string{"update"},
Args: cobra.RangeArgs(1, 2),
Run: func(cmd *cobra.Command, args []string) {
configFile := args[0]
if _, err := os.Stat(configFile); err != nil {
@ -105,7 +103,6 @@ func NewCmdConfigMigrate() *cobra.Command {
l.Log().Fatalln(err)
}
}
},
}

@ -28,7 +28,6 @@ import (
// NewCmdImage returns a new cobra command
func NewCmdImage() *cobra.Command {
// create new cobra command
cmd := &cobra.Command{
Use: "image",

@ -35,7 +35,6 @@ import (
// NewCmdImageImport returns a new cobra command
func NewCmdImageImport() *cobra.Command {
loadImageOpts := k3d.ImageImportOpts{}
// create new command
@ -107,7 +106,6 @@ So if a file './k3d-io/k3d-tools' exists, k3d will try to import it instead of t
// parseLoadImageCmd parses the command input into variables required to create a cluster
func parseLoadImageCmd(cmd *cobra.Command, args []string) ([]string, []*k3d.Cluster) {
// --cluster
clusterNames, err := cmd.Flags().GetStringArray("cluster")
if err != nil {

@ -28,7 +28,6 @@ import (
// NewCmdKubeconfig returns a new cobra command
func NewCmdKubeconfig() *cobra.Command {
// create new cobra command
cmd := &cobra.Command{
Use: "kubeconfig",

@ -39,7 +39,6 @@ type getKubeconfigFlags struct {
// NewCmdKubeconfigGet returns a new cobra command
func NewCmdKubeconfigGet() *cobra.Command {
writeKubeConfigOptions := client.WriteKubeConfigOptions{
UpdateExisting: true,
UpdateCurrentContext: true,

@ -45,7 +45,6 @@ type mergeKubeconfigFlags struct {
// NewCmdKubeconfigMerge returns a new cobra command
func NewCmdKubeconfigMerge() *cobra.Command {
writeKubeConfigOptions := client.WriteKubeConfigOptions{}
mergeKubeconfigFlags := mergeKubeconfigFlags{}
@ -73,7 +72,6 @@ func NewCmdKubeconfigMerge() *cobra.Command {
l.Log().Fatalln(err)
}
} else {
clusternames := []string{k3d.DefaultClusterName}
if len(args) != 0 {
clusternames = args

@ -28,7 +28,6 @@ import (
// NewCmdNode returns a new cobra command
func NewCmdNode() *cobra.Command {
// create new cobra command
cmd := &cobra.Command{
Use: "node",

@ -38,7 +38,6 @@ import (
// NewCmdNodeCreate returns a new cobra command
func NewCmdNodeCreate() *cobra.Command {
createNodeOpts := k3d.NodeCreateOpts{}
// create new command
@ -97,7 +96,6 @@ func NewCmdNodeCreate() *cobra.Command {
// parseCreateNodeCmd parses the command input into variables required to create a node
func parseCreateNodeCmd(cmd *cobra.Command, args []string) ([]*k3d.Node, string) {
// --replicas
replicas, err := cmd.Flags().GetInt("replicas")
if err != nil {

@ -37,7 +37,6 @@ type nodeDeleteFlags struct {
// NewCmdNodeDelete returns a new cobra command
func NewCmdNodeDelete() *cobra.Command {
flags := nodeDeleteFlags{}
// create new cobra command
@ -47,7 +46,6 @@ func NewCmdNodeDelete() *cobra.Command {
Long: `Delete node(s).`,
ValidArgsFunction: util.ValidArgsAvailableNodes,
Run: func(cmd *cobra.Command, args []string) {
nodes := parseDeleteNodeCmd(cmd, args, &flags)
nodeDeleteOpts := k3d.NodeDeleteOpts{SkipLBUpdate: flags.All} // do not update LB, if we're deleting all nodes anyway
@ -76,7 +74,6 @@ func NewCmdNodeDelete() *cobra.Command {
// parseDeleteNodeCmd parses the command input into variables required to delete nodes
func parseDeleteNodeCmd(cmd *cobra.Command, args []string, flags *nodeDeleteFlags) []*k3d.Node {
var nodes []*k3d.Node
var err error

@ -33,7 +33,6 @@ import (
// NewCmdNodeEdit returns a new cobra command
func NewCmdNodeEdit() *cobra.Command {
// create new cobra command
cmd := &cobra.Command{
Use: "edit NODE",
@ -43,7 +42,6 @@ func NewCmdNodeEdit() *cobra.Command {
Aliases: []string{"update"},
ValidArgsFunction: util.ValidArgsAvailableNodes,
Run: func(cmd *cobra.Command, args []string) {
existingNode, changeset := parseEditNodeCmd(cmd, args)
l.Log().Debugf("===== Current =====\n%+v\n===== Changeset =====\n%+v\n", existingNode, changeset)
@ -53,7 +51,6 @@ func NewCmdNodeEdit() *cobra.Command {
}
l.Log().Infof("Successfully updated %s", existingNode.Name)
},
}
@ -68,7 +65,6 @@ func NewCmdNodeEdit() *cobra.Command {
// parseEditNodeCmd parses the command input into variables required to delete nodes
func parseEditNodeCmd(cmd *cobra.Command, args []string) (*k3d.Node, *k3d.Node) {
existingNode, err := client.NodeGet(cmd.Context(), runtimes.SelectedRuntime, &k3d.Node{Name: args[0]})
if err != nil {
l.Log().Fatalln(err)
@ -98,7 +94,6 @@ func parseEditNodeCmd(cmd *cobra.Command, args []string) (*k3d.Node, *k3d.Node)
changeset.Ports = nat.PortMap{}
for _, flag := range portFlags {
portmappings, err := nat.ParsePortSpec(flag)
if err != nil {
l.Log().Fatalf("Failed to parse port spec '%s': %+v", flag, err)

@ -31,7 +31,6 @@ import (
// NewCmdNodeStart returns a new cobra command
func NewCmdNodeStart() *cobra.Command {
// create new command
cmd := &cobra.Command{
Use: "start NODE", // TODO: startNode: allow one or more names or --all

@ -32,7 +32,6 @@ import (
// NewCmdNodeStop returns a new cobra command
func NewCmdNodeStop() *cobra.Command {
// create new command
cmd := &cobra.Command{
Use: "stop NAME", // TODO: stopNode: allow one or more names or --all",

@ -28,7 +28,6 @@ import (
// NewCmdRegistry returns a new cobra command
func NewCmdRegistry() *cobra.Command {
// create new cobra command
cmd := &cobra.Command{
Use: "registry",

@ -66,7 +66,6 @@ kubectl run mynginx --image %s/mynginx:v0.1
// NewCmdRegistryCreate returns a new cobra command
func NewCmdRegistryCreate() *cobra.Command {
flags := &regCreateFlags{}
ppFlags := &regCreatePreProcessedFlags{}
@ -122,7 +121,6 @@ func NewCmdRegistryCreate() *cobra.Command {
// parseCreateRegistryCmd parses the command input into variables required to create a registry
func parseCreateRegistryCmd(cmd *cobra.Command, args []string, flags *regCreateFlags, ppFlags *regCreatePreProcessedFlags) (*k3d.Registry, []*k3d.Cluster) {
// --cluster
clusters := []*k3d.Cluster{}
for _, name := range ppFlags.Clusters {
@ -171,7 +169,6 @@ func parseCreateRegistryCmd(cmd *cobra.Command, args []string, flags *regCreateF
}
volumes = append(volumes, volume)
}
}
return &k3d.Registry{Host: registryName, Image: flags.Image, ExposureOpts: *exposePort, Network: flags.Network, Options: options, Volumes: volumes}, clusters

@ -36,7 +36,6 @@ type registryDeleteFlags struct {
// NewCmdRegistryDelete returns a new cobra command
func NewCmdRegistryDelete() *cobra.Command {
flags := registryDeleteFlags{}
// create new cobra command
@ -47,7 +46,6 @@ func NewCmdRegistryDelete() *cobra.Command {
Aliases: []string{"del", "rm"},
ValidArgsFunction: util.ValidArgsAvailableRegistries,
Run: func(cmd *cobra.Command, args []string) {
nodes := parseRegistryDeleteCmd(cmd, args, &flags)
if len(nodes) == 0 {
@ -73,7 +71,6 @@ func NewCmdRegistryDelete() *cobra.Command {
// parseRegistryDeleteCmd parses the command input into variables required to delete nodes
func parseRegistryDeleteCmd(cmd *cobra.Command, args []string, flags *registryDeleteFlags) []*k3d.Node {
var nodes []*k3d.Node
var err error

@ -67,7 +67,6 @@ type VersionInfo struct {
var flags = RootFlags{}
func NewCmdK3d() *cobra.Command {
// rootCmd represents the base command when called without any subcommands
rootCmd := &cobra.Command{
Use: "k3d",
@ -198,7 +197,6 @@ func initLogging() {
}
l.Log().SetFormatter(formatter)
}
func initRuntime() {
@ -261,7 +259,6 @@ func printVersion() {
}
func NewCmdVersionLs() *cobra.Command {
type VersionLsOutputFormat string
type VersionLsSortMode string
@ -310,7 +307,6 @@ func NewCmdVersionLs() *cobra.Command {
ValidArgs: []string{"k3d", "k3s", "k3d-proxy", "k3d-tools"},
Args: cobra.MatchAll(cobra.ExactArgs(1), cobra.OnlyValidArgs),
Run: func(cmd *cobra.Command, args []string) {
repo, ok := imageRepos[args[0]]
if !ok {
l.Log().Fatalf("Unknown target '%s'", args[0])
@ -384,7 +380,6 @@ func NewCmdVersionLs() *cobra.Command {
filteredTags = filteredTags[0:flags.limit]
}
fmt.Println(strings.Join(filteredTags, "\n"))
},
}
@ -401,7 +396,6 @@ func NewCmdVersionLs() *cobra.Command {
// NewCmdCompletion creates a new completion command
func NewCmdCompletion(rootCmd *cobra.Command) *cobra.Command {
completionFunctions := map[string]func(io.Writer) error{
"bash": rootCmd.GenBashCompletion,
"zsh": func(writer io.Writer) error {

@ -34,7 +34,6 @@ import (
// ValidArgsAvailableClusters is used for shell completion: proposes the list of existing clusters
func ValidArgsAvailableClusters(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
var completions []string
var clusters []*k3d.Cluster
clusters, err := k3dcluster.ClusterList(context.Background(), runtimes.SelectedRuntime)
@ -59,7 +58,6 @@ clusterLoop:
// ValidArgsAvailableNodes is used for shell completion: proposes the list of existing nodes
func ValidArgsAvailableNodes(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
var completions []string
var nodes []*k3d.Node
nodes, err := k3dcluster.NodeList(context.Background(), runtimes.SelectedRuntime)
@ -84,7 +82,6 @@ nodeLoop:
// ValidArgsAvailableRegistries is used for shell completions: proposes the list of existing registries
func ValidArgsAvailableRegistries(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
var completions []string
var nodes []*k3d.Node
nodes, err := k3dcluster.NodeList(context.Background(), runtimes.SelectedRuntime)
@ -111,7 +108,6 @@ nodeLoop:
// ValidArgsNodeRoles is used for shell completion: proposes the list of possible node roles
func ValidArgsNodeRoles(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
var completions []string
roles := []string{string(k3d.ServerRole), string(k3d.AgentRole)}

@ -38,7 +38,6 @@ import (
)
func InitViperWithConfigFile(cfgViper *viper.Viper, configFile string) error {
// viper for the general config (file, env and non pre-processed flags)
cfgViper.SetEnvPrefix("K3D")
cfgViper.AutomaticEnv()
@ -48,7 +47,6 @@ func InitViperWithConfigFile(cfgViper *viper.Viper, configFile string) error {
// Set config file, if specified
if configFile != "" {
streams := util.StandardIOStreams()
//flag to mark from where we read the config
fromStdIn := false

@ -30,7 +30,6 @@ import (
// SplitFiltersFromFlag separates a flag's value from the node filter, if there is one
func SplitFiltersFromFlag(flag string) (string, []string, error) {
/* Case 1) no filter specified */
if !strings.Contains(flag, "@") {
@ -44,7 +43,6 @@ func SplitFiltersFromFlag(flag string) (string, []string, error) {
buffer := ""
for i, it := range split {
// Case 1: There's a '\' just before the '@' sign -> Should it be escaped (aka be a literal '@')?
if strings.HasSuffix(it, "\\") && i != len(split)-1 {
// Case 1.1: Escaped backslash
@ -75,5 +73,4 @@ func SplitFiltersFromFlag(flag string) (string, []string, error) {
}
return newsplit[0], strings.Split(newsplit[1], ";"), nil
}

@ -61,7 +61,6 @@ func HandlePlugin(ctx context.Context, args []string) (bool, error) {
}
return true, ExecPlugin(ctx, execPath, args[len(argsPrefix):], os.Environ())
}
// FindPlugin tries to find the plugin executable on the filesystem

@ -38,7 +38,6 @@ var apiPortRegexp = regexp.MustCompile(`^(?P<hostref>(?P<hostip>\d{1,3}\.\d{1,3}
// ParsePortExposureSpec parses/validates a string to create an exposePort struct from it
func ParsePortExposureSpec(exposedPortSpec, internalPort string) (*k3d.ExposureOpts, error) {
match := apiPortRegexp.FindStringSubmatch(exposedPortSpec)
if len(match) == 0 {
@ -108,7 +107,6 @@ func ParsePortExposureSpec(exposedPortSpec, internalPort string) (*k3d.ExposureO
api.Binding = portMapping[0].Binding
return api, nil
}
// ValidatePortMap validates a port mapping

@ -129,7 +129,6 @@ func (act RewriteFileAction) Run(ctx context.Context, node *k3d.Node) error {
}
return nil
}
// ExecAction executes some command inside the node
@ -168,7 +167,6 @@ func (act ExecAction) Run(ctx context.Context, node *k3d.Node) error {
}
return fmt.Errorf("error executing hook %s in node %s: %w", act.Name(), node.Name, err)
}
}
return nil
}

@ -220,7 +220,6 @@ func ClusterPrep(ctx context.Context, runtime k3drt.Runtime, clusterConfig *conf
})
registryConfig = regConf
}
// merge with pre-existing, referenced registries.yaml
if clusterConfig.ClusterCreateOpts.Registries.Config != nil {
@ -251,7 +250,6 @@ func ClusterPrep(ctx context.Context, runtime k3drt.Runtime, clusterConfig *conf
}
return nil
}
// ClusterPrepNetwork creates a new cluster network, if needed or sets everything up to re-use an existing network
@ -332,7 +330,6 @@ func ClusterPrepImageVolume(ctx context.Context, runtime k3drt.Runtime, cluster
// - some containerized k3s nodes
// - a docker network
func ClusterCreate(ctx context.Context, runtime k3drt.Runtime, cluster *k3d.Cluster, clusterCreateOpts *k3d.ClusterCreateOpts) error {
l.Log().Tracef(`
===== Creating Cluster =====
@ -431,7 +428,6 @@ ClusterCreatOpts:
// node role specific settings
if node.Role == k3d.ServerRole {
if cluster.Network.IPAM.Managed {
ip, err := GetIP(ctx, runtime, &cluster.Network)
if err != nil {
@ -450,7 +446,6 @@ ClusterCreatOpts:
node.Env = append(node.Env, fmt.Sprintf("%s=%s", k3s.EnvClusterConnectURL, connectionURL))
node.RuntimeLabels[k3d.LabelServerIsInit] = "false" // set label, that this server node is not the init server
}
} else if node.Role == k3d.AgentRole {
node.Env = append(node.Env, fmt.Sprintf("%s=%s", k3s.EnvClusterConnectURL, connectionURL))
}
@ -492,13 +487,11 @@ ClusterCreatOpts:
return fmt.Errorf("failed init node setup: %w", err)
}
serverCount++
}
// create all other nodes, but skip the init node
for _, node := range cluster.Nodes {
if node.Role == k3d.ServerRole {
// skip the init node here
if node == cluster.InitNode {
continue
@ -513,7 +506,6 @@ ClusterCreatOpts:
time.Sleep(1 * time.Second) // FIXME: arbitrary wait for one second to avoid race conditions of servers registering
serverCount++
}
if node.Role == k3d.ServerRole || node.Role == k3d.AgentRole {
if err := nodeSetup(node); err != nil {
@ -589,7 +581,6 @@ ClusterCreatOpts:
// ClusterDelete deletes an existing cluster
func ClusterDelete(ctx context.Context, runtime k3drt.Runtime, cluster *k3d.Cluster, opts k3d.ClusterDeleteOpts) error {
l.Log().Infof("Deleting cluster '%s'", cluster.Name)
cluster, err := ClusterGet(ctx, runtime, cluster)
if err != nil {
@ -641,7 +632,6 @@ func ClusterDelete(ctx context.Context, runtime k3drt.Runtime, cluster *k3d.Clus
l.Log().Infof("Deleting cluster network '%s'", cluster.Network.Name)
if err := runtime.DeleteNetwork(ctx, cluster.Network.Name); err != nil {
if errors.Is(err, runtimeErr.ErrRuntimeNetworkNotEmpty) { // there are still containers connected to that network
connectedNodes, err := runtime.GetNodesInNetwork(ctx, cluster.Network.Name) // check, if there are any k3d nodes connected to the cluster
if err != nil {
l.Log().Warningf("Failed to check cluster network for connected nodes: %+v", err)
@ -751,7 +741,6 @@ func populateClusterFieldsFromLabels(cluster *k3d.Cluster) error {
networkExternalSet := false
for _, node := range cluster.Nodes {
// get the name of the cluster network
if cluster.Network.Name == "" {
if networkName, ok := node.RuntimeLabels[k3d.LabelNetwork]; ok {
@ -820,11 +809,9 @@ func ClusterGet(ctx context.Context, runtime k3drt.Runtime, cluster *k3d.Cluster
// append nodes
for _, node := range nodes {
// check if there's already a node in the struct
overwroteExisting := false
for _, existingNode := range cluster.Nodes {
// overwrite existing node
if existingNode.Name == node.Name {
mergo.MergeWithOverwrite(existingNode, node)
@ -836,7 +823,6 @@ func ClusterGet(ctx context.Context, runtime k3drt.Runtime, cluster *k3d.Cluster
if !overwroteExisting {
cluster.Nodes = append(cluster.Nodes, node)
}
}
// Loadbalancer
@ -1018,7 +1004,6 @@ func ClusterStart(ctx context.Context, runtime k3drt.Runtime, cluster *k3d.Clust
*/
if len(servers) > 0 || len(agents) > 0 { // TODO: make checks for required cluster start actions cleaner
postStartErrgrp, postStartErrgrpCtx := errgroup.WithContext(ctx)
/*** DNS ***/
@ -1044,7 +1029,6 @@ func ClusterStart(ctx context.Context, runtime k3drt.Runtime, cluster *k3d.Clust
// -> inject hostAliases and network members into CoreDNS configmap
if len(servers) > 0 {
postStartErrgrp.Go(func() error {
hosts := ""
// hosts: hostAliases (including host.k3d.internal)
@ -1101,7 +1085,6 @@ func ClusterStart(ctx context.Context, runtime k3drt.Runtime, cluster *k3d.Clust
// get the first server in the list and run action on it once it's ready for it
for _, n := range servers {
// do not try to run the action, if CoreDNS is disabled on K3s level
for _, flag := range n.Args {
if strings.HasPrefix(flag, "--disable") && strings.Contains(flag, "coredns") {

@ -47,7 +47,6 @@ func CheckName(name string) error {
// ValidateHostname ensures that a cluster name is also a valid host name according to RFC 1123.
func ValidateHostname(name string) error {
if len(name) == 0 {
return fmt.Errorf("No name provided")
}

@ -32,7 +32,6 @@ import (
)
func GatherEnvironmentInfo(ctx context.Context, runtime runtimes.Runtime, cluster *k3d.Cluster) (*k3d.EnvironmentInfo, error) {
envInfo := &k3d.EnvironmentInfo{}
rtimeInfo, err := runtime.Info()
@ -60,5 +59,4 @@ func GatherEnvironmentInfo(ctx context.Context, runtime runtimes.Runtime, cluste
}
return envInfo, nil
}

@ -42,7 +42,6 @@ func NewHostAliasesInjectEtcHostsAction(runtime runtimes.Runtime, hostAliases []
NoCopy: true,
},
RewriteFunc: func(input []byte) ([]byte, error) {
tmpHosts, err := os.CreateTemp("", "k3d-hostsfile-*")
if err != nil {
return nil, fmt.Errorf("error creating temp hosts file: %w", err)

@ -56,7 +56,6 @@ var (
// GetHostIP returns the routable IP address to be able to access services running on the host system from inside the cluster.
// This depends on the Operating System and the chosen Runtime.
func GetHostIP(ctx context.Context, runtime runtimes.Runtime, cluster *k3d.Cluster) (net.IP, error) {
rtimeInfo, err := runtime.Info()
if err != nil {
return nil, err
@ -66,10 +65,8 @@ func GetHostIP(ctx context.Context, runtime runtimes.Runtime, cluster *k3d.Clust
// Docker Runtime
if runtime == runtimes.Docker {
// Docker (for Desktop) on MacOS or Windows
if docker.IsDockerDesktop(rtimeInfo.OS) {
toolsNode, err := EnsureToolsNode(ctx, runtime, cluster)
if err != nil {
return nil, fmt.Errorf("failed to ensure that k3d-tools node is running to get host IP :%w", err)
@ -88,7 +85,6 @@ func GetHostIP(ctx context.Context, runtime runtimes.Runtime, cluster *k3d.Clust
}
l.Log().Debugf("[GetHostIP on Docker Desktop] failed to resolve 'host.docker.internal' from inside the k3d-tools node: %v", err)
}
// Colima
@ -113,16 +109,13 @@ func GetHostIP(ctx context.Context, runtime runtimes.Runtime, cluster *k3d.Clust
l.Log().Infof("HostIP: using network gateway %s address", ip)
return ip, nil
}
// Catch all other runtime selections
return nil, fmt.Errorf("GetHostIP only implemented for the docker runtime")
}
func resolveHostnameFromInside(ctx context.Context, rtime runtimes.Runtime, node *k3d.Node, hostname string, cmd ResolveHostCmd) (net.IP, error) {
errPrefix := fmt.Errorf("error resolving hostname %s from inside node %s", hostname, node.Name)
logreader, execErr := rtime.ExecInNodeGetLogs(ctx, node, []string{"sh", "-c", fmt.Sprintf(cmd.Cmd, hostname)})
@ -166,5 +159,4 @@ func resolveHostnameFromInside(ctx context.Context, rtime runtimes.Runtime, node
l.Log().Debugf("Hostname '%s' resolved to address '%s' inside node %s", hostname, submatches["ip"], node.Name)
return net.ParseIP(submatches["ip"]), nil
}

@ -33,7 +33,6 @@ import (
// GetIP checks a given network for a free IP and returns it, if possible
func GetIP(ctx context.Context, runtime k3drt.Runtime, network *k3d.ClusterNetwork) (netaddr.IP, error) {
network, err := runtime.GetNetwork(ctx, network)
if err != nil {
return netaddr.IP{}, fmt.Errorf("runtime failed to get network '%s': %w", network.Name, err)

@ -49,7 +49,6 @@ type WriteKubeConfigOptions struct {
// 2. modifies it by updating some fields with cluster-specific information
// 3. writes it to the specified output
func KubeconfigGetWrite(ctx context.Context, runtime runtimes.Runtime, cluster *k3d.Cluster, output string, writeKubeConfigOptions *WriteKubeConfigOptions) (string, error) {
// get kubeconfig from cluster node
kubeconfig, err := KubeconfigGet(ctx, runtime, cluster)
if err != nil {
@ -75,7 +74,6 @@ func KubeconfigGetWrite(ctx context.Context, runtime runtimes.Runtime, cluster *
for {
existingKubeConfig, err = clientcmd.LoadFromFile(output) // will return an empty config if file is empty
if err != nil {
// the output file does not exist: try to create it and try again
if os.IsNotExist(err) && firstRun {
l.Log().Debugf("Output path '%s' doesn't exist, trying to create it...", output)
@ -103,7 +101,6 @@ func KubeconfigGetWrite(ctx context.Context, runtime runtimes.Runtime, cluster *
// update existing kubeconfig, but error out if there are conflicting fields but we don't want to update them
return output, KubeconfigMerge(ctx, kubeconfig, existingKubeConfig, output, writeKubeConfigOptions.UpdateExisting, writeKubeConfigOptions.UpdateCurrentContext)
}
// KubeconfigGet grabs the kubeconfig file from /output from a server node container,
@ -223,12 +220,10 @@ func KubeconfigWriteToPath(ctx context.Context, kubeconfig *clientcmdapi.Config,
l.Log().Debugf("Wrote kubeconfig to '%s'", output.Name())
return nil
}
// KubeconfigMerge merges a new kubeconfig into an existing kubeconfig and returns the result
func KubeconfigMerge(ctx context.Context, newKubeConfig *clientcmdapi.Config, existingKubeConfig *clientcmdapi.Config, outPath string, overwriteConflicting bool, updateCurrentContext bool) error {
l.Log().Tracef("Merging new Kubeconfig:\n%+v\n>>> into existing Kubeconfig:\n%+v", newKubeConfig, existingKubeConfig)
// Overwrite values in existing kubeconfig

@ -50,7 +50,6 @@ var (
// UpdateLoadbalancerConfig updates the loadbalancer config with an updated list of servers belonging to that cluster
func UpdateLoadbalancerConfig(ctx context.Context, runtime runtimes.Runtime, cluster *k3d.Cluster) error {
var err error
// update cluster details to ensure that we have the latest node list
cluster, err = ClusterGet(ctx, runtime, cluster)
@ -113,7 +112,6 @@ func UpdateLoadbalancerConfig(ctx context.Context, runtime runtimes.Runtime, clu
}
func GetLoadbalancerConfig(ctx context.Context, runtime runtimes.Runtime, cluster *k3d.Cluster) (types.LoadbalancerConfig, error) {
var cfg k3d.LoadbalancerConfig
if cluster.ServerLoadBalancer == nil || cluster.ServerLoadBalancer.Node == nil {
@ -224,7 +222,6 @@ func LoadbalancerPrepare(ctx context.Context, runtime runtimes.Runtime, cluster
}
return lbNode, nil
}
func loadbalancerAddPortConfigs(loadbalancer *k3d.Loadbalancer, portmapping nat.PortMapping, targetNodes []*k3d.Node) error {

@ -421,7 +421,6 @@ func NodeRun(ctx context.Context, runtime runtimes.Runtime, node *k3d.Node, node
// NodeStart starts an existing node
func NodeStart(ctx context.Context, runtime runtimes.Runtime, node *k3d.Node, nodeStartOpts *k3d.NodeStartOpts) error {
// return early, if the node is already running
if node.State.Running {
l.Log().Infof("Node %s is already running", node.Name)
@ -489,9 +488,7 @@ func NodeStart(ctx context.Context, runtime runtimes.Runtime, node *k3d.Node, no
}
func enableFixes(ctx context.Context, runtime runtimes.Runtime, node *k3d.Node, nodeStartOpts *k3d.NodeStartOpts) error {
if node.Role == k3d.ServerRole || node.Role == k3d.AgentRole {
// FIXME: FixCgroupV2 - to be removed when fixed upstream
// auto-enable, if needed
EnableCgroupV2FixIfNeeded(runtime)
@ -806,7 +803,6 @@ func NodeWaitForLogMessage(ctx context.Context, runtime runtimes.Runtime, node *
}
time.Sleep(500 * time.Millisecond)
}
}(ctx, runtime, node, since, donechan)
// pre-building error message in case the node stops returning logs for some reason: to be enriched with scanner error
@ -817,7 +813,6 @@ func NodeWaitForLogMessage(ctx context.Context, runtime runtimes.Runtime, node *
// e.g. when a new server is joining an existing cluster and has to wait for another member to finish learning.
// The logstream returned by docker ends everytime the container restarts, so we have to start from the beginning.
for i := 0; i < backOffLimit; i++ {
// get the log stream (reader is following the logstream)
out, err := runtime.GetNodeLogs(ctx, node, since, &runtimeTypes.NodeLogsOpts{Follow: true})
if out != nil {
@ -856,7 +851,6 @@ func NodeWaitForLogMessage(ctx context.Context, runtime runtimes.Runtime, node *
}
previousline = scanner.Text()
}
if e := scanner.Err(); e != nil {
@ -923,7 +917,6 @@ nodeLoop:
// NodeEdit let's you update an existing node
func NodeEdit(ctx context.Context, runtime runtimes.Runtime, existingNode, changeset *k3d.Node) error {
/*
* Make a deep copy of the existing node
*/
@ -944,7 +937,6 @@ func NodeEdit(ctx context.Context, runtime runtimes.Runtime, existingNode, chang
for port, portbindings := range changeset.Ports {
loopChangesetPortbindings:
for _, portbinding := range portbindings {
// loop over existing portbindings to avoid port collisions (docker doesn't check for it)
for _, existingPB := range result.Ports[port] {
if util.IsPortBindingEqual(portbinding, existingPB) { // also matches on "equal" HostIPs (127.0.0.1, "", 0.0.0.0)
@ -997,7 +989,6 @@ func NodeEdit(ctx context.Context, runtime runtimes.Runtime, existingNode, chang
}
func NodeReplace(ctx context.Context, runtime runtimes.Runtime, old, new *k3d.Node) error {
// rename existing node
oldNameTemp := fmt.Sprintf("%s-%s", old.Name, util.GenerateRandomString(5))
oldNameOriginal := old.Name
@ -1053,7 +1044,6 @@ type CopyNodeOpts struct {
}
func CopyNode(ctx context.Context, src *k3d.Node, opts CopyNodeOpts) (*k3d.Node, error) {
targetCopy, err := copystruct.Copy(src)
if err != nil {
return nil, fmt.Errorf("failed to copy node struct: %w", err)

@ -102,7 +102,6 @@ func TransformPorts(ctx context.Context, runtime runtimes.Runtime, cluster *k3d.
return fmt.Errorf("error adding port mappings: unknown suffix %s", suffix)
}
}
}
// print generated loadbalancer config if exists
@ -119,7 +118,6 @@ func TransformPorts(ctx context.Context, runtime runtimes.Runtime, cluster *k3d.
}
func addPortMappings(node *k3d.Node, portmappings []nat.PortMapping) error {
if node.Ports == nil {
node.Ports = nat.PortMap{}
}

@ -53,7 +53,6 @@ func RegistryRun(ctx context.Context, runtime runtimes.Runtime, reg *k3d.Registr
// RegistryCreate creates a registry node
func RegistryCreate(ctx context.Context, runtime runtimes.Runtime, reg *k3d.Registry) (*k3d.Node, error) {
// registry name
if len(reg.Host) == 0 {
reg.Host = k3d.DefaultRegistryName
@ -127,12 +126,10 @@ func RegistryCreate(ctx context.Context, runtime runtimes.Runtime, reg *k3d.Regi
l.Log().Infof("Successfully created registry '%s'", registryNode.Name)
return registryNode, nil
}
// RegistryConnectClusters connects an existing registry to one or more clusters
func RegistryConnectClusters(ctx context.Context, runtime runtimes.Runtime, registryNode *k3d.Node, clusters []*k3d.Cluster) error {
// find registry node
registryNode, err := NodeGet(ctx, runtime, registryNode)
if err != nil {
@ -164,7 +161,6 @@ func RegistryConnectClusters(ctx context.Context, runtime runtimes.Runtime, regi
// RegistryConnectNetworks connects an existing registry to one or more networks
func RegistryConnectNetworks(ctx context.Context, runtime runtimes.Runtime, registryNode *k3d.Node, networks []string) error {
// find registry node
registryNode, err := NodeGet(ctx, runtime, registryNode)
if err != nil {
@ -220,7 +216,6 @@ func RegistryGenerateK3sConfig(ctx context.Context, registries []*k3d.Registry)
regConf.Mirrors[reg.Options.Proxy.RemoteURL] = wharfie.Mirror{
Endpoints: []string{fmt.Sprintf("http://%s", internalAddress)},
}
}
}
@ -242,7 +237,6 @@ func RegistryGet(ctx context.Context, runtime runtimes.Runtime, name string) (*k
}
// TODO: finish RegistryGet
return registry, nil
}
// RegistryFromNode transforms a node spec to a registry spec
@ -273,12 +267,10 @@ func RegistryFromNode(node *k3d.Node) (*k3d.Registry, error) {
l.Log().Tracef("Got registry %+v from node %+v", registry, node)
return registry, nil
}
// RegistryGenerateLocalRegistryHostingConfigMapYAML generates a ConfigMap used to advertise the registries in the cluster
func RegistryGenerateLocalRegistryHostingConfigMapYAML(ctx context.Context, runtime runtimes.Runtime, registries []*k3d.Registry) ([]byte, error) {
type cmMetadata struct {
Name string `json:"name"`
Namespace string `json:"namespace"`

@ -64,5 +64,4 @@ metadata:
if !(strings.TrimSpace(string(cm)) == strings.TrimSpace(expectedYAMLString)) {
t.Errorf("Computed configmap\n-> Actual:\n%s\n does not match expected YAML\n-> Expected:\n%s", strings.TrimSpace(string(cm)), strings.TrimSpace(expectedYAMLString))
}
}

@ -42,7 +42,6 @@ import (
// ImageImportIntoClusterMulti starts up a k3d tools container for the selected cluster and uses it to export
// images from the runtime to import them into the nodes of the selected cluster
func ImageImportIntoClusterMulti(ctx context.Context, runtime runtimes.Runtime, images []string, cluster *k3d.Cluster, opts k3d.ImageImportOpts) error {
// stdin case
if len(images) == 1 && images[0] == "-" {
err := loadImageFromStream(ctx, runtime, os.Stdin, cluster, []string{"stdin"})
@ -181,7 +180,6 @@ func importWithStream(ctx context.Context, runtime runtimes.Runtime, cluster *k3
return fmt.Errorf("could not load image to cluster from stream %s: %w", imagesFromRuntime, err)
}
// load the images directly into the nodes
}
if len(imagesFromTar) > 0 {
@ -320,7 +318,6 @@ func dockerSpecialImageNameEqual(requestedImageName string, runtimeImageName str
if strings.HasPrefix(requestedImageName, prefix) {
return imageNamesEqual(strings.TrimPrefix(requestedImageName, prefix), runtimeImageName)
}
}
return false
@ -398,7 +395,6 @@ func EnsureToolsNode(ctx context.Context, runtime runtimes.Runtime, cluster *k3d
var toolsNode *k3d.Node
toolsNode, err := runtime.GetNode(ctx, &k3d.Node{Name: fmt.Sprintf("%s-%s-tools", k3d.DefaultObjectNamePrefix, cluster.Name)})
if err != nil || toolsNode == nil {
// Get more info on the cluster, if required
var imageVolume string
if cluster.Network.Name == "" || cluster.ImageVolume == "" {
@ -450,5 +446,4 @@ func EnsureToolsNode(ctx context.Context, runtime runtimes.Runtime, cluster *k3d
}
return toolsNode, err
}

@ -56,7 +56,6 @@ func GetSchemaByVersion(apiVersion string) ([]byte, error) {
}
func FromViper(config *viper.Viper) (types.Config, error) {
var cfg types.Config
var err error

@ -34,7 +34,6 @@ import (
)
func TestReadSimpleConfig(t *testing.T) {
exposedAPI := conf.SimpleExposureOpts{}
exposedAPI.HostIP = "0.0.0.0"
exposedAPI.HostPort = "6443"
@ -137,11 +136,9 @@ func TestReadSimpleConfig(t *testing.T) {
if diff := deep.Equal(cfg, expectedConfig); diff != nil {
t.Errorf("Actual representation\n%+v\ndoes not match expected representation\n%+v\nDiff:\n%+v", cfg, expectedConfig, diff)
}
}
func TestReadClusterConfig(t *testing.T) {
expectedConfig := conf.ClusterConfig{
TypeMeta: configtypes.TypeMeta{
APIVersion: "k3d.io/v1alpha5",
@ -182,11 +179,9 @@ func TestReadClusterConfig(t *testing.T) {
if diff := deep.Equal(readConfig, expectedConfig); diff != nil {
t.Errorf("Actual representation\n%+v\ndoes not match expected representation\n%+v\nDiff:\n%+v", readConfig, expectedConfig, diff)
}
}
func TestReadClusterListConfig(t *testing.T) {
expectedConfig := conf.ClusterListConfig{
TypeMeta: configtypes.TypeMeta{
APIVersion: "k3d.io/v1alpha5",
@ -238,11 +233,9 @@ func TestReadClusterListConfig(t *testing.T) {
if diff := deep.Equal(readConfig, expectedConfig); diff != nil {
t.Errorf("Actual representation\n%+v\ndoes not match expected representation\n%+v\nDiff:\n%+v", readConfig, expectedConfig, diff)
}
}
func TestReadUnknownConfig(t *testing.T) {
cfgFile := "./test_assets/config_test_unknown.yaml"
config := viper.New()
@ -261,11 +254,9 @@ func TestReadUnknownConfig(t *testing.T) {
if err == nil {
t.Fail()
}
}
func TestReadSimpleConfigRegistries(t *testing.T) {
exposedAPI := conf.SimpleExposureOpts{}
exposedAPI.HostIP = "0.0.0.0"
exposedAPI.HostPort = "6443"

@ -54,7 +54,6 @@ func ValidateSchemaFile(filepath string, schema []byte) error {
// ValidateSchema validates a YAML construct (non-struct representation) against a JSON Schema
func ValidateSchema(content interface{}, schemaJSON []byte) error {
contentYaml, err := yaml.Marshal(content)
if err != nil {
return err
@ -65,7 +64,6 @@ func ValidateSchema(content interface{}, schemaJSON []byte) error {
}
return ValidateSchemaJSON(contentJSON, schemaJSON)
}
func ValidateSchemaJSON(contentJSON []byte, schemaJSON []byte) error {

@ -28,17 +28,14 @@ import (
)
func TestValidateSchema(t *testing.T) {
cfgPath := "./test_assets/config_test_simple.yaml"
if err := ValidateSchemaFile(cfgPath, []byte(conf.JSONSchema)); err != nil {
t.Errorf("Validation of config file %s against the default schema failed: %+v", cfgPath, err)
}
}
func TestValidateSchemaFail(t *testing.T) {
cfgPath := "./test_assets/config_test_simple_invalid_servers.yaml"
var err error
@ -52,5 +49,4 @@ func TestValidateSchemaFail(t *testing.T) {
if err.Error() != expectedErrorText {
t.Errorf("Actual validation error\n%s\ndoes not match expected error\n%s\n", err.Error(), expectedErrorText)
}
}

@ -35,7 +35,6 @@ func MergeSimple(dest, src conf.SimpleConfig) (*conf.SimpleConfig, error) {
l.Log().Debugf("Merging %+v into %+v", src, dest)
if err := mergo.Merge(&dest, src); err != nil {
return nil, fmt.Errorf("failed to merge configs: %w", err)
}

@ -29,7 +29,6 @@ import (
)
func Migrate(config types.Config, targetVersion string) (types.Config, error) {
migration, ok := getMigrations(targetVersion)[config.GetAPIVersion()]
if !ok {
return nil, fmt.Errorf("no migration possible from '%s' to '%s'", config.GetAPIVersion(), targetVersion)
@ -50,5 +49,4 @@ func Migrate(config types.Config, targetVersion string) (types.Config, error) {
}
return cfg, err
}

@ -63,7 +63,6 @@ func TestMigrate(t *testing.T) {
for name, tc := range tests {
t.Run(name, func(t *testing.T) {
actualViper := viper.New()
expectedViper := viper.New()
@ -102,7 +101,6 @@ func TestMigrate(t *testing.T) {
if diff := deep.Equal(actualCfg, expectedCfg); diff != nil {
t.Fatalf("Actual\n%#v\ndoes not match expected\n%+v\nDiff:\n%#v", actualCfg, expectedCfg, diff)
}
})
}
}

@ -77,5 +77,4 @@ func TestProcessClusterConfig(t *testing.T) {
t.Logf("\n===== Resulting Cluster Config (host network) =====\n%+v\n===============\n", clusterCfg)
t.Logf("\n===== First Node in Resulting Cluster Config (host network) =====\n%+v\n===============\n", clusterCfg.Cluster.Nodes[0])
}

@ -47,7 +47,6 @@ import (
// TransformSimpleToClusterConfig transforms a simple configuration to a full-fledged cluster configuration
func TransformSimpleToClusterConfig(ctx context.Context, runtime runtimes.Runtime, simpleConfig conf.SimpleConfig) (*conf.ClusterConfig, error) {
// set default cluster name
if simpleConfig.Name == "" {
simpleConfig.Name = k3d.DefaultClusterName
@ -209,7 +208,6 @@ func TransformSimpleToClusterConfig(ctx context.Context, runtime runtimes.Runtim
}
k, v := util.SplitLabelKeyValue(k3sNodeLabelWithNodeFilters.Label)
node.K3sNodeLabels[k] = v
}
}
@ -311,7 +309,6 @@ func TransformSimpleToClusterConfig(ctx context.Context, runtime runtimes.Runtim
* Registries
*/
if simpleConfig.Registries.Create != nil {
epSpecHost := "0.0.0.0"
epSpecPort := "random"

@ -51,5 +51,4 @@ func TestTransformSimpleConfigToClusterConfig(t *testing.T) {
}
t.Logf("\n===== Resulting Cluster Config =====\n%+v\n===============\n", clusterCfg)
}

@ -181,7 +181,6 @@ func (c ClusterListConfig) GetAPIVersion() string {
}
func GetConfigByKind(kind string) (configtypes.Config, error) {
// determine config kind
switch kind {
case "simple":
@ -195,5 +194,4 @@ func GetConfigByKind(kind string) (configtypes.Config, error) {
default:
return nil, fmt.Errorf("unknown `kind` '%s' in config file", kind)
}
}

@ -140,11 +140,9 @@ func MigrateV1Alpha2(input configtypes.Config) (configtypes.Config, error) {
l.Log().Debugf("Migrated config: %+v", cfg)
return cfg, nil
}
l.Log().Debugf("No migration needed for %s#%s -> %s#%s", input.GetAPIVersion(), input.GetKind(), ApiVersion, input.GetKind())
return input, nil
}

@ -221,7 +221,6 @@ func (c ClusterListConfig) GetAPIVersion() string {
}
func GetConfigByKind(kind string) (config.Config, error) {
// determine config kind
switch strings.ToLower(kind) {
case "simple":
@ -235,5 +234,4 @@ func GetConfigByKind(kind string) (config.Config, error) {
default:
return nil, fmt.Errorf("unknown `kind` '%s' in config file", kind)
}
}

@ -91,7 +91,6 @@ func MigrateV1Alpha3(input configtypes.Config) (configtypes.Config, error) {
l.Log().Debugf("Migrated config: %+v", cfg)
return cfg, nil
}
l.Log().Debugf("No migration needed for %s#%s -> %s#%s", input.GetAPIVersion(), input.GetKind(), ApiVersion, input.GetKind())

@ -204,7 +204,6 @@ func (c ClusterListConfig) GetAPIVersion() string {
}
func GetConfigByKind(kind string) (config.Config, error) {
// determine config kind
switch strings.ToLower(kind) {
case "simple":
@ -218,5 +217,4 @@ func GetConfigByKind(kind string) (config.Config, error) {
default:
return nil, fmt.Errorf("unknown `kind` '%s' in config file", kind)
}
}

@ -211,7 +211,6 @@ func (c ClusterListConfig) GetAPIVersion() string {
}
func GetConfigByKind(kind string) (config.Config, error) {
// determine config kind
switch strings.ToLower(kind) {
case "simple":
@ -225,5 +224,4 @@ func GetConfigByKind(kind string) (config.Config, error) {
default:
return nil, fmt.Errorf("unknown `kind` '%s' in config file", kind)
}
}

@ -68,7 +68,6 @@ func ValidateClusterConfig(ctx context.Context, runtime runtimes.Runtime, config
if _, err := dockerunits.RAMInBytes(config.ClusterCreateOpts.ServersMemory); err != nil {
return fmt.Errorf("provided servers memory limit value is invalid: %w", err)
}
}
if config.ClusterCreateOpts.AgentsMemory != "" {
@ -99,15 +98,12 @@ func ValidateClusterConfig(ctx context.Context, runtime runtimes.Runtime, config
}
}
}
}
// validate nodes one by one
for _, node := range config.Cluster.Nodes {
// volumes have to be either an existing path on the host or a named runtime volume
for _, volume := range node.Volumes {
if err := runtimeutil.ValidateVolumeMount(ctx, runtime, volume, &config.Cluster); err != nil {
return fmt.Errorf("failed to validate volume mount '%s': %w", volume, err)
}

@ -39,7 +39,6 @@ import (
// createContainer creates a new docker container from translated specs
func createContainer(ctx context.Context, dockerNode *NodeInDocker, name string) (string, error) {
l.Log().Tracef("Creating docker container with translated config\n%+v\n", dockerNode)
// initialize docker client
@ -82,7 +81,6 @@ func startContainer(ctx context.Context, ID string) error {
// removeContainer deletes a running container (like docker rm -f)
func removeContainer(ctx context.Context, ID string) error {
// (0) create docker client
docker, err := GetDockerClient()
if err != nil {
@ -108,7 +106,6 @@ func removeContainer(ctx context.Context, ID string) error {
// pullImage pulls a container image and outputs progress if --verbose flag is set
func pullImage(ctx context.Context, docker client.APIClient, image string) error {
resp, err := docker.ImagePull(ctx, image, types.ImagePullOptions{})
if err != nil {
return fmt.Errorf("docker failed to pull the image '%s': %w", image, err)
@ -128,11 +125,9 @@ func pullImage(ctx context.Context, docker client.APIClient, image string) error
}
return nil
}
func getNodeContainer(ctx context.Context, node *k3d.Node) (*types.Container, error) {
// (0) create docker client
docker, err := GetDockerClient()
if err != nil {
@ -169,7 +164,6 @@ func getNodeContainer(ctx context.Context, node *k3d.Node) (*types.Container, er
}
return &containers[0], nil
}
// executes an arbitrary command in a container while returning its exit code.

@ -44,7 +44,6 @@ func (d Docker) ID() string {
// GetHost returns the docker daemon host
func (d Docker) GetHost() string {
// a) docker-machine
machineIP, err := d.GetDockerMachineIP()
if err != nil {

@ -34,5 +34,4 @@ func (d Docker) GetHostIP(ctx context.Context, network string) (net.IP, error) {
return nil, fmt.Errorf("failed to get gateway IP of docker network '%s': %w", network, err)
}
return ip, nil
}

@ -126,13 +126,11 @@ func (d Docker) GetNetwork(ctx context.Context, searchNet *k3d.ClusterNetwork) (
}
return network, nil
}
// CreateNetworkIfNotPresent creates a new docker network
// @return: network, exists, error
func (d Docker) CreateNetworkIfNotPresent(ctx context.Context, inNet *k3d.ClusterNetwork) (*k3d.ClusterNetwork, bool, error) {
// (0) create new docker client
docker, err := GetDockerClient()
if err != nil {
@ -267,7 +265,6 @@ func GetGatewayIP(ctx context.Context, network string) (net.IP, error) {
} else {
return nil, fmt.Errorf("Failed to get IPAM Config for network %s", bridgeNetwork.Name)
}
}
// ConnectNodeToNetwork connects a node to a network
@ -353,7 +350,6 @@ func (d Docker) getFreeSubnetPrefix(ctx context.Context) (netaddr.IPPrefix, erro
}
return fakenet.IPAM.IPPrefix, nil
}
// parseIPAM Returns an IPAM structure with the subnet and gateway filled in. If some of the values

@ -43,7 +43,6 @@ import (
// CreateNode creates a new container
func (d Docker) CreateNode(ctx context.Context, node *k3d.Node) error {
// translate node spec to docker container specs
dockerNode, err := TranslateNodeToContainer(node)
if err != nil {
@ -67,7 +66,6 @@ func (d Docker) DeleteNode(ctx context.Context, nodeSpec *k3d.Node) error {
// GetNodesByLabel returns a list of existing nodes
func (d Docker) GetNodesByLabel(ctx context.Context, labels map[string]string) ([]*k3d.Node, error) {
// (0) get containers
containers, err := getContainersByLabel(ctx, labels)
if err != nil {
@ -97,7 +95,6 @@ func (d Docker) GetNodesByLabel(ctx context.Context, labels map[string]string) (
}
return nodes, nil
}
// StartNode starts an existing node
@ -210,7 +207,6 @@ func getContainerDetails(ctx context.Context, containerID string) (types.Contain
}
return containerDetails, nil
}
// GetNode tries to get a node container by its name
@ -231,12 +227,10 @@ func (d Docker) GetNode(ctx context.Context, node *k3d.Node) (*k3d.Node, error)
}
return node, nil
}
// GetNodeStatus returns the status of a node (Running, Started, etc.)
func (d Docker) GetNodeStatus(ctx context.Context, node *k3d.Node) (bool, string, error) {
stateString := ""
running := false
@ -368,7 +362,6 @@ func (d Docker) ExecInNodeWithStdin(ctx context.Context, node *k3d.Node, cmd []s
}
func executeInNode(ctx context.Context, node *k3d.Node, cmd []string, stdin io.ReadCloser) (*types.HijackedResponse, error) {
l.Log().Debugf("Executing command '%+v' in node '%s'", cmd, node.Name)
// get the container for the given node

@ -195,7 +195,6 @@ func TranslateContainerToNode(cont *types.Container) (*k3d.Node, error) {
// TranslateContainerDetailsToNode translates a docker containerJSON object into a k3d node representation
func TranslateContainerDetailsToNode(containerDetails types.ContainerJSON) (*k3d.Node, error) {
// first, make sure, that it's actually a k3d managed container by checking if it has all the default labels
for k, v := range k3d.DefaultRuntimeLabels {
l.Log().Tracef("TranslateContainerDetailsToNode: Checking for default object label %s=%s on container %s", k, v, containerDetails.Name)

@ -37,7 +37,6 @@ import (
)
func TestTranslateNodeToContainer(t *testing.T) {
inputNode := &k3d.Node{
Name: "test",
Role: k3d.ServerRole,
@ -113,5 +112,4 @@ func TestTranslateNodeToContainer(t *testing.T) {
if diff := deep.Equal(actualRepresentation, expectedRepresentation); diff != nil {
t.Errorf("Actual representation\n%+v\ndoes not match expected representation\n%+v\nDiff:\n%+v", actualRepresentation, expectedRepresentation, diff)
}
}

@ -113,7 +113,6 @@ func (d Docker) CopyToNode(ctx context.Context, src string, dest string, node *k
// WriteToNode writes a byte array to the selected node
func (d Docker) WriteToNode(ctx context.Context, content []byte, dest string, mode os.FileMode, node *k3d.Node) error {
nodeContainer, err := getNodeContainer(ctx, node)
if err != nil {
return fmt.Errorf("Failed to find container for node '%s': %+v", node.Name, err)

@ -113,7 +113,6 @@ func (d Docker) GetVolume(name string) (string, error) {
}
return volumeList.Volumes[0].Name, nil
}
func (d Docker) GetVolumesByLabel(ctx context.Context, labels map[string]string) ([]string, error) {
@ -144,5 +143,4 @@ func (d Docker) GetVolumesByLabel(ctx context.Context, labels map[string]string)
}
return volumes, nil
}

@ -36,5 +36,4 @@ func (node *Node) FillRuntimeLabels() {
}
// second most important: the node role label
node.RuntimeLabels[LabelRole] = string(node.Role)
}

@ -32,7 +32,6 @@ import (
// GetConfigDirOrCreate will return the base path of the k3d config directory or create it if it doesn't exist yet
// k3d's config directory will be $HOME/.k3d (Unix)
func GetConfigDirOrCreate() (string, error) {
// build the path
homeDir, err := homedir.Dir()
if err != nil {
@ -46,7 +45,6 @@ func GetConfigDirOrCreate() (string, error) {
}
return configDir, nil
}
// createDirIfNotExists checks for the existence of a directory and creates it along with all required parents if not.

@ -103,7 +103,6 @@ func FilterNodesWithSuffix(nodes []*k3d.Node, nodefilters []string, allowedSuffi
// FilterNodes takes a string filter to return a filtered list of nodes
func FilterNodes(nodes []*k3d.Node, filters []string) ([]*k3d.Node, error) {
l.Log().Tracef("Filtering %d nodes by %s", len(nodes), filters)
if len(filters) == 0 || len(filters[0]) == 0 {
@ -130,7 +129,6 @@ func FilterNodes(nodes []*k3d.Node, filters []string) ([]*k3d.Node, error) {
// range over all instances of group[subset] specs
for _, filter := range filters {
// match regex with capturing groups
match := NodeFilterRegexp.FindStringSubmatch(filter)
@ -193,7 +191,6 @@ func FilterNodes(nodes []*k3d.Node, filters []string) ([]*k3d.Node, error) {
/* Option 2) subset defined by range */
} else if submatches["subsetRange"] != "" {
/*
* subset specified by a range 'START-END', where each side is optional
*/
@ -216,7 +213,6 @@ func FilterNodes(nodes []*k3d.Node, filters []string) ([]*k3d.Node, error) {
if start < 0 || start >= len(groupNodes) {
return nil, fmt.Errorf("Invalid subset range: start < 0 or > number of available nodes in '%s'", filter)
}
}
if split[1] != "" {
@ -252,7 +248,6 @@ func FilterNodes(nodes []*k3d.Node, filters []string) ([]*k3d.Node, error) {
} else {
return nil, fmt.Errorf("Failed to parse node specifiers: unknown subset in '%s'", filter)
}
}
l.Log().Tracef("Filtered %d nodes (filter: %s)", len(filteredNodes), filters)

@ -67,7 +67,6 @@ func GetNodeFakerDirOrCreate(name string) (string, error) {
}
return fakeDir, nil
}
// GetFakeMeminfoPathForName returns a path to (existent or not) fake meminfo file for a given node/container name

@ -39,7 +39,6 @@ var src = rand.NewSource(time.Now().UnixNano())
// GenerateRandomString thanks to https://stackoverflow.com/a/31832326/6450189
// GenerateRandomString is used to generate a random string that is used as a cluster token
func GenerateRandomString(n int) string {
sb := strings.Builder{}
sb.Grow(n)
// A src.Int63() generates 63 random bits, enough for letterIdxMax characters!

@ -103,7 +103,6 @@ func (c *httpClient) fetchLatestK3sVersion(channel string) (string, error) {
}
return "", fmt.Errorf("no latest version found for channel %s (%s)", channel, c.baseURL)
}
func newHttpClient(baseURL string) *httpClient {

Loading…
Cancel
Save