Skip to content

Commit

Permalink
Merge pull request #2787 from grafana/refactor/split-ui-cmd
Browse files Browse the repository at this point in the history
Refactor console UI handling outside of the `cmd` package
  • Loading branch information
Ivan Mirić authored Dec 19, 2022
2 parents dbdcfc5 + e77b7cf commit 5070a2c
Show file tree
Hide file tree
Showing 52 changed files with 826 additions and 667 deletions.
56 changes: 33 additions & 23 deletions cmd/cloud.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ import (
"sync"
"time"

"github.com/fatih/color"
"github.com/spf13/cobra"
"github.com/spf13/pflag"

Expand All @@ -21,7 +20,7 @@ import (
"go.k6.io/k6/errext/exitcodes"
"go.k6.io/k6/lib"
"go.k6.io/k6/lib/consts"
"go.k6.io/k6/ui/pb"
"go.k6.io/k6/ui/console/pb"
)

// cmdCloud handles the `k6 cloud` sub-command
Expand Down Expand Up @@ -64,13 +63,13 @@ func (c *cmdCloud) preRun(cmd *cobra.Command, args []string) error {
// TODO: split apart some more
//nolint:funlen,gocognit,cyclop
func (c *cmdCloud) run(cmd *cobra.Command, args []string) error {
printBanner(c.gs)
maybePrintBanner(c.gs)

progressBar := pb.New(
pb.WithConstLeft("Init"),
pb.WithConstProgress(0, "Loading test script..."),
)
printBar(c.gs, progressBar)
maybePrintBar(c.gs, progressBar)

test, err := loadAndConfigureTest(c.gs, cmd, args, getPartialConfig)
if err != nil {
Expand All @@ -91,7 +90,8 @@ func (c *cmdCloud) run(cmd *cobra.Command, args []string) error {
// TODO: validate for externally controlled executor (i.e. executors that aren't distributable)
// TODO: move those validations to a separate function and reuse validateConfig()?

modifyAndPrintBar(c.gs, progressBar, pb.WithConstProgress(0, "Building the archive..."))
progressBar.Modify(pb.WithConstProgress(0, "Building the archive..."))
maybePrintBar(c.gs, progressBar)
arc := testRunState.Runner.MakeArchive()

// TODO: Fix this
Expand Down Expand Up @@ -152,14 +152,16 @@ func (c *cmdCloud) run(cmd *cobra.Command, args []string) error {
logger := c.gs.logger

// Start cloud test run
modifyAndPrintBar(c.gs, progressBar, pb.WithConstProgress(0, "Validating script options"))
progressBar.Modify(pb.WithConstProgress(0, "Validating script options"))
maybePrintBar(c.gs, progressBar)
client := cloudapi.NewClient(
logger, cloudConfig.Token.String, cloudConfig.Host.String, consts.Version, cloudConfig.Timeout.TimeDuration())
if err = client.ValidateOptions(arc.Options); err != nil {
return err
}

modifyAndPrintBar(c.gs, progressBar, pb.WithConstProgress(0, "Uploading archive"))
progressBar.Modify(pb.WithConstProgress(0, "Uploading archive"))
maybePrintBar(c.gs, progressBar)
refID, err := client.StartCloudTestRun(name, cloudConfig.ProjectID.Int64, arc)
if err != nil {
return err
Expand Down Expand Up @@ -192,24 +194,34 @@ func (c *cmdCloud) run(cmd *cobra.Command, args []string) error {
}
testURL := cloudapi.URLForResults(refID, cloudConfig)
executionPlan := test.derivedConfig.Scenarios.GetFullExecutionRequirements(et)
printExecutionDescription(
c.gs, "cloud", test.sourceRootPath, testURL, test.derivedConfig, et, executionPlan, nil,

execDesc := getExecutionDescription(
c.gs.console.ApplyTheme, "cloud", test.sourceRootPath, testURL, test.derivedConfig,
et, executionPlan, nil,
)
if c.gs.flags.quiet {
c.gs.logger.Debug(execDesc)
} else {
c.gs.console.Print(execDesc)
}

modifyAndPrintBar(
c.gs, progressBar,
pb.WithConstLeft("Run "), pb.WithConstProgress(0, "Initializing the cloud test"),
progressBar.Modify(
pb.WithConstLeft("Run "),
pb.WithConstProgress(0, "Initializing the cloud test"),
)
maybePrintBar(c.gs, progressBar)

progressCtx, progressCancel := context.WithCancel(globalCtx)
progressBarWG := &sync.WaitGroup{}
progressBarWG.Add(1)
defer progressBarWG.Wait()
defer progressCancel()
go func() {
showProgress(progressCtx, c.gs, []*pb.ProgressBar{progressBar}, logger)
progressBarWG.Done()
}()
if !c.gs.flags.quiet {
progressBarWG := &sync.WaitGroup{}
progressBarWG.Add(1)
defer progressBarWG.Wait()
go func() {
c.gs.console.ShowProgress(progressCtx, []*pb.ProgressBar{progressBar})
progressBarWG.Done()
}()
}

var (
startTime time.Time
Expand Down Expand Up @@ -282,10 +294,8 @@ func (c *cmdCloud) run(cmd *cobra.Command, args []string) error {
}

if !c.gs.flags.quiet {
valueColor := getColor(c.gs.flags.noColor || !c.gs.stdOut.isTTY, color.FgCyan)
printToStdout(c.gs, fmt.Sprintf(
" test status: %s\n", valueColor.Sprint(testProgress.RunStatusText),
))
c.gs.console.Printf(" test status: %s\n",
c.gs.console.ApplyTheme(testProgress.RunStatusText))
} else {
logger.WithField("run_status", testProgress.RunStatusText).Debug("Test finished")
}
Expand Down
58 changes: 52 additions & 6 deletions cmd/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,18 @@ package cmd
import (
"fmt"
"os"
"strings"
"syscall"
"time"

"github.com/spf13/cobra"
"github.com/spf13/pflag"
"gopkg.in/guregu/null.v3"

"go.k6.io/k6/errext/exitcodes"
"go.k6.io/k6/lib"
"go.k6.io/k6/lib/types"
"go.k6.io/k6/output"
)

// Panic if the given error is not nil.
Expand Down Expand Up @@ -65,12 +69,6 @@ func exactArgsWithMsg(n int, msg string) cobra.PositionalArgs {
}
}

func printToStdout(gs *globalState, s string) {
if _, err := fmt.Fprint(gs.stdOut, s); err != nil {
gs.logger.Errorf("could not print '%s' to stdout: %s", s, err.Error())
}
}

// Trap Interrupts, SIGINTs and SIGTERMs and call the given.
func handleTestAbortSignals(gs *globalState, gracefulStopHandler, onHardStop func(os.Signal)) (stop func()) {
sigC := make(chan os.Signal, 2)
Expand Down Expand Up @@ -103,3 +101,51 @@ func handleTestAbortSignals(gs *globalState, gracefulStopHandler, onHardStop fun
gs.signalStop(sigC)
}
}

// Generate execution description for both cloud and local execution.
// TODO: Clean this up as part of #1499 or #1427
func getExecutionDescription(
applyTheme func(string) string, execution, filename, outputOverride string,
conf Config, et *lib.ExecutionTuple, execPlan []lib.ExecutionStep,
outputs []output.Output,
) string {
buf := &strings.Builder{}
fmt.Fprintf(buf, " execution: %s\n", applyTheme(execution))
fmt.Fprintf(buf, " script: %s\n", applyTheme(filename))

var outputDescriptions []string
switch {
case outputOverride != "":
outputDescriptions = []string{outputOverride}
case len(outputs) == 0:
outputDescriptions = []string{"-"}
default:
for _, out := range outputs {
outputDescriptions = append(outputDescriptions, out.Description())
}
}

fmt.Fprintf(buf, " output: %s\n", applyTheme(strings.Join(outputDescriptions, ", ")))
fmt.Fprintf(buf, "\n")

maxDuration, _ := lib.GetEndOffset(execPlan)
executorConfigs := conf.Scenarios.GetSortedConfigs()

scenarioDesc := "1 scenario"
if len(executorConfigs) > 1 {
scenarioDesc = fmt.Sprintf("%d scenarios", len(executorConfigs))
}

fmt.Fprintf(buf, " scenarios: %s\n", applyTheme(fmt.Sprintf(
"(%.2f%%) %s, %d max VUs, %s max duration (incl. graceful stop):",
conf.ExecutionSegment.FloatLength()*100, scenarioDesc,
lib.GetMaxPossibleVUs(execPlan), maxDuration.Round(100*time.Millisecond)),
))
for _, ec := range executorConfigs {
fmt.Fprintf(buf, " * %s: %s\n",
ec.GetName(), ec.GetDescription(et))
}
fmt.Fprintf(buf, "\n")

return buf.String()
}
2 changes: 1 addition & 1 deletion cmd/convert.go
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ func getCmdConvert(globalState *globalState) *cobra.Command {

// Write script content to stdout or file
if convertOutput == "" || convertOutput == "-" { //nolint:nestif
if _, err := io.WriteString(globalState.stdOut, script); err != nil {
if _, err := io.WriteString(globalState.console.Stdout, script); err != nil {
return err
}
} else {
Expand Down
2 changes: 2 additions & 0 deletions cmd/doc.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
// Package cmd implements the command-line interface of k6.
package cmd
2 changes: 1 addition & 1 deletion cmd/inspect.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ func getCmdInspect(gs *globalState) *cobra.Command {
if err != nil {
return err
}
printToStdout(gs, string(data))
gs.console.Print(string(data))

return nil
},
Expand Down
Loading

0 comments on commit 5070a2c

Please sign in to comment.