Skip to content

Commit

Permalink
add global debug flag (#357)
Browse files Browse the repository at this point in the history
* add global debug flag

* add debug for command execution
  • Loading branch information
zreigz authored Mar 3, 2023
1 parent 331ce26 commit 2a39f5c
Show file tree
Hide file tree
Showing 11 changed files with 74 additions and 8 deletions.
1 change: 1 addition & 0 deletions cmd/plural/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ func handleInfo(c *cli.Context) error {

_, err := exec.LookPath("k9s")
if err != nil {
utils.LogError().Println(err)
if strings.Contains(err.Error(), exec.ErrNotFound.Error()) {
utils.Error("Application k9s not installed.\n")
fmt.Println("Please install it first from here: https://k9scli.io/topics/install/ and try again")
Expand Down
2 changes: 1 addition & 1 deletion cmd/plural/init.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ func (p *Plural) handleInit(c *cli.Context) error {

me, err := p.Me()
if err != nil {
return err
return api.GetErrorResponse(err, "Me")
}
if me.Demoing {
return fmt.Errorf(DemoingErrorMsg)
Expand Down
7 changes: 7 additions & 0 deletions cmd/plural/plural.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ func (p *Plural) InitPluralClient() {
if project, err := manifest.FetchProject(); err == nil && config.Exists() {
conf := config.Read()
if owner := project.Owner; owner != nil && conf.Email != owner.Email {
utils.LogInfo().Printf("Trying to impersonate service account: %s \n", owner.Email)
jwt, email, err := api.FromConfig(&conf).ImpersonateServiceAccount(owner.Email)
if err != nil {
utils.Error("You (%s) are not the owner of this repo %s, %v \n", conf.Email, owner.Email, api.GetErrorResponse(err, "ImpersonateServiceAccount"))
Expand Down Expand Up @@ -473,6 +474,12 @@ func globalFlags() []cli.Flag {
EnvVar: "PLURAL_ENCRYPTION_KEY_FILE",
Destination: &crypto.EncryptionKeyFile,
},
cli.BoolFlag{
Name: "debug",
Usage: "enable debug mode",
EnvVar: "PLURAL_DEBUG_ENABLE",
Destination: &utils.EnableDebug,
},
}
}

Expand Down
1 change: 1 addition & 0 deletions cmd/plural/validation.go
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,7 @@ func upstreamSynced(fn func(*cli.Context) error) func(*cli.Context) error {
return func(c *cli.Context) error {
changed, sha, err := git.HasUpstreamChanges()
if err != nil {
utils.LogError().Println(err)
return errors.ErrorWrap(errNoGit, "Failed to get git information")
}

Expand Down
2 changes: 2 additions & 0 deletions pkg/api/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"github.com/pkg/errors"
"github.com/pluralsh/gqlclient"
"github.com/pluralsh/plural/pkg/config"
"github.com/pluralsh/plural/pkg/utils"
)

type authedTransport struct {
Expand Down Expand Up @@ -111,6 +112,7 @@ func GetErrorResponse(err error, methodName string) error {
if err == nil {
return nil
}
utils.LogError().Println(err)
errResponse := &rawclient.ErrorResponse{}
newErr := json.Unmarshal([]byte(err.Error()), errResponse)
if newErr != nil {
Expand Down
12 changes: 9 additions & 3 deletions pkg/executor/output.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ package executor
import (
"io"
"strings"

"github.com/pluralsh/plural/pkg/utils"
)

type OutputWriter struct {
Expand All @@ -17,10 +19,14 @@ func (out *OutputWriter) Write(line []byte) (int, error) {
}

out.lines = append(out.lines, string(line))
_, err := out.delegate.Write([]byte("."))
if err != nil {
return 0, err
utils.LogInfo().Println(string(line))
if !utils.EnableDebug {
_, err := out.delegate.Write([]byte("."))
if err != nil {
return 0, err
}
}

return len(line), nil
}

Expand Down
4 changes: 4 additions & 0 deletions pkg/executor/step.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,10 @@ func SuppressedCommand(command string, args ...string) (cmd *exec.Cmd, output *O
output = &OutputWriter{delegate: os.Stdout}
cmd.Stdout = output
cmd.Stderr = output
if utils.EnableDebug {
cmd.Env = os.Environ()
cmd.Env = append(cmd.Env, fmt.Sprintf("PLURAL_DEBUG_ENABLE=%t", true))
}
return
}

Expand Down
7 changes: 3 additions & 4 deletions pkg/helm/helm.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,15 @@ import (
"log"
"strings"

"github.com/pluralsh/plural/pkg/utils"
"helm.sh/helm/v3/pkg/action"
"helm.sh/helm/v3/pkg/chart/loader"
"helm.sh/helm/v3/pkg/cli"
)

const enableDebug = false

func debug(format string, v ...interface{}) {
if enableDebug {
format = fmt.Sprintf("[debug] %s\n", format)
if utils.EnableDebug {
format = fmt.Sprintf("INFO: %s\n", format)
err := log.Output(2, fmt.Sprintf(format, v...))
if err != nil {
log.Panic(err)
Expand Down
3 changes: 3 additions & 0 deletions pkg/provider/azure.go
Original file line number Diff line number Diff line change
Expand Up @@ -251,6 +251,7 @@ func (az *AzureProvider) CreateResourceGroup(resourceGroup string) error {
}

if isNotFoundResourceGroup(err) {
utils.LogInfo().Printf("The resource group %s is not found, creating ...", resourceGroup)
param := armresources.ResourceGroup{
Location: to.StringPtr(az.region),
}
Expand All @@ -259,6 +260,7 @@ func (az *AzureProvider) CreateResourceGroup(resourceGroup string) error {
if err != nil {
return err
}
utils.LogInfo().Printf("The resource group %s created successfully", resourceGroup)
}

return nil
Expand Down Expand Up @@ -399,6 +401,7 @@ func (az *AzureProvider) upsertStorageAccount(account string) (storage.Account,
}

if inNotFoundStorageAccount(err) {
utils.LogInfo().Printf("The storage account %s is not found, creating ...", account)
ctx := context.Background()
future, err := az.clients.Accounts.Create(
ctx,
Expand Down
5 changes: 5 additions & 0 deletions pkg/provider/gcp.go
Original file line number Diff line number Diff line change
Expand Up @@ -360,6 +360,7 @@ func (gcp *GCPProvider) validateEnabled() error {
errEnabled := fmt.Errorf("You don't have necessary services enabled. Please run: `gcloud services enable serviceusage.googleapis.com cloudresourcemanager.googleapis.com container.googleapis.com` with an owner of the project to enable or enable them in the GCP console.")
proj, err := gcp.getProject()
if err != nil {
utils.LogError().Println(err)
return errEnabled
}

Expand All @@ -376,11 +377,13 @@ func (gcp *GCPProvider) validateEnabled() error {
}
resp, err := c.BatchGetServices(ctx, req)
if err != nil {
utils.LogError().Println(err)
return errEnabled
}

for _, svc := range resp.Services {
if svc.State != serviceusagepb.State_ENABLED {
utils.LogError().Printf("the service state %v != %v", svc.State, serviceusagepb.State_ENABLED)
return errEnabled
}
}
Expand All @@ -397,6 +400,7 @@ func (gcp *GCPProvider) Permissions() (permissions.Checker, error) {
}

func (gcp *GCPProvider) validatePermissions() error {
utils.LogInfo().Println("Validate GCP permissions")
ctx := context.Background()
proj, err := gcp.getProject()
if err != nil {
Expand All @@ -414,6 +418,7 @@ func (gcp *GCPProvider) validatePermissions() error {
}

for _, perm := range missing {
utils.LogError().Printf("Required GCP permission %s \n", perm)
provUtils.FailedPermission(perm)
}

Expand Down
38 changes: 38 additions & 0 deletions pkg/utils/logs.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package utils

import (
"io"
"log"
"os"
)

func init() {
EnableDebug = false
}

var infoLogger *log.Logger
var errorLogger *log.Logger

var EnableDebug bool

func LogInfo() *log.Logger {
if infoLogger == nil {
infoLogger = log.New(getOutputWriter(), "INFO: ", log.Ldate|log.Ltime|log.Lshortfile)
}
return infoLogger
}

func LogError() *log.Logger {
if errorLogger == nil {
errorLogger = log.New(getOutputWriter(), "ERROR: ", log.Ldate|log.Ltime|log.Lshortfile)
}
return errorLogger
}

func getOutputWriter() (out io.Writer) {
out = os.Stdout
if !EnableDebug {
out = io.Discard
}
return
}

0 comments on commit 2a39f5c

Please sign in to comment.