diff --git a/cli/cluster.go b/cli/cluster.go index 2421c25c..fc21a269 100644 --- a/cli/cluster.go +++ b/cli/cluster.go @@ -5,7 +5,6 @@ import ( "context" "fmt" "io/ioutil" - "log" "os" "path" "strconv" @@ -16,6 +15,7 @@ import ( "github.com/docker/docker/client" homedir "github.com/mitchellh/go-homedir" "github.com/olekukonko/tablewriter" + "github.com/sirupsen/logrus" ) const ( @@ -65,11 +65,11 @@ func createDirIfNotExists(path string) error { func createClusterDir(name string) { clusterPath, _ := getClusterDir(name) if err := createDirIfNotExists(clusterPath); err != nil { - log.Fatalf("ERROR: couldn't create cluster directory [%s] -> %+v", clusterPath, err) + logrus.Fatalf("ERROR: couldn't create cluster directory [%s] -> %+v", clusterPath, err) } // create subdir for sharing container images if err := createDirIfNotExists(clusterPath + "/images"); err != nil { - log.Fatalf("ERROR: couldn't create cluster sub-directory [%s] -> %+v", clusterPath+"/images", err) + logrus.Fatalf("ERROR: couldn't create cluster sub-directory [%s] -> %+v", clusterPath+"/images", err) } } @@ -77,7 +77,7 @@ func createClusterDir(name string) { func deleteClusterDir(name string) { clusterPath, _ := getClusterDir(name) if err := os.RemoveAll(clusterPath); err != nil { - log.Printf("WARNING: couldn't delete cluster directory [%s]. You might want to delete it manually.", clusterPath) + logrus.Printf("WARNING: couldn't delete cluster directory [%s]. You might want to delete it manually.", clusterPath) } } @@ -85,7 +85,7 @@ func deleteClusterDir(name string) { func getClusterDir(name string) (string, error) { homeDir, err := homedir.Dir() if err != nil { - log.Printf("ERROR: Couldn't get user's home directory") + logrus.Printf("ERROR: Couldn't get user's home directory") return "", err } return path.Join(homeDir, ".config", "k3d", name), nil @@ -202,10 +202,10 @@ func getKubeConfig(cluster string) (string, error) { func printClusters() { clusters, err := getClusters(true, "") if err != nil { - log.Fatalf("ERROR: Couldn't list clusters\n%+v", err) + logrus.Fatalf("ERROR: Couldn't list clusters\n%+v", err) } if len(clusters) == 0 { - log.Printf("No clusters found!") + logrus.Printf("No clusters found!") return } @@ -295,7 +295,7 @@ func getClusters(all bool, name string) (map[string]cluster, error) { Filters: filters, }) if err != nil { - log.Printf("WARNING: couldn't get worker containers for cluster %s\n%+v", clusterName, err) + logrus.Printf("WARNING: couldn't get worker containers for cluster %s\n%+v", clusterName, err) } // save cluster information diff --git a/cli/commands.go b/cli/commands.go index 0b2556b6..2586c03d 100644 --- a/cli/commands.go +++ b/cli/commands.go @@ -9,7 +9,6 @@ import ( "context" "errors" "fmt" - "log" "os" "strconv" "strings" @@ -17,6 +16,7 @@ import ( "github.com/docker/docker/api/types" "github.com/docker/docker/client" + "github.com/sirupsen/logrus" "github.com/urfave/cli" ) @@ -27,7 +27,7 @@ const ( // CheckTools checks if the docker API server is responding func CheckTools(c *cli.Context) error { - log.Print("Checking docker...") + logrus.Print("Checking docker...") ctx := context.Background() docker, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation()) if err != nil { @@ -38,7 +38,7 @@ func CheckTools(c *cli.Context) error { if err != nil { return fmt.Errorf("ERROR: checking docker failed\n%+v", err) } - log.Printf("SUCCESS: Checking docker succeeded (API: v%s)\n", ping.APIVersion) + logrus.Printf("SUCCESS: Checking docker succeeded (API: v%s)\n", ping.APIVersion) return nil } @@ -61,7 +61,7 @@ func CreateCluster(c *cli.Context) error { // so that they don't linger around. deleteCluster := func() { if err := DeleteCluster(c); err != nil { - log.Printf("Error: Failed to delete cluster %s", c.String("name")) + logrus.Printf("Error: Failed to delete cluster %s", c.String("name")) } } @@ -69,10 +69,10 @@ func CreateCluster(c *cli.Context) error { image := c.String("image") if c.IsSet("version") { // TODO: --version to be deprecated - log.Println("[WARNING] The `--version` flag will be deprecated soon, please use `--image rancher/k3s:` instead") + logrus.Println("[WARNING] The `--version` flag will be deprecated soon, please use `--image rancher/k3s:` instead") if c.IsSet("image") { // version specified, custom image = error (to push deprecation of version flag) - log.Fatalln("[ERROR] Please use `--image :` instead of --image and --version") + logrus.Fatalln("[ERROR] Please use `--image :` instead of --image and --version") } else { // version specified, default image = ok (until deprecation of version flag) image = fmt.Sprintf("%s:%s", strings.Split(image, ":")[0], c.String("version")) @@ -88,7 +88,7 @@ func CreateCluster(c *cli.Context) error { if err != nil { return err } - log.Printf("Created cluster network with ID %s", networkID) + logrus.Printf("Created cluster network with ID %s", networkID) // environment variables env := []string{"K3S_KUBECONFIG_OUTPUT=/output/kubeconfig.yaml"} @@ -98,7 +98,7 @@ func CreateCluster(c *cli.Context) error { // k3s server arguments // TODO: --port will soon be --api-port since we want to re-use --port for arbitrary port mappings if c.IsSet("port") { - log.Println("INFO: As of v2.0.0 --port will be used for arbitrary port mapping. Please use --api-port/-a instead for configuring the Api Port") + logrus.Println("INFO: As of v2.0.0 --port will be used for arbitrary port mapping. Please use --api-port/-a instead for configuring the Api Port") } apiPort, err := parseAPIPort(c.String("api-port")) if err != nil { @@ -116,13 +116,13 @@ func CreateCluster(c *cli.Context) error { // In case of error, Log a warning message, and continue on. Since it more likely caused by a miss configured // DOCKER_MACHINE_NAME environment variable. if err != nil { - log.Printf("WARNING: Failed to get docker machine IP address, ignoring the DOCKER_MACHINE_NAME environment variable setting.\n") + logrus.Printf("WARNING: Failed to get docker machine IP address, ignoring the DOCKER_MACHINE_NAME environment variable setting.\n") } } if apiPort.Host != "" { // Add TLS SAN for non default host name - log.Printf("Add TLS SAN for %s", apiPort.Host) + logrus.Printf("Add TLS SAN for %s", apiPort.Host) k3sServerArgs = append(k3sServerArgs, "--tls-san", apiPort.Host) } @@ -137,12 +137,12 @@ func CreateCluster(c *cli.Context) error { // new port map portmap, err := mapNodesToPortSpecs(c.StringSlice("publish"), GetAllContainerNames(c.String("name"), defaultServerCount, c.Int("workers"))) if err != nil { - log.Fatal(err) + logrus.Fatal(err) } // create a docker volume for sharing image tarballs with the cluster imageVolume, err := createImageVolume(c.String("name")) - log.Println("Created docker volume ", imageVolume.Name) + logrus.Println("Created docker volume ", imageVolume.Name) if err != nil { return err } @@ -164,7 +164,7 @@ func CreateCluster(c *cli.Context) error { } // create the server - log.Printf("Creating cluster [%s]", c.String("name")) + logrus.Printf("Creating cluster [%s]", c.String("name")) // create the directory where we will put the kubeconfig file by default (when running `k3d get-config`) createClusterDir(c.String("name")) @@ -213,19 +213,19 @@ func CreateCluster(c *cli.Context) error { // spin up the worker nodes // TODO: do this concurrently in different goroutines if c.Int("workers") > 0 { - log.Printf("Booting %s workers for cluster %s", strconv.Itoa(c.Int("workers")), c.String("name")) + logrus.Printf("Booting %s workers for cluster %s", strconv.Itoa(c.Int("workers")), c.String("name")) for i := 0; i < c.Int("workers"); i++ { workerID, err := createWorker(clusterSpec, i) if err != nil { deleteCluster() return err } - log.Printf("Created worker with ID %s\n", workerID) + logrus.Printf("Created worker with ID %s\n", workerID) } } - log.Printf("SUCCESS: created cluster [%s]", c.String("name")) - log.Printf(`You can now use the cluster with: + logrus.Printf("SUCCESS: created cluster [%s]", c.String("name")) + logrus.Printf(`You can now use the cluster with: export KUBECONFIG="$(%s get-kubeconfig --name='%s')" kubectl cluster-info`, os.Args[0], c.String("name")) @@ -244,33 +244,33 @@ func DeleteCluster(c *cli.Context) error { // remove clusters one by one instead of appending all names to the docker command // this allows for more granular error handling and logging for _, cluster := range clusters { - log.Printf("Removing cluster [%s]", cluster.name) + logrus.Printf("Removing cluster [%s]", cluster.name) if len(cluster.workers) > 0 { // TODO: this could be done in goroutines - log.Printf("...Removing %d workers\n", len(cluster.workers)) + logrus.Printf("...Removing %d workers\n", len(cluster.workers)) for _, worker := range cluster.workers { if err := removeContainer(worker.ID); err != nil { - log.Println(err) + logrus.Println(err) continue } } } deleteClusterDir(cluster.name) - log.Println("...Removing server") + logrus.Println("...Removing server") if err := removeContainer(cluster.server.ID); err != nil { return fmt.Errorf("ERROR: Couldn't remove server for cluster %s\n%+v", cluster.name, err) } if err := deleteClusterNetwork(cluster.name); err != nil { - log.Printf("WARNING: couldn't delete cluster network for cluster %s\n%+v", cluster.name, err) + logrus.Printf("WARNING: couldn't delete cluster network for cluster %s\n%+v", cluster.name, err) } - log.Println("...Removing docker image volume") + logrus.Println("...Removing docker image volume") if err := deleteImageVolume(cluster.name); err != nil { - log.Printf("WARNING: couldn't delete image docker volume for cluster %s\n%+v", cluster.name, err) + logrus.Printf("WARNING: couldn't delete image docker volume for cluster %s\n%+v", cluster.name, err) } - log.Printf("SUCCESS: removed cluster [%s]", cluster.name) + logrus.Printf("SUCCESS: removed cluster [%s]", cluster.name) } return nil @@ -293,22 +293,22 @@ func StopCluster(c *cli.Context) error { // remove clusters one by one instead of appending all names to the docker command // this allows for more granular error handling and logging for _, cluster := range clusters { - log.Printf("Stopping cluster [%s]", cluster.name) + logrus.Printf("Stopping cluster [%s]", cluster.name) if len(cluster.workers) > 0 { - log.Printf("...Stopping %d workers\n", len(cluster.workers)) + logrus.Printf("...Stopping %d workers\n", len(cluster.workers)) for _, worker := range cluster.workers { if err := docker.ContainerStop(ctx, worker.ID, nil); err != nil { - log.Println(err) + logrus.Println(err) continue } } } - log.Println("...Stopping server") + logrus.Println("...Stopping server") if err := docker.ContainerStop(ctx, cluster.server.ID, nil); err != nil { return fmt.Errorf("ERROR: Couldn't stop server for cluster %s\n%+v", cluster.name, err) } - log.Printf("SUCCESS: Stopped cluster [%s]", cluster.name) + logrus.Printf("SUCCESS: Stopped cluster [%s]", cluster.name) } return nil @@ -331,24 +331,24 @@ func StartCluster(c *cli.Context) error { // remove clusters one by one instead of appending all names to the docker command // this allows for more granular error handling and logging for _, cluster := range clusters { - log.Printf("Starting cluster [%s]", cluster.name) + logrus.Printf("Starting cluster [%s]", cluster.name) - log.Println("...Starting server") + logrus.Println("...Starting server") if err := docker.ContainerStart(ctx, cluster.server.ID, types.ContainerStartOptions{}); err != nil { return fmt.Errorf("ERROR: Couldn't start server for cluster %s\n%+v", cluster.name, err) } if len(cluster.workers) > 0 { - log.Printf("...Starting %d workers\n", len(cluster.workers)) + logrus.Printf("...Starting %d workers\n", len(cluster.workers)) for _, worker := range cluster.workers { if err := docker.ContainerStart(ctx, worker.ID, types.ContainerStartOptions{}); err != nil { - log.Println(err) + logrus.Println(err) continue } } } - log.Printf("SUCCESS: Started cluster [%s]", cluster.name) + logrus.Printf("SUCCESS: Started cluster [%s]", cluster.name) } return nil @@ -357,7 +357,7 @@ func StartCluster(c *cli.Context) error { // ListClusters prints a list of created clusters func ListClusters(c *cli.Context) error { if c.IsSet("all") { - log.Println("INFO: --all is on by default, thus no longer required. This option will be removed in v2.0.0") + logrus.Println("INFO: --all is on by default, thus no longer required. This option will be removed in v2.0.0") } printClusters() diff --git a/cli/container.go b/cli/container.go index aadbb454..34a309bb 100644 --- a/cli/container.go +++ b/cli/container.go @@ -10,7 +10,6 @@ import ( "fmt" "io" "io/ioutil" - "log" "os" "time" @@ -18,6 +17,7 @@ import ( "github.com/docker/docker/api/types/container" "github.com/docker/docker/api/types/network" "github.com/docker/docker/client" + "github.com/sirupsen/logrus" ) type ClusterSpec struct { @@ -44,7 +44,7 @@ func startContainer(verbose bool, config *container.Config, hostConfig *containe resp, err := docker.ContainerCreate(ctx, config, hostConfig, networkingConfig, containerName) if client.IsErrNotFound(err) { - log.Printf("Pulling image %s...\n", config.Image) + logrus.Printf("Pulling image %s...\n", config.Image) reader, err := docker.ImagePull(ctx, config.Image, types.ImagePullOptions{}) if err != nil { return "", fmt.Errorf("ERROR: couldn't pull image %s\n%+v", config.Image, err) @@ -53,12 +53,12 @@ func startContainer(verbose bool, config *container.Config, hostConfig *containe if verbose { _, err := io.Copy(os.Stdout, reader) if err != nil { - log.Printf("WARNING: couldn't get docker output\n%+v", err) + logrus.Printf("WARNING: couldn't get docker output\n%+v", err) } } else { _, err := io.Copy(ioutil.Discard, reader) if err != nil { - log.Printf("WARNING: couldn't get docker output\n%+v", err) + logrus.Printf("WARNING: couldn't get docker output\n%+v", err) } } resp, err = docker.ContainerCreate(ctx, config, hostConfig, networkingConfig, containerName) @@ -77,7 +77,7 @@ func startContainer(verbose bool, config *container.Config, hostConfig *containe } func createServer(spec *ClusterSpec) (string, error) { - log.Printf("Creating server using %s...\n", spec.Image) + logrus.Printf("Creating server using %s...\n", spec.Image) containerLabels := make(map[string]string) containerLabels["app"] = "k3d" @@ -107,7 +107,7 @@ func createServer(spec *ClusterSpec) (string, error) { serverPublishedPorts, err := CreatePublishedPorts(serverPorts) if err != nil { - log.Fatalf("Error: failed to parse port specs %+v \n%+v", serverPorts, err) + logrus.Fatalf("Error: failed to parse port specs %+v \n%+v", serverPorts, err) } hostConfig := &container.HostConfig{ diff --git a/cli/docker-machine.go b/cli/docker-machine.go index cd7f97d8..5d48885b 100644 --- a/cli/docker-machine.go +++ b/cli/docker-machine.go @@ -1,10 +1,11 @@ package run import ( - "log" "os" "os/exec" "strings" + + "github.com/sirupsen/logrus" ) func getDockerMachineIp() (string, error) { @@ -21,10 +22,10 @@ func getDockerMachineIp() (string, error) { out, err := exec.Command(dockerMachinePath, "ip", machine).Output() if err != nil { - log.Printf("Error executing 'docker-machine ip'") + logrus.Printf("Error executing 'docker-machine ip'") if exitError, ok := err.(*exec.ExitError); ok { - log.Printf("%s", string(exitError.Stderr)) + logrus.Printf("%s", string(exitError.Stderr)) } return "", err } diff --git a/cli/image.go b/cli/image.go index f1a40953..3714e15c 100644 --- a/cli/image.go +++ b/cli/image.go @@ -4,7 +4,6 @@ import ( "context" "fmt" "io/ioutil" - "log" "strings" "time" @@ -12,6 +11,7 @@ import ( "github.com/docker/docker/api/types/container" "github.com/docker/docker/api/types/network" "github.com/docker/docker/client" + "github.com/sirupsen/logrus" ) const ( @@ -34,7 +34,7 @@ func importImage(clusterName string, images []string, noRemove bool) error { } //*** first, save the images using the local docker daemon - log.Printf("INFO: Saving images %s from local docker daemon...", images) + logrus.Printf("INFO: Saving images %s from local docker daemon...", images) toolsContainerName := fmt.Sprintf("k3d-%s-tools", clusterName) tarFileName := fmt.Sprintf("%s/k3d-%s-images-%s.tar", imageBasePathRemote, clusterName, time.Now().Format("20060102150405")) @@ -67,7 +67,7 @@ func importImage(clusterName string, images []string, noRemove bool) error { if err = docker.ContainerRemove(ctx, toolsContainerID, types.ContainerRemoveOptions{ Force: true, }); err != nil { - log.Println(fmt.Errorf("WARN: couldn't remove tools container\n%+v", err)) + logrus.Println(fmt.Errorf("WARN: couldn't remove tools container\n%+v", err)) } }() @@ -79,7 +79,7 @@ func importImage(clusterName string, images []string, noRemove bool) error { } if !cont.State.Running { // container finished... if cont.State.ExitCode == 0 { // ...successfully - log.Println("INFO: saved images to shared docker volume") + logrus.Println("INFO: saved images to shared docker volume") break } else if cont.State.ExitCode != 0 { // ...failed errTxt := "ERROR: helper container failed to save images" @@ -133,7 +133,7 @@ func importImage(clusterName string, images []string, noRemove bool) error { for _, container := range containerList { containerName := container.Names[0][1:] // trimming the leading "/" from name - log.Printf("INFO: Importing images %s in container [%s]", images, containerName) + logrus.Printf("INFO: Importing images %s in container [%s]", images, containerName) // create exec configuration execResponse, err := docker.ContainerExecCreate(ctx, container.ID, execConfig) @@ -169,44 +169,44 @@ func importImage(clusterName string, images []string, noRemove bool) error { } } - log.Printf("INFO: Successfully imported images %s in all nodes of cluster [%s]", images, clusterName) + logrus.Printf("INFO: Successfully imported images %s in all nodes of cluster [%s]", images, clusterName) // remove tarball from inside the server container if !noRemove { - log.Println("INFO: Cleaning up tarball") + logrus.Println("INFO: Cleaning up tarball") execID, err := docker.ContainerExecCreate(ctx, clusters[clusterName].server.ID, types.ExecConfig{ Cmd: []string{"rm", "-f", tarFileName}, }) if err != nil { - log.Printf("WARN: failed to delete tarball: couldn't create remove in container [%s]\n%+v", clusters[clusterName].server.ID, err) + logrus.Printf("WARN: failed to delete tarball: couldn't create remove in container [%s]\n%+v", clusters[clusterName].server.ID, err) } err = docker.ContainerExecStart(ctx, execID.ID, types.ExecStartCheck{ Detach: true, }) if err != nil { - log.Printf("WARN: couldn't start tarball deletion action\n%+v", err) + logrus.Printf("WARN: couldn't start tarball deletion action\n%+v", err) } for { execInspect, err := docker.ContainerExecInspect(ctx, execID.ID) if err != nil { - log.Printf("WARN: couldn't verify deletion of tarball\n%+v", err) + logrus.Printf("WARN: couldn't verify deletion of tarball\n%+v", err) } if !execInspect.Running { if execInspect.ExitCode == 0 { - log.Println("INFO: deleted tarball") + logrus.Println("INFO: deleted tarball") break } else { - log.Println("WARN: failed to delete tarball") + logrus.Println("WARN: failed to delete tarball") break } } } } - log.Println("INFO: ...Done") + logrus.Println("INFO: ...Done") return nil } diff --git a/cli/network.go b/cli/network.go index c9a33f2b..8f457f80 100644 --- a/cli/network.go +++ b/cli/network.go @@ -3,11 +3,11 @@ package run import ( "context" "fmt" - "log" "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/filters" "github.com/docker/docker/client" + "github.com/sirupsen/logrus" ) func k3dNetworkName(clusterName string) string { @@ -32,7 +32,7 @@ func createClusterNetwork(clusterName string) (string, error) { } if len(nl) > 1 { - log.Printf("WARNING: Found %d networks for %s when we only expect 1\n", len(nl), clusterName) + logrus.Printf("WARNING: Found %d networks for %s when we only expect 1\n", len(nl), clusterName) } if len(nl) > 0 { @@ -75,7 +75,7 @@ func deleteClusterNetwork(clusterName string) error { // there should be only one network that matches the name... but who knows? for _, network := range networks { if err := docker.NetworkRemove(ctx, network.ID); err != nil { - log.Printf("WARNING: couldn't remove network for cluster %s\n%+v", clusterName, err) + logrus.Printf("WARNING: couldn't remove network for cluster %s\n%+v", clusterName, err) continue } } diff --git a/cli/port.go b/cli/port.go index 6069ad31..0568ceb7 100644 --- a/cli/port.go +++ b/cli/port.go @@ -2,10 +2,10 @@ package run import ( "fmt" - "log" "strings" "github.com/docker/go-connections/nat" + "github.com/sirupsen/logrus" ) // PublishedPorts is a struct used for exposing container ports on the host system @@ -54,7 +54,7 @@ func mapNodesToPortSpecs(specs []string, createdNodes []string) (map[string][]st } } if !nodeFound { - log.Printf("WARNING: Unknown node-specifier [%s] in port mapping entry [%s]", node, spec) + logrus.Printf("WARNING: Unknown node-specifier [%s] in port mapping entry [%s]", node, spec) } } } diff --git a/main.go b/main.go index fb5dfaf1..91a315bc 100644 --- a/main.go +++ b/main.go @@ -2,12 +2,13 @@ package main import ( "fmt" - "log" "os" + "github.com/sirupsen/logrus" + "github.com/urfave/cli" + run "github.com/rancher/k3d/cli" "github.com/rancher/k3d/version" - "github.com/urfave/cli" ) // defaultK3sImage specifies the default image being used for server and workers @@ -249,6 +250,6 @@ func main() { // run the whole thing err := app.Run(os.Args) if err != nil { - log.Fatal(err) + logrus.Fatal(err) } }