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 // NewCmdCluster returns a new cobra command
func NewCmdCluster() *cobra.Command { func NewCmdCluster() *cobra.Command {
// create new cobra command // create new cobra command
cmd := &cobra.Command{ cmd := &cobra.Command{
Use: "cluster", Use: "cluster",

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

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

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

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

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

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

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

@ -35,7 +35,6 @@ import (
// NewCmdImageImport returns a new cobra command // NewCmdImageImport returns a new cobra command
func NewCmdImageImport() *cobra.Command { func NewCmdImageImport() *cobra.Command {
loadImageOpts := k3d.ImageImportOpts{} loadImageOpts := k3d.ImageImportOpts{}
// create new command // 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 // parseLoadImageCmd parses the command input into variables required to create a cluster
func parseLoadImageCmd(cmd *cobra.Command, args []string) ([]string, []*k3d.Cluster) { func parseLoadImageCmd(cmd *cobra.Command, args []string) ([]string, []*k3d.Cluster) {
// --cluster // --cluster
clusterNames, err := cmd.Flags().GetStringArray("cluster") clusterNames, err := cmd.Flags().GetStringArray("cluster")
if err != nil { if err != nil {

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

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

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

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

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

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

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

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

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

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

@ -66,7 +66,6 @@ kubectl run mynginx --image %s/mynginx:v0.1
// NewCmdRegistryCreate returns a new cobra command // NewCmdRegistryCreate returns a new cobra command
func NewCmdRegistryCreate() *cobra.Command { func NewCmdRegistryCreate() *cobra.Command {
flags := &regCreateFlags{} flags := &regCreateFlags{}
ppFlags := &regCreatePreProcessedFlags{} ppFlags := &regCreatePreProcessedFlags{}
@ -122,7 +121,6 @@ func NewCmdRegistryCreate() *cobra.Command {
// parseCreateRegistryCmd parses the command input into variables required to create a registry // 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) { func parseCreateRegistryCmd(cmd *cobra.Command, args []string, flags *regCreateFlags, ppFlags *regCreatePreProcessedFlags) (*k3d.Registry, []*k3d.Cluster) {
// --cluster // --cluster
clusters := []*k3d.Cluster{} clusters := []*k3d.Cluster{}
for _, name := range ppFlags.Clusters { for _, name := range ppFlags.Clusters {
@ -171,7 +169,6 @@ func parseCreateRegistryCmd(cmd *cobra.Command, args []string, flags *regCreateF
} }
volumes = append(volumes, volume) volumes = append(volumes, volume)
} }
} }
return &k3d.Registry{Host: registryName, Image: flags.Image, ExposureOpts: *exposePort, Network: flags.Network, Options: options, Volumes: volumes}, clusters 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 // NewCmdRegistryDelete returns a new cobra command
func NewCmdRegistryDelete() *cobra.Command { func NewCmdRegistryDelete() *cobra.Command {
flags := registryDeleteFlags{} flags := registryDeleteFlags{}
// create new cobra command // create new cobra command
@ -47,7 +46,6 @@ func NewCmdRegistryDelete() *cobra.Command {
Aliases: []string{"del", "rm"}, Aliases: []string{"del", "rm"},
ValidArgsFunction: util.ValidArgsAvailableRegistries, ValidArgsFunction: util.ValidArgsAvailableRegistries,
Run: func(cmd *cobra.Command, args []string) { Run: func(cmd *cobra.Command, args []string) {
nodes := parseRegistryDeleteCmd(cmd, args, &flags) nodes := parseRegistryDeleteCmd(cmd, args, &flags)
if len(nodes) == 0 { if len(nodes) == 0 {
@ -73,7 +71,6 @@ func NewCmdRegistryDelete() *cobra.Command {
// parseRegistryDeleteCmd parses the command input into variables required to delete nodes // parseRegistryDeleteCmd parses the command input into variables required to delete nodes
func parseRegistryDeleteCmd(cmd *cobra.Command, args []string, flags *registryDeleteFlags) []*k3d.Node { func parseRegistryDeleteCmd(cmd *cobra.Command, args []string, flags *registryDeleteFlags) []*k3d.Node {
var nodes []*k3d.Node var nodes []*k3d.Node
var err error var err error

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

@ -34,7 +34,6 @@ import (
// ValidArgsAvailableClusters is used for shell completion: proposes the list of existing clusters // ValidArgsAvailableClusters is used for shell completion: proposes the list of existing clusters
func ValidArgsAvailableClusters(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { func ValidArgsAvailableClusters(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
var completions []string var completions []string
var clusters []*k3d.Cluster var clusters []*k3d.Cluster
clusters, err := k3dcluster.ClusterList(context.Background(), runtimes.SelectedRuntime) 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 // ValidArgsAvailableNodes is used for shell completion: proposes the list of existing nodes
func ValidArgsAvailableNodes(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { func ValidArgsAvailableNodes(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
var completions []string var completions []string
var nodes []*k3d.Node var nodes []*k3d.Node
nodes, err := k3dcluster.NodeList(context.Background(), runtimes.SelectedRuntime) 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 // ValidArgsAvailableRegistries is used for shell completions: proposes the list of existing registries
func ValidArgsAvailableRegistries(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { func ValidArgsAvailableRegistries(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
var completions []string var completions []string
var nodes []*k3d.Node var nodes []*k3d.Node
nodes, err := k3dcluster.NodeList(context.Background(), runtimes.SelectedRuntime) 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 // 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) { func ValidArgsNodeRoles(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
var completions []string var completions []string
roles := []string{string(k3d.ServerRole), string(k3d.AgentRole)} roles := []string{string(k3d.ServerRole), string(k3d.AgentRole)}

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

@ -30,7 +30,6 @@ import (
// SplitFiltersFromFlag separates a flag's value from the node filter, if there is one // SplitFiltersFromFlag separates a flag's value from the node filter, if there is one
func SplitFiltersFromFlag(flag string) (string, []string, error) { func SplitFiltersFromFlag(flag string) (string, []string, error) {
/* Case 1) no filter specified */ /* Case 1) no filter specified */
if !strings.Contains(flag, "@") { if !strings.Contains(flag, "@") {
@ -44,7 +43,6 @@ func SplitFiltersFromFlag(flag string) (string, []string, error) {
buffer := "" buffer := ""
for i, it := range split { for i, it := range split {
// Case 1: There's a '\' just before the '@' sign -> Should it be escaped (aka be a literal '@')? // 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 { if strings.HasSuffix(it, "\\") && i != len(split)-1 {
// Case 1.1: Escaped backslash // Case 1.1: Escaped backslash
@ -75,5 +73,4 @@ func SplitFiltersFromFlag(flag string) (string, []string, error) {
} }
return newsplit[0], strings.Split(newsplit[1], ";"), nil 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()) return true, ExecPlugin(ctx, execPath, args[len(argsPrefix):], os.Environ())
} }
// FindPlugin tries to find the plugin executable on the filesystem // 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 // ParsePortExposureSpec parses/validates a string to create an exposePort struct from it
func ParsePortExposureSpec(exposedPortSpec, internalPort string) (*k3d.ExposureOpts, error) { func ParsePortExposureSpec(exposedPortSpec, internalPort string) (*k3d.ExposureOpts, error) {
match := apiPortRegexp.FindStringSubmatch(exposedPortSpec) match := apiPortRegexp.FindStringSubmatch(exposedPortSpec)
if len(match) == 0 { if len(match) == 0 {
@ -108,7 +107,6 @@ func ParsePortExposureSpec(exposedPortSpec, internalPort string) (*k3d.ExposureO
api.Binding = portMapping[0].Binding api.Binding = portMapping[0].Binding
return api, nil return api, nil
} }
// ValidatePortMap validates a port mapping // ValidatePortMap validates a port mapping

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

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

@ -42,7 +42,6 @@ func NewHostAliasesInjectEtcHostsAction(runtime runtimes.Runtime, hostAliases []
NoCopy: true, NoCopy: true,
}, },
RewriteFunc: func(input []byte) ([]byte, error) { RewriteFunc: func(input []byte) ([]byte, error) {
tmpHosts, err := os.CreateTemp("", "k3d-hostsfile-*") tmpHosts, err := os.CreateTemp("", "k3d-hostsfile-*")
if err != nil { if err != nil {
return nil, fmt.Errorf("error creating temp hosts file: %w", err) 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. // 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. // This depends on the Operating System and the chosen Runtime.
func GetHostIP(ctx context.Context, runtime runtimes.Runtime, cluster *k3d.Cluster) (net.IP, error) { func GetHostIP(ctx context.Context, runtime runtimes.Runtime, cluster *k3d.Cluster) (net.IP, error) {
rtimeInfo, err := runtime.Info() rtimeInfo, err := runtime.Info()
if err != nil { if err != nil {
return nil, err return nil, err
@ -66,10 +65,8 @@ func GetHostIP(ctx context.Context, runtime runtimes.Runtime, cluster *k3d.Clust
// Docker Runtime // Docker Runtime
if runtime == runtimes.Docker { if runtime == runtimes.Docker {
// Docker (for Desktop) on MacOS or Windows // Docker (for Desktop) on MacOS or Windows
if docker.IsDockerDesktop(rtimeInfo.OS) { if docker.IsDockerDesktop(rtimeInfo.OS) {
toolsNode, err := EnsureToolsNode(ctx, runtime, cluster) toolsNode, err := EnsureToolsNode(ctx, runtime, cluster)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to ensure that k3d-tools node is running to get host IP :%w", err) 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) l.Log().Debugf("[GetHostIP on Docker Desktop] failed to resolve 'host.docker.internal' from inside the k3d-tools node: %v", err)
} }
// Colima // 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) l.Log().Infof("HostIP: using network gateway %s address", ip)
return ip, nil return ip, nil
} }
// Catch all other runtime selections // Catch all other runtime selections
return nil, fmt.Errorf("GetHostIP only implemented for the docker runtime") 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) { 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) 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)}) 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) l.Log().Debugf("Hostname '%s' resolved to address '%s' inside node %s", hostname, submatches["ip"], node.Name)
return net.ParseIP(submatches["ip"]), nil 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 // 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) { func GetIP(ctx context.Context, runtime k3drt.Runtime, network *k3d.ClusterNetwork) (netaddr.IP, error) {
network, err := runtime.GetNetwork(ctx, network) network, err := runtime.GetNetwork(ctx, network)
if err != nil { if err != nil {
return netaddr.IP{}, fmt.Errorf("runtime failed to get network '%s': %w", network.Name, err) 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 // 2. modifies it by updating some fields with cluster-specific information
// 3. writes it to the specified output // 3. writes it to the specified output
func KubeconfigGetWrite(ctx context.Context, runtime runtimes.Runtime, cluster *k3d.Cluster, output string, writeKubeConfigOptions *WriteKubeConfigOptions) (string, error) { func KubeconfigGetWrite(ctx context.Context, runtime runtimes.Runtime, cluster *k3d.Cluster, output string, writeKubeConfigOptions *WriteKubeConfigOptions) (string, error) {
// get kubeconfig from cluster node // get kubeconfig from cluster node
kubeconfig, err := KubeconfigGet(ctx, runtime, cluster) kubeconfig, err := KubeconfigGet(ctx, runtime, cluster)
if err != nil { if err != nil {
@ -75,7 +74,6 @@ func KubeconfigGetWrite(ctx context.Context, runtime runtimes.Runtime, cluster *
for { for {
existingKubeConfig, err = clientcmd.LoadFromFile(output) // will return an empty config if file is empty existingKubeConfig, err = clientcmd.LoadFromFile(output) // will return an empty config if file is empty
if err != nil { if err != nil {
// the output file does not exist: try to create it and try again // the output file does not exist: try to create it and try again
if os.IsNotExist(err) && firstRun { if os.IsNotExist(err) && firstRun {
l.Log().Debugf("Output path '%s' doesn't exist, trying to create it...", output) 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 // 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) return output, KubeconfigMerge(ctx, kubeconfig, existingKubeConfig, output, writeKubeConfigOptions.UpdateExisting, writeKubeConfigOptions.UpdateCurrentContext)
} }
// KubeconfigGet grabs the kubeconfig file from /output from a server node container, // 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()) l.Log().Debugf("Wrote kubeconfig to '%s'", output.Name())
return nil return nil
} }
// KubeconfigMerge merges a new kubeconfig into an existing kubeconfig and returns the result // 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 { 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) l.Log().Tracef("Merging new Kubeconfig:\n%+v\n>>> into existing Kubeconfig:\n%+v", newKubeConfig, existingKubeConfig)
// Overwrite values in existing kubeconfig // 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 // 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 { func UpdateLoadbalancerConfig(ctx context.Context, runtime runtimes.Runtime, cluster *k3d.Cluster) error {
var err error var err error
// update cluster details to ensure that we have the latest node list // update cluster details to ensure that we have the latest node list
cluster, err = ClusterGet(ctx, runtime, cluster) 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) { func GetLoadbalancerConfig(ctx context.Context, runtime runtimes.Runtime, cluster *k3d.Cluster) (types.LoadbalancerConfig, error) {
var cfg k3d.LoadbalancerConfig var cfg k3d.LoadbalancerConfig
if cluster.ServerLoadBalancer == nil || cluster.ServerLoadBalancer.Node == nil { if cluster.ServerLoadBalancer == nil || cluster.ServerLoadBalancer.Node == nil {
@ -224,7 +222,6 @@ func LoadbalancerPrepare(ctx context.Context, runtime runtimes.Runtime, cluster
} }
return lbNode, nil return lbNode, nil
} }
func loadbalancerAddPortConfigs(loadbalancer *k3d.Loadbalancer, portmapping nat.PortMapping, targetNodes []*k3d.Node) error { 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 // NodeStart starts an existing node
func NodeStart(ctx context.Context, runtime runtimes.Runtime, node *k3d.Node, nodeStartOpts *k3d.NodeStartOpts) error { func NodeStart(ctx context.Context, runtime runtimes.Runtime, node *k3d.Node, nodeStartOpts *k3d.NodeStartOpts) error {
// return early, if the node is already running // return early, if the node is already running
if node.State.Running { if node.State.Running {
l.Log().Infof("Node %s is already running", node.Name) 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 { func enableFixes(ctx context.Context, runtime runtimes.Runtime, node *k3d.Node, nodeStartOpts *k3d.NodeStartOpts) error {
if node.Role == k3d.ServerRole || node.Role == k3d.AgentRole { if node.Role == k3d.ServerRole || node.Role == k3d.AgentRole {
// FIXME: FixCgroupV2 - to be removed when fixed upstream // FIXME: FixCgroupV2 - to be removed when fixed upstream
// auto-enable, if needed // auto-enable, if needed
EnableCgroupV2FixIfNeeded(runtime) EnableCgroupV2FixIfNeeded(runtime)
@ -806,7 +803,6 @@ func NodeWaitForLogMessage(ctx context.Context, runtime runtimes.Runtime, node *
} }
time.Sleep(500 * time.Millisecond) time.Sleep(500 * time.Millisecond)
} }
}(ctx, runtime, node, since, donechan) }(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 // 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. // 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. // The logstream returned by docker ends everytime the container restarts, so we have to start from the beginning.
for i := 0; i < backOffLimit; i++ { for i := 0; i < backOffLimit; i++ {
// get the log stream (reader is following the logstream) // get the log stream (reader is following the logstream)
out, err := runtime.GetNodeLogs(ctx, node, since, &runtimeTypes.NodeLogsOpts{Follow: true}) out, err := runtime.GetNodeLogs(ctx, node, since, &runtimeTypes.NodeLogsOpts{Follow: true})
if out != nil { if out != nil {
@ -856,7 +851,6 @@ func NodeWaitForLogMessage(ctx context.Context, runtime runtimes.Runtime, node *
} }
previousline = scanner.Text() previousline = scanner.Text()
} }
if e := scanner.Err(); e != nil { if e := scanner.Err(); e != nil {
@ -923,7 +917,6 @@ nodeLoop:
// NodeEdit let's you update an existing node // NodeEdit let's you update an existing node
func NodeEdit(ctx context.Context, runtime runtimes.Runtime, existingNode, changeset *k3d.Node) error { func NodeEdit(ctx context.Context, runtime runtimes.Runtime, existingNode, changeset *k3d.Node) error {
/* /*
* Make a deep copy of the existing node * 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 { for port, portbindings := range changeset.Ports {
loopChangesetPortbindings: loopChangesetPortbindings:
for _, portbinding := range portbindings { for _, portbinding := range portbindings {
// loop over existing portbindings to avoid port collisions (docker doesn't check for it) // loop over existing portbindings to avoid port collisions (docker doesn't check for it)
for _, existingPB := range result.Ports[port] { for _, existingPB := range result.Ports[port] {
if util.IsPortBindingEqual(portbinding, existingPB) { // also matches on "equal" HostIPs (127.0.0.1, "", 0.0.0.0) 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 { func NodeReplace(ctx context.Context, runtime runtimes.Runtime, old, new *k3d.Node) error {
// rename existing node // rename existing node
oldNameTemp := fmt.Sprintf("%s-%s", old.Name, util.GenerateRandomString(5)) oldNameTemp := fmt.Sprintf("%s-%s", old.Name, util.GenerateRandomString(5))
oldNameOriginal := old.Name oldNameOriginal := old.Name
@ -1053,7 +1044,6 @@ type CopyNodeOpts struct {
} }
func CopyNode(ctx context.Context, src *k3d.Node, opts CopyNodeOpts) (*k3d.Node, error) { func CopyNode(ctx context.Context, src *k3d.Node, opts CopyNodeOpts) (*k3d.Node, error) {
targetCopy, err := copystruct.Copy(src) targetCopy, err := copystruct.Copy(src)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to copy node struct: %w", err) 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) return fmt.Errorf("error adding port mappings: unknown suffix %s", suffix)
} }
} }
} }
// print generated loadbalancer config if exists // 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 { func addPortMappings(node *k3d.Node, portmappings []nat.PortMapping) error {
if node.Ports == nil { if node.Ports == nil {
node.Ports = nat.PortMap{} node.Ports = nat.PortMap{}
} }

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

@ -64,5 +64,4 @@ metadata:
if !(strings.TrimSpace(string(cm)) == strings.TrimSpace(expectedYAMLString)) { 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)) 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 // 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 // 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 { func ImageImportIntoClusterMulti(ctx context.Context, runtime runtimes.Runtime, images []string, cluster *k3d.Cluster, opts k3d.ImageImportOpts) error {
// stdin case // stdin case
if len(images) == 1 && images[0] == "-" { if len(images) == 1 && images[0] == "-" {
err := loadImageFromStream(ctx, runtime, os.Stdin, cluster, []string{"stdin"}) 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) return fmt.Errorf("could not load image to cluster from stream %s: %w", imagesFromRuntime, err)
} }
// load the images directly into the nodes // load the images directly into the nodes
} }
if len(imagesFromTar) > 0 { if len(imagesFromTar) > 0 {
@ -320,7 +318,6 @@ func dockerSpecialImageNameEqual(requestedImageName string, runtimeImageName str
if strings.HasPrefix(requestedImageName, prefix) { if strings.HasPrefix(requestedImageName, prefix) {
return imageNamesEqual(strings.TrimPrefix(requestedImageName, prefix), runtimeImageName) return imageNamesEqual(strings.TrimPrefix(requestedImageName, prefix), runtimeImageName)
} }
} }
return false return false
@ -398,7 +395,6 @@ func EnsureToolsNode(ctx context.Context, runtime runtimes.Runtime, cluster *k3d
var toolsNode *k3d.Node var toolsNode *k3d.Node
toolsNode, err := runtime.GetNode(ctx, &k3d.Node{Name: fmt.Sprintf("%s-%s-tools", k3d.DefaultObjectNamePrefix, cluster.Name)}) toolsNode, err := runtime.GetNode(ctx, &k3d.Node{Name: fmt.Sprintf("%s-%s-tools", k3d.DefaultObjectNamePrefix, cluster.Name)})
if err != nil || toolsNode == nil { if err != nil || toolsNode == nil {
// Get more info on the cluster, if required // Get more info on the cluster, if required
var imageVolume string var imageVolume string
if cluster.Network.Name == "" || cluster.ImageVolume == "" { if cluster.Network.Name == "" || cluster.ImageVolume == "" {
@ -450,5 +446,4 @@ func EnsureToolsNode(ctx context.Context, runtime runtimes.Runtime, cluster *k3d
} }
return toolsNode, err return toolsNode, err
} }

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

@ -34,7 +34,6 @@ import (
) )
func TestReadSimpleConfig(t *testing.T) { func TestReadSimpleConfig(t *testing.T) {
exposedAPI := conf.SimpleExposureOpts{} exposedAPI := conf.SimpleExposureOpts{}
exposedAPI.HostIP = "0.0.0.0" exposedAPI.HostIP = "0.0.0.0"
exposedAPI.HostPort = "6443" exposedAPI.HostPort = "6443"
@ -137,11 +136,9 @@ func TestReadSimpleConfig(t *testing.T) {
if diff := deep.Equal(cfg, expectedConfig); diff != nil { 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) t.Errorf("Actual representation\n%+v\ndoes not match expected representation\n%+v\nDiff:\n%+v", cfg, expectedConfig, diff)
} }
} }
func TestReadClusterConfig(t *testing.T) { func TestReadClusterConfig(t *testing.T) {
expectedConfig := conf.ClusterConfig{ expectedConfig := conf.ClusterConfig{
TypeMeta: configtypes.TypeMeta{ TypeMeta: configtypes.TypeMeta{
APIVersion: "k3d.io/v1alpha5", APIVersion: "k3d.io/v1alpha5",
@ -182,11 +179,9 @@ func TestReadClusterConfig(t *testing.T) {
if diff := deep.Equal(readConfig, expectedConfig); diff != nil { 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) t.Errorf("Actual representation\n%+v\ndoes not match expected representation\n%+v\nDiff:\n%+v", readConfig, expectedConfig, diff)
} }
} }
func TestReadClusterListConfig(t *testing.T) { func TestReadClusterListConfig(t *testing.T) {
expectedConfig := conf.ClusterListConfig{ expectedConfig := conf.ClusterListConfig{
TypeMeta: configtypes.TypeMeta{ TypeMeta: configtypes.TypeMeta{
APIVersion: "k3d.io/v1alpha5", APIVersion: "k3d.io/v1alpha5",
@ -238,11 +233,9 @@ func TestReadClusterListConfig(t *testing.T) {
if diff := deep.Equal(readConfig, expectedConfig); diff != nil { 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) t.Errorf("Actual representation\n%+v\ndoes not match expected representation\n%+v\nDiff:\n%+v", readConfig, expectedConfig, diff)
} }
} }
func TestReadUnknownConfig(t *testing.T) { func TestReadUnknownConfig(t *testing.T) {
cfgFile := "./test_assets/config_test_unknown.yaml" cfgFile := "./test_assets/config_test_unknown.yaml"
config := viper.New() config := viper.New()
@ -261,11 +254,9 @@ func TestReadUnknownConfig(t *testing.T) {
if err == nil { if err == nil {
t.Fail() t.Fail()
} }
} }
func TestReadSimpleConfigRegistries(t *testing.T) { func TestReadSimpleConfigRegistries(t *testing.T) {
exposedAPI := conf.SimpleExposureOpts{} exposedAPI := conf.SimpleExposureOpts{}
exposedAPI.HostIP = "0.0.0.0" exposedAPI.HostIP = "0.0.0.0"
exposedAPI.HostPort = "6443" 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 // ValidateSchema validates a YAML construct (non-struct representation) against a JSON Schema
func ValidateSchema(content interface{}, schemaJSON []byte) error { func ValidateSchema(content interface{}, schemaJSON []byte) error {
contentYaml, err := yaml.Marshal(content) contentYaml, err := yaml.Marshal(content)
if err != nil { if err != nil {
return err return err
@ -65,7 +64,6 @@ func ValidateSchema(content interface{}, schemaJSON []byte) error {
} }
return ValidateSchemaJSON(contentJSON, schemaJSON) return ValidateSchemaJSON(contentJSON, schemaJSON)
} }
func ValidateSchemaJSON(contentJSON []byte, schemaJSON []byte) error { func ValidateSchemaJSON(contentJSON []byte, schemaJSON []byte) error {

@ -28,17 +28,14 @@ import (
) )
func TestValidateSchema(t *testing.T) { func TestValidateSchema(t *testing.T) {
cfgPath := "./test_assets/config_test_simple.yaml" cfgPath := "./test_assets/config_test_simple.yaml"
if err := ValidateSchemaFile(cfgPath, []byte(conf.JSONSchema)); err != nil { if err := ValidateSchemaFile(cfgPath, []byte(conf.JSONSchema)); err != nil {
t.Errorf("Validation of config file %s against the default schema failed: %+v", cfgPath, err) t.Errorf("Validation of config file %s against the default schema failed: %+v", cfgPath, err)
} }
} }
func TestValidateSchemaFail(t *testing.T) { func TestValidateSchemaFail(t *testing.T) {
cfgPath := "./test_assets/config_test_simple_invalid_servers.yaml" cfgPath := "./test_assets/config_test_simple_invalid_servers.yaml"
var err error var err error
@ -52,5 +49,4 @@ func TestValidateSchemaFail(t *testing.T) {
if err.Error() != expectedErrorText { if err.Error() != expectedErrorText {
t.Errorf("Actual validation error\n%s\ndoes not match expected error\n%s\n", 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) l.Log().Debugf("Merging %+v into %+v", src, dest)
if err := mergo.Merge(&dest, src); err != nil { if err := mergo.Merge(&dest, src); err != nil {
return nil, fmt.Errorf("failed to merge configs: %w", err) 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) { func Migrate(config types.Config, targetVersion string) (types.Config, error) {
migration, ok := getMigrations(targetVersion)[config.GetAPIVersion()] migration, ok := getMigrations(targetVersion)[config.GetAPIVersion()]
if !ok { if !ok {
return nil, fmt.Errorf("no migration possible from '%s' to '%s'", config.GetAPIVersion(), targetVersion) 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 return cfg, err
} }

@ -63,7 +63,6 @@ func TestMigrate(t *testing.T) {
for name, tc := range tests { for name, tc := range tests {
t.Run(name, func(t *testing.T) { t.Run(name, func(t *testing.T) {
actualViper := viper.New() actualViper := viper.New()
expectedViper := viper.New() expectedViper := viper.New()
@ -102,7 +101,6 @@ func TestMigrate(t *testing.T) {
if diff := deep.Equal(actualCfg, expectedCfg); diff != nil { 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) 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===== 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]) 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 // 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) { func TransformSimpleToClusterConfig(ctx context.Context, runtime runtimes.Runtime, simpleConfig conf.SimpleConfig) (*conf.ClusterConfig, error) {
// set default cluster name // set default cluster name
if simpleConfig.Name == "" { if simpleConfig.Name == "" {
simpleConfig.Name = k3d.DefaultClusterName simpleConfig.Name = k3d.DefaultClusterName
@ -209,7 +208,6 @@ func TransformSimpleToClusterConfig(ctx context.Context, runtime runtimes.Runtim
} }
k, v := util.SplitLabelKeyValue(k3sNodeLabelWithNodeFilters.Label) k, v := util.SplitLabelKeyValue(k3sNodeLabelWithNodeFilters.Label)
node.K3sNodeLabels[k] = v node.K3sNodeLabels[k] = v
} }
} }
@ -311,7 +309,6 @@ func TransformSimpleToClusterConfig(ctx context.Context, runtime runtimes.Runtim
* Registries * Registries
*/ */
if simpleConfig.Registries.Create != nil { if simpleConfig.Registries.Create != nil {
epSpecHost := "0.0.0.0" epSpecHost := "0.0.0.0"
epSpecPort := "random" epSpecPort := "random"

@ -51,5 +51,4 @@ func TestTransformSimpleConfigToClusterConfig(t *testing.T) {
} }
t.Logf("\n===== Resulting Cluster Config =====\n%+v\n===============\n", clusterCfg) 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) { func GetConfigByKind(kind string) (configtypes.Config, error) {
// determine config kind // determine config kind
switch kind { switch kind {
case "simple": case "simple":
@ -195,5 +194,4 @@ func GetConfigByKind(kind string) (configtypes.Config, error) {
default: default:
return nil, fmt.Errorf("unknown `kind` '%s' in config file", kind) 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) l.Log().Debugf("Migrated config: %+v", cfg)
return cfg, nil return cfg, nil
} }
l.Log().Debugf("No migration needed for %s#%s -> %s#%s", input.GetAPIVersion(), input.GetKind(), ApiVersion, input.GetKind()) l.Log().Debugf("No migration needed for %s#%s -> %s#%s", input.GetAPIVersion(), input.GetKind(), ApiVersion, input.GetKind())
return input, nil return input, nil
} }

@ -221,7 +221,6 @@ func (c ClusterListConfig) GetAPIVersion() string {
} }
func GetConfigByKind(kind string) (config.Config, error) { func GetConfigByKind(kind string) (config.Config, error) {
// determine config kind // determine config kind
switch strings.ToLower(kind) { switch strings.ToLower(kind) {
case "simple": case "simple":
@ -235,5 +234,4 @@ func GetConfigByKind(kind string) (config.Config, error) {
default: default:
return nil, fmt.Errorf("unknown `kind` '%s' in config file", kind) 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) l.Log().Debugf("Migrated config: %+v", cfg)
return cfg, nil return cfg, nil
} }
l.Log().Debugf("No migration needed for %s#%s -> %s#%s", input.GetAPIVersion(), input.GetKind(), ApiVersion, input.GetKind()) 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) { func GetConfigByKind(kind string) (config.Config, error) {
// determine config kind // determine config kind
switch strings.ToLower(kind) { switch strings.ToLower(kind) {
case "simple": case "simple":
@ -218,5 +217,4 @@ func GetConfigByKind(kind string) (config.Config, error) {
default: default:
return nil, fmt.Errorf("unknown `kind` '%s' in config file", kind) 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) { func GetConfigByKind(kind string) (config.Config, error) {
// determine config kind // determine config kind
switch strings.ToLower(kind) { switch strings.ToLower(kind) {
case "simple": case "simple":
@ -225,5 +224,4 @@ func GetConfigByKind(kind string) (config.Config, error) {
default: default:
return nil, fmt.Errorf("unknown `kind` '%s' in config file", kind) 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 { if _, err := dockerunits.RAMInBytes(config.ClusterCreateOpts.ServersMemory); err != nil {
return fmt.Errorf("provided servers memory limit value is invalid: %w", err) return fmt.Errorf("provided servers memory limit value is invalid: %w", err)
} }
} }
if config.ClusterCreateOpts.AgentsMemory != "" { if config.ClusterCreateOpts.AgentsMemory != "" {
@ -99,15 +98,12 @@ func ValidateClusterConfig(ctx context.Context, runtime runtimes.Runtime, config
} }
} }
} }
} }
// validate nodes one by one // validate nodes one by one
for _, node := range config.Cluster.Nodes { for _, node := range config.Cluster.Nodes {
// volumes have to be either an existing path on the host or a named runtime volume // volumes have to be either an existing path on the host or a named runtime volume
for _, volume := range node.Volumes { for _, volume := range node.Volumes {
if err := runtimeutil.ValidateVolumeMount(ctx, runtime, volume, &config.Cluster); err != nil { if err := runtimeutil.ValidateVolumeMount(ctx, runtime, volume, &config.Cluster); err != nil {
return fmt.Errorf("failed to validate volume mount '%s': %w", volume, err) 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 // createContainer creates a new docker container from translated specs
func createContainer(ctx context.Context, dockerNode *NodeInDocker, name string) (string, error) { func createContainer(ctx context.Context, dockerNode *NodeInDocker, name string) (string, error) {
l.Log().Tracef("Creating docker container with translated config\n%+v\n", dockerNode) l.Log().Tracef("Creating docker container with translated config\n%+v\n", dockerNode)
// initialize docker client // initialize docker client
@ -82,7 +81,6 @@ func startContainer(ctx context.Context, ID string) error {
// removeContainer deletes a running container (like docker rm -f) // removeContainer deletes a running container (like docker rm -f)
func removeContainer(ctx context.Context, ID string) error { func removeContainer(ctx context.Context, ID string) error {
// (0) create docker client // (0) create docker client
docker, err := GetDockerClient() docker, err := GetDockerClient()
if err != nil { 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 // pullImage pulls a container image and outputs progress if --verbose flag is set
func pullImage(ctx context.Context, docker client.APIClient, image string) error { func pullImage(ctx context.Context, docker client.APIClient, image string) error {
resp, err := docker.ImagePull(ctx, image, types.ImagePullOptions{}) resp, err := docker.ImagePull(ctx, image, types.ImagePullOptions{})
if err != nil { if err != nil {
return fmt.Errorf("docker failed to pull the image '%s': %w", image, err) 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 return nil
} }
func getNodeContainer(ctx context.Context, node *k3d.Node) (*types.Container, error) { func getNodeContainer(ctx context.Context, node *k3d.Node) (*types.Container, error) {
// (0) create docker client // (0) create docker client
docker, err := GetDockerClient() docker, err := GetDockerClient()
if err != nil { if err != nil {
@ -169,7 +164,6 @@ func getNodeContainer(ctx context.Context, node *k3d.Node) (*types.Container, er
} }
return &containers[0], nil return &containers[0], nil
} }
// executes an arbitrary command in a container while returning its exit code. // 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 // GetHost returns the docker daemon host
func (d Docker) GetHost() string { func (d Docker) GetHost() string {
// a) docker-machine // a) docker-machine
machineIP, err := d.GetDockerMachineIP() machineIP, err := d.GetDockerMachineIP()
if err != nil { 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 nil, fmt.Errorf("failed to get gateway IP of docker network '%s': %w", network, err)
} }
return ip, nil return ip, nil
} }

@ -126,13 +126,11 @@ func (d Docker) GetNetwork(ctx context.Context, searchNet *k3d.ClusterNetwork) (
} }
return network, nil return network, nil
} }
// CreateNetworkIfNotPresent creates a new docker network // CreateNetworkIfNotPresent creates a new docker network
// @return: network, exists, error // @return: network, exists, error
func (d Docker) CreateNetworkIfNotPresent(ctx context.Context, inNet *k3d.ClusterNetwork) (*k3d.ClusterNetwork, bool, error) { func (d Docker) CreateNetworkIfNotPresent(ctx context.Context, inNet *k3d.ClusterNetwork) (*k3d.ClusterNetwork, bool, error) {
// (0) create new docker client // (0) create new docker client
docker, err := GetDockerClient() docker, err := GetDockerClient()
if err != nil { if err != nil {
@ -267,7 +265,6 @@ func GetGatewayIP(ctx context.Context, network string) (net.IP, error) {
} else { } else {
return nil, fmt.Errorf("Failed to get IPAM Config for network %s", bridgeNetwork.Name) return nil, fmt.Errorf("Failed to get IPAM Config for network %s", bridgeNetwork.Name)
} }
} }
// ConnectNodeToNetwork connects a node to a network // 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 return fakenet.IPAM.IPPrefix, nil
} }
// parseIPAM Returns an IPAM structure with the subnet and gateway filled in. If some of the values // 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 // CreateNode creates a new container
func (d Docker) CreateNode(ctx context.Context, node *k3d.Node) error { func (d Docker) CreateNode(ctx context.Context, node *k3d.Node) error {
// translate node spec to docker container specs // translate node spec to docker container specs
dockerNode, err := TranslateNodeToContainer(node) dockerNode, err := TranslateNodeToContainer(node)
if err != nil { 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 // GetNodesByLabel returns a list of existing nodes
func (d Docker) GetNodesByLabel(ctx context.Context, labels map[string]string) ([]*k3d.Node, error) { func (d Docker) GetNodesByLabel(ctx context.Context, labels map[string]string) ([]*k3d.Node, error) {
// (0) get containers // (0) get containers
containers, err := getContainersByLabel(ctx, labels) containers, err := getContainersByLabel(ctx, labels)
if err != nil { if err != nil {
@ -97,7 +95,6 @@ func (d Docker) GetNodesByLabel(ctx context.Context, labels map[string]string) (
} }
return nodes, nil return nodes, nil
} }
// StartNode starts an existing node // StartNode starts an existing node
@ -210,7 +207,6 @@ func getContainerDetails(ctx context.Context, containerID string) (types.Contain
} }
return containerDetails, nil return containerDetails, nil
} }
// GetNode tries to get a node container by its name // 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 return node, nil
} }
// GetNodeStatus returns the status of a node (Running, Started, etc.) // GetNodeStatus returns the status of a node (Running, Started, etc.)
func (d Docker) GetNodeStatus(ctx context.Context, node *k3d.Node) (bool, string, error) { func (d Docker) GetNodeStatus(ctx context.Context, node *k3d.Node) (bool, string, error) {
stateString := "" stateString := ""
running := false 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) { 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) l.Log().Debugf("Executing command '%+v' in node '%s'", cmd, node.Name)
// get the container for the given node // 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 // TranslateContainerDetailsToNode translates a docker containerJSON object into a k3d node representation
func TranslateContainerDetailsToNode(containerDetails types.ContainerJSON) (*k3d.Node, error) { 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 // 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 { for k, v := range k3d.DefaultRuntimeLabels {
l.Log().Tracef("TranslateContainerDetailsToNode: Checking for default object label %s=%s on container %s", k, v, containerDetails.Name) 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) { func TestTranslateNodeToContainer(t *testing.T) {
inputNode := &k3d.Node{ inputNode := &k3d.Node{
Name: "test", Name: "test",
Role: k3d.ServerRole, Role: k3d.ServerRole,
@ -113,5 +112,4 @@ func TestTranslateNodeToContainer(t *testing.T) {
if diff := deep.Equal(actualRepresentation, expectedRepresentation); diff != nil { 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) 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 // 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 { func (d Docker) WriteToNode(ctx context.Context, content []byte, dest string, mode os.FileMode, node *k3d.Node) error {
nodeContainer, err := getNodeContainer(ctx, node) nodeContainer, err := getNodeContainer(ctx, node)
if err != nil { if err != nil {
return fmt.Errorf("Failed to find container for node '%s': %+v", node.Name, err) 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 return volumeList.Volumes[0].Name, nil
} }
func (d Docker) GetVolumesByLabel(ctx context.Context, labels map[string]string) ([]string, error) { 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 return volumes, nil
} }

@ -36,5 +36,4 @@ func (node *Node) FillRuntimeLabels() {
} }
// second most important: the node role label // second most important: the node role label
node.RuntimeLabels[LabelRole] = string(node.Role) 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 // 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) // k3d's config directory will be $HOME/.k3d (Unix)
func GetConfigDirOrCreate() (string, error) { func GetConfigDirOrCreate() (string, error) {
// build the path // build the path
homeDir, err := homedir.Dir() homeDir, err := homedir.Dir()
if err != nil { if err != nil {
@ -46,7 +45,6 @@ func GetConfigDirOrCreate() (string, error) {
} }
return configDir, nil return configDir, nil
} }
// createDirIfNotExists checks for the existence of a directory and creates it along with all required parents if not. // 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 // FilterNodes takes a string filter to return a filtered list of nodes
func FilterNodes(nodes []*k3d.Node, filters []string) ([]*k3d.Node, error) { func FilterNodes(nodes []*k3d.Node, filters []string) ([]*k3d.Node, error) {
l.Log().Tracef("Filtering %d nodes by %s", len(nodes), filters) l.Log().Tracef("Filtering %d nodes by %s", len(nodes), filters)
if len(filters) == 0 || len(filters[0]) == 0 { 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 // range over all instances of group[subset] specs
for _, filter := range filters { for _, filter := range filters {
// match regex with capturing groups // match regex with capturing groups
match := NodeFilterRegexp.FindStringSubmatch(filter) match := NodeFilterRegexp.FindStringSubmatch(filter)
@ -193,7 +191,6 @@ func FilterNodes(nodes []*k3d.Node, filters []string) ([]*k3d.Node, error) {
/* Option 2) subset defined by range */ /* Option 2) subset defined by range */
} else if submatches["subsetRange"] != "" { } else if submatches["subsetRange"] != "" {
/* /*
* subset specified by a range 'START-END', where each side is optional * 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) { if start < 0 || start >= len(groupNodes) {
return nil, fmt.Errorf("Invalid subset range: start < 0 or > number of available nodes in '%s'", filter) return nil, fmt.Errorf("Invalid subset range: start < 0 or > number of available nodes in '%s'", filter)
} }
} }
if split[1] != "" { if split[1] != "" {
@ -252,7 +248,6 @@ func FilterNodes(nodes []*k3d.Node, filters []string) ([]*k3d.Node, error) {
} else { } else {
return nil, fmt.Errorf("Failed to parse node specifiers: unknown subset in '%s'", filter) 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) l.Log().Tracef("Filtered %d nodes (filter: %s)", len(filteredNodes), filters)

@ -67,7 +67,6 @@ func GetNodeFakerDirOrCreate(name string) (string, error) {
} }
return fakeDir, nil return fakeDir, nil
} }
// GetFakeMeminfoPathForName returns a path to (existent or not) fake meminfo file for a given node/container name // 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 thanks to https://stackoverflow.com/a/31832326/6450189
// GenerateRandomString is used to generate a random string that is used as a cluster token // GenerateRandomString is used to generate a random string that is used as a cluster token
func GenerateRandomString(n int) string { func GenerateRandomString(n int) string {
sb := strings.Builder{} sb := strings.Builder{}
sb.Grow(n) sb.Grow(n)
// A src.Int63() generates 63 random bits, enough for letterIdxMax characters! // 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) return "", fmt.Errorf("no latest version found for channel %s (%s)", channel, c.baseURL)
} }
func newHttpClient(baseURL string) *httpClient { func newHttpClient(baseURL string) *httpClient {

Loading…
Cancel
Save