use createClusterOpts

This commit is contained in:
iwilltry42 2020-02-01 14:10:14 +01:00
parent 5500872544
commit 2b674cb4e3
No known key found for this signature in database
GPG Key ID: 7BA57AD1CFF16110
3 changed files with 30 additions and 45 deletions

View File

@ -37,18 +37,10 @@ import (
log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
) )
// createClusterOpts describes a set of options set via CLI flags
type createClusterOpts struct { // TODO: merge createClusterOpts with types.ClusterCreationOpts
K3sServerArgs []string
K3sAgentArgs []string
WaitTime int
}
// NewCmdCreateCluster returns a new cobra command // NewCmdCreateCluster returns a new cobra command
func NewCmdCreateCluster() *cobra.Command { func NewCmdCreateCluster() *cobra.Command {
opts := &createClusterOpts{} createClusterOpts := &k3d.CreateClusterOpts{}
// create new command // create new command
cmd := &cobra.Command{ cmd := &cobra.Command{
@ -57,7 +49,7 @@ func NewCmdCreateCluster() *cobra.Command {
Long: `Create a new k3s cluster with containerized nodes (k3s in docker).`, Long: `Create a new k3s cluster with containerized nodes (k3s in docker).`,
Args: cobra.ExactArgs(1), // exactly one cluster name can be set // TODO: if not specified, use k3d.DefaultClusterName Args: cobra.ExactArgs(1), // exactly one cluster name can be set // TODO: if not specified, use k3d.DefaultClusterName
Run: func(cmd *cobra.Command, args []string) { Run: func(cmd *cobra.Command, args []string) {
runtime, cluster := parseCreateClusterCmd(cmd, args, opts) runtime, cluster := parseCreateClusterCmd(cmd, args, createClusterOpts)
if err := k3dCluster.CreateCluster(cluster, runtime); err != nil { if err := k3dCluster.CreateCluster(cluster, runtime); err != nil {
log.Errorln(err) log.Errorln(err)
log.Errorln("Failed to create cluster >>> Rolling Back") log.Errorln("Failed to create cluster >>> Rolling Back")
@ -85,10 +77,10 @@ func NewCmdCreateCluster() *cobra.Command {
cmd.Flags().String("secret", "", "Specify a cluster secret. By default, we generate one.") cmd.Flags().String("secret", "", "Specify a cluster secret. By default, we generate one.")
cmd.Flags().StringArrayP("volume", "v", nil, "Mount volumes into the nodes (Format: `--volume [SOURCE:]DEST[@NODEFILTER[;NODEFILTER...]]`\n - Example: `k3d create -w 2 -v /my/path@worker[0,1] -v /tmp/test:/tmp/other@master[0]`") cmd.Flags().StringArrayP("volume", "v", nil, "Mount volumes into the nodes (Format: `--volume [SOURCE:]DEST[@NODEFILTER[;NODEFILTER...]]`\n - Example: `k3d create -w 2 -v /my/path@worker[0,1] -v /tmp/test:/tmp/other@master[0]`")
cmd.Flags().StringArrayP("port", "p", nil, "Map ports from the node containers to the host (Format: `[HOST:][HOSTPORT:]CONTAINERPORT[/PROTOCOL][@NODEFILTER]`)\n - Example: `k3d create -w 2 -p 8080:80@worker[0] -p 8081@worker[1]`") cmd.Flags().StringArrayP("port", "p", nil, "Map ports from the node containers to the host (Format: `[HOST:][HOSTPORT:]CONTAINERPORT[/PROTOCOL][@NODEFILTER]`)\n - Example: `k3d create -w 2 -p 8080:80@worker[0] -p 8081@worker[1]`")
cmd.Flags().IntVar(&opts.WaitTime, "wait", -1, "Wait for a specified amount of time (seconds >= 0, where 0 means forever) for the master(s) to be ready or timeout and rollback before returning") cmd.Flags().IntVar(&createClusterOpts.WaitForMaster, "wait", -1, "Wait for a specified amount of time (seconds >= 0, where 0 means forever) for the master(s) to be ready or timeout and rollback before returning")
/* Image Importing */ /* Image Importing */
cmd.Flags().Bool("no-image-volume", false, "Disable the creation of a volume for importing images") cmd.Flags().BoolVar(&createClusterOpts.DisableImageVolume, "no-image-volume", false, "Disable the creation of a volume for importing images")
/* Multi Master Configuration */ // TODO: to implement (whole multi master thingy) /* Multi Master Configuration */ // TODO: to implement (whole multi master thingy)
// multi-master - general // multi-master - general
@ -107,8 +99,8 @@ func NewCmdCreateCluster() *cobra.Command {
*/ */
/* k3s */ // TODO: to implement extra args /* k3s */ // TODO: to implement extra args
cmd.Flags().StringArrayVar(&opts.K3sServerArgs, "k3s-server-arg", nil, "Additional args passed to the `k3s server` command on master nodes (new flag per arg)") cmd.Flags().StringArrayVar(&createClusterOpts.K3sServerArgs, "k3s-server-arg", nil, "Additional args passed to the `k3s server` command on master nodes (new flag per arg)")
cmd.Flags().StringArrayVar(&opts.K3sAgentArgs, "k3s-agent-arg", nil, "Additional args passed to the `k3s agent` command on worker nodes (new flag per arg)") cmd.Flags().StringArrayVar(&createClusterOpts.K3sAgentArgs, "k3s-agent-arg", nil, "Additional args passed to the `k3s agent` command on worker nodes (new flag per arg)")
/* Subcommands */ /* Subcommands */
@ -117,7 +109,7 @@ func NewCmdCreateCluster() *cobra.Command {
} }
// parseCreateClusterCmd parses the command input into variables required to create a cluster // parseCreateClusterCmd parses the command input into variables required to create a cluster
func parseCreateClusterCmd(cmd *cobra.Command, args []string, opts *createClusterOpts) (runtimes.Runtime, *k3d.Cluster) { func parseCreateClusterCmd(cmd *cobra.Command, args []string, createClusterOpts *k3d.CreateClusterOpts) (runtimes.Runtime, *k3d.Cluster) {
// --runtime // --runtime
rt, err := cmd.Flags().GetString("runtime") rt, err := cmd.Flags().GetString("runtime")
if err != nil { if err != nil {
@ -173,7 +165,7 @@ func parseCreateClusterCmd(cmd *cobra.Command, args []string, opts *createCluste
} }
// --wait // --wait
if cmd.Flags().Changed("wait") && opts.WaitTime < 0 { if cmd.Flags().Changed("wait") && createClusterOpts.WaitForMaster < 0 {
log.Fatalln("Value of '--wait' can't be less than 0") log.Fatalln("Value of '--wait' can't be less than 0")
} }
@ -318,12 +310,6 @@ func parseCreateClusterCmd(cmd *cobra.Command, args []string, opts *createCluste
log.Debugln(portFilterMap) log.Debugln(portFilterMap)
// --no-image-volume
noImageVolume, err := cmd.Flags().GetBool("no-image-volume")
if err != nil {
log.Fatalln(err)
}
/******************* /*******************
* generate cluster * * generate cluster *
********************/ ********************/
@ -331,10 +317,7 @@ func parseCreateClusterCmd(cmd *cobra.Command, args []string, opts *createCluste
Name: args[0], // TODO: validate name0 Name: args[0], // TODO: validate name0
Network: network, Network: network,
Secret: secret, Secret: secret,
ClusterCreationOpts: &k3d.ClusterCreationOpts{ CreateClusterOpts: createClusterOpts,
DisableImageVolume: noImageVolume,
WaitForMaster: opts.WaitTime,
},
} }
// generate list of nodes // generate list of nodes
@ -345,7 +328,7 @@ func parseCreateClusterCmd(cmd *cobra.Command, args []string, opts *createCluste
node := k3d.Node{ node := k3d.Node{
Role: k3d.MasterRole, Role: k3d.MasterRole,
Image: image, Image: image,
Args: opts.K3sServerArgs, Args: createClusterOpts.K3sServerArgs,
MasterOpts: k3d.MasterOpts{}, MasterOpts: k3d.MasterOpts{},
} }
@ -367,7 +350,7 @@ func parseCreateClusterCmd(cmd *cobra.Command, args []string, opts *createCluste
node := k3d.Node{ node := k3d.Node{
Role: k3d.WorkerRole, Role: k3d.WorkerRole,
Image: image, Image: image,
Args: opts.K3sAgentArgs, Args: createClusterOpts.K3sAgentArgs,
} }
cluster.Nodes = append(cluster.Nodes, &node) cluster.Nodes = append(cluster.Nodes, &node)

View File

@ -81,7 +81,7 @@ func CreateCluster(cluster *k3d.Cluster, runtime k3drt.Runtime) error {
* Cluster-Wide volumes * Cluster-Wide volumes
* - image volume (for importing images) * - image volume (for importing images)
*/ */
if !cluster.ClusterCreationOpts.DisableImageVolume { if !cluster.CreateClusterOpts.DisableImageVolume {
imageVolumeName := fmt.Sprintf("%s-%s-images", k3d.DefaultObjectNamePrefix, cluster.Name) imageVolumeName := fmt.Sprintf("%s-%s-images", k3d.DefaultObjectNamePrefix, cluster.Name)
if err := runtime.CreateVolume(imageVolumeName, map[string]string{"k3d.cluster": cluster.Name}); err != nil { if err := runtime.CreateVolume(imageVolumeName, map[string]string{"k3d.cluster": cluster.Name}); err != nil {
log.Errorln("Failed to create image volume '%s' for cluster '%s'", imageVolumeName, cluster.Name) log.Errorln("Failed to create image volume '%s' for cluster '%s'", imageVolumeName, cluster.Name)
@ -210,12 +210,12 @@ initNodeFinished:
} }
// asynchronously wait for this master node to be ready (by checking the logs for a specific log mesage) // asynchronously wait for this master node to be ready (by checking the logs for a specific log mesage)
if node.Role == k3d.MasterRole && cluster.ClusterCreationOpts.WaitForMaster >= 0 { if node.Role == k3d.MasterRole && cluster.CreateClusterOpts.WaitForMaster >= 0 {
waitForMasterWaitgroup.Add(1) waitForMasterWaitgroup.Add(1)
go func(masterNode *k3d.Node) { go func(masterNode *k3d.Node) {
log.Debugf("Starting to wait for master node '%s'", masterNode.Name) log.Debugf("Starting to wait for master node '%s'", masterNode.Name)
// TODO: it may be better to give endtime=starttime+timeout here so that there is no difference between the instances (go func may be called with a few (milli-)seconds difference) // TODO: it may be better to give endtime=starttime+timeout here so that there is no difference between the instances (go func may be called with a few (milli-)seconds difference)
err := WaitForNodeLogMessage(runtime, masterNode, "Wrote kubeconfig", (time.Duration(cluster.ClusterCreationOpts.WaitForMaster) * time.Second)) err := WaitForNodeLogMessage(runtime, masterNode, "Wrote kubeconfig", (time.Duration(cluster.CreateClusterOpts.WaitForMaster) * time.Second))
waitForMasterErrChan <- err waitForMasterErrChan <- err
if err == nil { if err == nil {
log.Debugf("Master Node '%s' ready", masterNode.Name) log.Debugf("Master Node '%s' ready", masterNode.Name)
@ -225,7 +225,7 @@ initNodeFinished:
} }
// block until all masters are ready (if --wait was set) and collect errors if not // block until all masters are ready (if --wait was set) and collect errors if not
if cluster.ClusterCreationOpts.WaitForMaster >= 0 { if cluster.CreateClusterOpts.WaitForMaster >= 0 {
errs := []error{} errs := []error{}
go func() { go func() {
for elem := range waitForMasterErrChan { for elem := range waitForMasterErrChan {

View File

@ -87,10 +87,12 @@ const DefaultConfigDirName = ".k3d" // should end up in $HOME/
// DefaultKubeconfigPrefix defines the default prefix for kubeconfig files // DefaultKubeconfigPrefix defines the default prefix for kubeconfig files
const DefaultKubeconfigPrefix = DefaultObjectNamePrefix + "-kubeconfig" const DefaultKubeconfigPrefix = DefaultObjectNamePrefix + "-kubeconfig"
// ClusterCreationOpts describe a set of options one can set when creating a cluster // CreateClusterOpts describe a set of options one can set when creating a cluster
type ClusterCreationOpts struct { type CreateClusterOpts struct {
DisableImageVolume bool DisableImageVolume bool
WaitForMaster int WaitForMaster int
K3sServerArgs []string
K3sAgentArgs []string
} }
// ClusterNetwork describes a network which a cluster is running in // ClusterNetwork describes a network which a cluster is running in
@ -108,7 +110,7 @@ type Cluster struct {
InitNode *Node // init master node InitNode *Node // init master node
MasterLoadBalancer *ClusterLoadbalancer `yaml:"master_loadbalancer" json:"masterLoadBalancer,omitempty"` MasterLoadBalancer *ClusterLoadbalancer `yaml:"master_loadbalancer" json:"masterLoadBalancer,omitempty"`
ExternalDatastore ExternalDatastore `yaml:"external_datastore" json:"externalDatastore,omitempty"` ExternalDatastore ExternalDatastore `yaml:"external_datastore" json:"externalDatastore,omitempty"`
ClusterCreationOpts *ClusterCreationOpts `yaml:"options" json:"options,omitempty"` CreateClusterOpts *CreateClusterOpts `yaml:"options" json:"options,omitempty"`
} }
// Node describes a k3d node // Node describes a k3d node