Refactor logging

pull/1/head
stefanprodan 5 years ago
parent 2d300d7344
commit 8392c4fe24

@ -1,7 +1,6 @@
package main package main
import ( import (
"fmt"
"os" "os"
"os/exec" "os/exec"
"strings" "strings"
@ -32,6 +31,7 @@ func init() {
} }
func runCheckCmd(cmd *cobra.Command, args []string) error { func runCheckCmd(cmd *cobra.Command, args []string) error {
logAction("starting verification")
checkFailed := false checkFailed := false
if !sshCheck() { if !sshCheck() {
checkFailed = true checkFailed = true
@ -49,7 +49,7 @@ func runCheckCmd(cmd *cobra.Command, args []string) error {
if checkFailed { if checkFailed {
os.Exit(1) os.Exit(1)
} }
fmt.Println(``, "all prerequisites checks passed") logSuccess("all prerequisites checks passed")
return nil return nil
} }
@ -60,7 +60,7 @@ func runCheckCmd(cmd *cobra.Command, args []string) error {
if checkFailed { if checkFailed {
os.Exit(1) os.Exit(1)
} }
fmt.Println(``, "all checks passed") logSuccess("all checks passed")
return nil return nil
} }
@ -69,10 +69,10 @@ func sshCheck() bool {
for _, cmd := range []string{"ssh-keygen", "ssh-keyscan"} { for _, cmd := range []string{"ssh-keygen", "ssh-keyscan"} {
_, err := exec.LookPath(cmd) _, err := exec.LookPath(cmd)
if err != nil { if err != nil {
fmt.Println(``, cmd, "not found") logFailure("%s not found", cmd)
ok = false ok = false
} else { } else {
fmt.Println(``, cmd, "found") logSuccess("%s found", cmd)
} }
} }
@ -82,94 +82,94 @@ func sshCheck() bool {
func kubectlCheck(version string) bool { func kubectlCheck(version string) bool {
_, err := exec.LookPath("kubectl") _, err := exec.LookPath("kubectl")
if err != nil { if err != nil {
fmt.Println(``, "kubectl not found") logFailure("kubectl not found")
return false return false
} }
output, err := execCommand("kubectl version --client --short | awk '{ print $3 }'") output, err := execCommand("kubectl version --client --short | awk '{ print $3 }'")
if err != nil { if err != nil {
fmt.Println(``, "kubectl version can't be determined") logFailure("kubectl version can't be determined")
return false return false
} }
v, err := semver.ParseTolerant(output) v, err := semver.ParseTolerant(output)
if err != nil { if err != nil {
fmt.Println(``, "kubectl version can't be parsed") logFailure("kubectl version can't be parsed")
return false return false
} }
rng, _ := semver.ParseRange(version) rng, _ := semver.ParseRange(version)
if !rng(v) { if !rng(v) {
fmt.Println(``, "kubectl version must be", version) logFailure("kubectl version must be %s", version)
return false return false
} }
fmt.Println(``, "kubectl", v.String(), version) logSuccess("kubectl %s %s", v.String(), version)
return true return true
} }
func kustomizeCheck(version string) bool { func kustomizeCheck(version string) bool {
_, err := exec.LookPath("kustomize") _, err := exec.LookPath("kustomize")
if err != nil { if err != nil {
fmt.Println(``, "kustomize not found") logFailure("kustomize not found")
return false return false
} }
output, err := execCommand("kustomize version --short | awk '{ print $1 }' | cut -c2-") output, err := execCommand("kustomize version --short | awk '{ print $1 }' | cut -c2-")
if err != nil { if err != nil {
fmt.Println(``, "kustomize version can't be determined") logFailure("kustomize version can't be determined")
return false return false
} }
if strings.Contains(output, "kustomize/") { if strings.Contains(output, "kustomize/") {
output, err = execCommand("kustomize version --short | awk '{ print $1 }' | cut -c12-") output, err = execCommand("kustomize version --short | awk '{ print $1 }' | cut -c12-")
if err != nil { if err != nil {
fmt.Println(``, "kustomize version can't be determined") logFailure("kustomize version can't be determined")
return false return false
} }
} }
v, err := semver.ParseTolerant(output) v, err := semver.ParseTolerant(output)
if err != nil { if err != nil {
fmt.Println(``, "kustomize version can't be parsed") logFailure("kustomize version can't be parsed")
return false return false
} }
rng, _ := semver.ParseRange(version) rng, _ := semver.ParseRange(version)
if !rng(v) { if !rng(v) {
fmt.Println(``, "kustomize version must be", version) logFailure("kustomize version must be %s", version)
return false return false
} }
fmt.Println(``, "kustomize", v.String(), version) logSuccess("kustomize %s %s", v.String(), version)
return true return true
} }
func kubernetesCheck(version string) bool { func kubernetesCheck(version string) bool {
client, err := kubernetesClient() client, err := kubernetesClient()
if err != nil { if err != nil {
fmt.Println(``, "kubernetes client initialization failed", err.Error()) logFailure("kubernetes client initialization failed: %s", err.Error())
return false return false
} }
ver, err := client.Discovery().ServerVersion() ver, err := client.Discovery().ServerVersion()
if err != nil { if err != nil {
fmt.Println(``, "kubernetes API call failed", err.Error()) logFailure("kubernetes API call failed %s", err.Error())
return false return false
} }
v, err := semver.ParseTolerant(ver.String()) v, err := semver.ParseTolerant(ver.String())
if err != nil { if err != nil {
fmt.Println(``, "kubernetes version can't be determined") logFailure("kubernetes version can't be determined")
return false return false
} }
rng, _ := semver.ParseRange(version) rng, _ := semver.ParseRange(version)
if !rng(v) { if !rng(v) {
fmt.Println(``, "kubernetes version must be", version) logFailure("kubernetes version must be %s", version)
return false return false
} }
fmt.Println(``, "kubernetes", v.String(), version) logSuccess("kubernetes %s %s", v.String(), version)
return true return true
} }

@ -3,6 +3,7 @@ package main
import ( import (
"bufio" "bufio"
"bytes" "bytes"
"context"
"fmt" "fmt"
"io" "io"
"io/ioutil" "io/ioutil"
@ -78,6 +79,9 @@ func createSourceCmdRun(cmd *cobra.Command, args []string) error {
return fmt.Errorf("git URL parse failed: %w", err) return fmt.Errorf("git URL parse failed: %w", err)
} }
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
withAuth := false withAuth := false
if strings.HasPrefix(sourceGitURL, "ssh") { if strings.HasPrefix(sourceGitURL, "ssh") {
if err := generateSSH(name, u.Host, tmpDir); err != nil { if err := generateSSH(name, u.Host, tmpDir); err != nil {
@ -91,7 +95,7 @@ func createSourceCmdRun(cmd *cobra.Command, args []string) error {
withAuth = true withAuth = true
} }
fmt.Println(``, "generating source resource") logAction("generating source %s in %s namespace", name, namespace)
t, err := template.New("tmpl").Parse(gitSource) t, err := template.New("tmpl").Parse(gitSource)
if err != nil { if err != nil {
@ -130,7 +134,7 @@ func createSourceCmdRun(cmd *cobra.Command, args []string) error {
} }
command := fmt.Sprintf("echo '%s' | kubectl apply -f-", data.String()) command := fmt.Sprintf("echo '%s' | kubectl apply -f-", data.String())
c := exec.Command("/bin/sh", "-c", command) c := exec.CommandContext(ctx, "/bin/sh", "-c", command)
var stdoutBuf, stderrBuf bytes.Buffer var stdoutBuf, stderrBuf bytes.Buffer
c.Stdout = io.MultiWriter(os.Stdout, &stdoutBuf) c.Stdout = io.MultiWriter(os.Stdout, &stdoutBuf)
@ -138,11 +142,10 @@ func createSourceCmdRun(cmd *cobra.Command, args []string) error {
err = c.Run() err = c.Run()
if err != nil { if err != nil {
fmt.Println(``, "source apply failed") return fmt.Errorf("source apply failed")
os.Exit(1)
} }
fmt.Println(``, "waiting for source sync") logAction("waiting for source sync")
if output, err := execCommand(fmt.Sprintf( if output, err := execCommand(fmt.Sprintf(
"kubectl -n %s wait gitrepository/%s --for=condition=ready --timeout=1m", "kubectl -n %s wait gitrepository/%s --for=condition=ready --timeout=1m",
namespace, name)); err != nil { namespace, name)); err != nil {
@ -155,7 +158,7 @@ func createSourceCmdRun(cmd *cobra.Command, args []string) error {
} }
func generateBasicAuth(name string) error { func generateBasicAuth(name string) error {
fmt.Println(``, "saving credentials") logAction("saving credentials")
credentials := fmt.Sprintf("--from-literal=username='%s' --from-literal=password='%s'", credentials := fmt.Sprintf("--from-literal=username='%s' --from-literal=password='%s'",
sourceUsername, sourcePassword) sourceUsername, sourcePassword)
secret := fmt.Sprintf("kubectl -n %s create secret generic %s %s --dry-run=client -oyaml | kubectl apply -f-", secret := fmt.Sprintf("kubectl -n %s create secret generic %s %s --dry-run=client -oyaml | kubectl apply -f-",
@ -169,14 +172,14 @@ func generateBasicAuth(name string) error {
} }
func generateSSH(name, host, tmpDir string) error { func generateSSH(name, host, tmpDir string) error {
fmt.Println(``, "generating host key for", host) logAction("generating host key for %s", host)
keyscan := fmt.Sprintf("ssh-keyscan %s > %s/known_hosts", host, tmpDir) keyscan := fmt.Sprintf("ssh-keyscan %s > %s/known_hosts", host, tmpDir)
if output, err := execCommand(keyscan); err != nil { if output, err := execCommand(keyscan); err != nil {
return fmt.Errorf("ssh-keyscan failed: %s", output) return fmt.Errorf("ssh-keyscan failed: %s", output)
} }
fmt.Println(``, "generating deploy key") logAction("generating deploy key")
keygen := fmt.Sprintf("ssh-keygen -b 2048 -t rsa -f %s/identity -q -N \"\"", tmpDir) keygen := fmt.Sprintf("ssh-keygen -b 2048 -t rsa -f %s/identity -q -N \"\"", tmpDir)
if output, err := execCommand(keygen); err != nil { if output, err := execCommand(keygen); err != nil {
@ -194,11 +197,11 @@ func generateSSH(name, host, tmpDir string) error {
IsConfirm: true, IsConfirm: true,
} }
if _, err := prompt.Run(); err != nil { if _, err := prompt.Run(); err != nil {
fmt.Println(``, "aborting") logFailure("aborting")
os.Exit(1) os.Exit(1)
} }
fmt.Println(``, "saving deploy key") logAction("saving deploy key")
files := fmt.Sprintf("--from-file=%s/identity --from-file=%s/identity.pub --from-file=%s/known_hosts", files := fmt.Sprintf("--from-file=%s/identity --from-file=%s/identity.pub --from-file=%s/known_hosts",
tmpDir, tmpDir, tmpDir) tmpDir, tmpDir, tmpDir)
secret := fmt.Sprintf("kubectl -n %s create secret generic %s %s --dry-run=client -oyaml | kubectl apply -f-", secret := fmt.Sprintf("kubectl -n %s create secret generic %s %s --dry-run=client -oyaml | kubectl apply -f-",

@ -62,19 +62,19 @@ func installCmdRun(cmd *cobra.Command, args []string) error {
c.Stdout = io.MultiWriter(os.Stdout, &stdoutBuf) c.Stdout = io.MultiWriter(os.Stdout, &stdoutBuf)
c.Stderr = io.MultiWriter(os.Stderr, &stderrBuf) c.Stderr = io.MultiWriter(os.Stderr, &stderrBuf)
fmt.Println(``, "installing...") logAction("installing components in %s namespace", namespace)
err := c.Run() err := c.Run()
if err != nil { if err != nil {
fmt.Println(``, "install failed") logFailure("install failed")
os.Exit(1) os.Exit(1)
} }
if installDryRun { if installDryRun {
fmt.Println(``, "install dry-run finished") logSuccess("install dry-run finished")
return nil return nil
} }
fmt.Println(``, "verifying installation...") logAction("verifying installation")
for _, deployment := range []string{"source-controller", "kustomize-controller"} { for _, deployment := range []string{"source-controller", "kustomize-controller"} {
command = fmt.Sprintf("kubectl -n %s rollout status deployment %s --timeout=%s", command = fmt.Sprintf("kubectl -n %s rollout status deployment %s --timeout=%s",
namespace, deployment, timeout.String()) namespace, deployment, timeout.String())
@ -83,11 +83,11 @@ func installCmdRun(cmd *cobra.Command, args []string) error {
c.Stderr = io.MultiWriter(os.Stderr, &stderrBuf) c.Stderr = io.MultiWriter(os.Stderr, &stderrBuf)
err := c.Run() err := c.Run()
if err != nil { if err != nil {
fmt.Println(``, "install failed") logFailure("install failed")
os.Exit(1) os.Exit(1)
} }
} }
fmt.Println(``, "install finished") logSuccess("install finished")
return nil return nil
} }

@ -47,7 +47,7 @@ func init() {
func main() { func main() {
log.SetFlags(0) log.SetFlags(0)
if err := rootCmd.Execute(); err != nil { if err := rootCmd.Execute(); err != nil {
fmt.Println(err) logFailure("%v", err)
os.Exit(1) os.Exit(1)
} }
} }
@ -81,3 +81,15 @@ func execCommand(command string) (string, error) {
} }
return string(output), nil return string(output), nil
} }
func logAction(format string, a ...interface{}) {
fmt.Println(``, fmt.Sprintf(format, a...))
}
func logSuccess(format string, a ...interface{}) {
fmt.Println(``, fmt.Sprintf(format, a...))
}
func logFailure(format string, a ...interface{}) {
fmt.Println(``, fmt.Sprintf(format, a...))
}

@ -49,7 +49,7 @@ func uninstallCmdRun(cmd *cobra.Command, args []string) error {
IsConfirm: true, IsConfirm: true,
} }
if _, err := prompt.Run(); err != nil { if _, err := prompt.Run(); err != nil {
fmt.Println(``, "aborting") logFailure("aborting")
os.Exit(1) os.Exit(1)
} }
} }
@ -67,13 +67,13 @@ func uninstallCmdRun(cmd *cobra.Command, args []string) error {
c.Stdout = io.MultiWriter(os.Stdout, &stdoutBuf) c.Stdout = io.MultiWriter(os.Stdout, &stdoutBuf)
c.Stderr = io.MultiWriter(os.Stderr, &stderrBuf) c.Stderr = io.MultiWriter(os.Stderr, &stderrBuf)
fmt.Println(``, "uninstalling...") logAction("uninstalling components")
err := c.Run() err := c.Run()
if err != nil { if err != nil {
fmt.Println(``, "uninstall failed") logFailure("uninstall failed")
os.Exit(1) os.Exit(1)
} }
fmt.Println(``, "uninstall finished") logSuccess("uninstall finished")
return nil return nil
} }

Loading…
Cancel
Save