Skip to content

Commit

Permalink
Refactor.
Browse files Browse the repository at this point in the history
Change `redirect-console-to-file` to  `console-output`

Console/Env variables override `.js` config variables.
Add a method to initialise a file-based config
if  `console-output` is provided.

Update breaking test.
  • Loading branch information
cheesedosa committed Jan 15, 2019
1 parent 49458ba commit 65afa75
Show file tree
Hide file tree
Showing 7 changed files with 62 additions and 37 deletions.
6 changes: 3 additions & 3 deletions cmd/options.go
Expand Up @@ -67,7 +67,7 @@ func optionFlagSet() *pflag.FlagSet {
flags.String("summary-time-unit", "", "define the time unit used to display the trend stats. Possible units are: 's', 'ms' and 'us'")
flags.StringSlice("system-tags", lib.DefaultSystemTagList, "only include these system tags in metrics")
flags.StringSlice("tag", nil, "add a `tag` to be applied to all samples, as `[name]=[value]`")
flags.String("redirect-console-to-file", "", "redirects the console logging to the provided file")
flags.String("console-output", "", "redirects the console logging to the provided output file")
flags.Bool("discard-response-bodies", false, "Read but don't process or save HTTP response bodies")
return flags
}
Expand Down Expand Up @@ -175,13 +175,13 @@ func getOptions(flags *pflag.FlagSet) (lib.Options, error) {
opts.RunTags = stats.IntoSampleTags(&parsedRunTags)
}

redirectConFile, err := flags.GetString("redirect-console-to-file")
redirectConFile, err := flags.GetString("console-output")
if err != nil {
return opts, err
}

if redirectConFile != "" {
opts.RedirectConsoleToFile = null.StringFrom(redirectConFile)
opts.ConsoleOutput = null.StringFrom(redirectConFile)
}

return opts, nil
Expand Down
8 changes: 8 additions & 0 deletions cmd/run.go
Expand Up @@ -173,6 +173,14 @@ a commandline interface for interacting with it.`,
// Write options back to the runner too.
r.SetOptions(conf.Options)

// If we have a file-based console, we need to override the
// default console.
if conf.ConsoleOutput.Valid {
if err := r.InitConsole(); err != nil {
return err
}
}

// Create a local executor wrapping the runner.
fprintf(stdout, "%s executor\r", initBar.String())
ex := local.New(r)
Expand Down
13 changes: 3 additions & 10 deletions js/console.go
Expand Up @@ -27,7 +27,6 @@ import (

"github.com/dop251/goja"
log "github.com/sirupsen/logrus"
"github.com/spf13/afero"
)

type Console struct {
Expand All @@ -40,16 +39,10 @@ func NewConsole() *Console {
}

// NewFileConsole creates a console logger with its output set to the file at the provided `filepath`.
func NewFileConsole(fs afero.Fs, filepath string) (*Console, error) {
f, err := fs.OpenFile(filepath, os.O_APPEND|os.O_WRONLY, os.ModeAppend)
func NewFileConsole(filepath string) (*Console, error) {
f, err := os.OpenFile(filepath, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0644)
if err != nil {
if os.IsNotExist(err) {
if f, err = fs.Create(filepath); err != nil {
return nil, err
}
} else {
return nil, err
}
return nil, err
}

l := log.New()
Expand Down
25 changes: 16 additions & 9 deletions js/console_test.go
Expand Up @@ -24,8 +24,11 @@ import (
"context"
"fmt"
"io/ioutil"
"os"
"testing"

"gopkg.in/guregu/null.v3"

"github.com/dop251/goja"
"github.com/loadimpact/k6/js/common"
"github.com/loadimpact/k6/lib"
Expand Down Expand Up @@ -146,17 +149,19 @@ func TestFileConsole(t *testing.T) {
t.Run(name, func(t *testing.T) {
for args, result := range argsets {
t.Run(args, func(t *testing.T) {
mockFs := afero.NewMemMapFs()
r, err := New(&lib.SourceData{
Filename: "/script",
Data: []byte(fmt.Sprintf(
`export let options = {
redirectConsoleToFile: "%s",
};
export default function() { console.%s(%s); }`,
logFile, name, args,
`export default function() { console.%s(%s); }`,
name, args,
)),
}, mockFs, lib.RuntimeOptions{})
}, afero.NewMemMapFs(), lib.RuntimeOptions{})
assert.NoError(t, err)

r.SetOptions(lib.Options{
ConsoleOutput: null.StringFrom(logFile),
})
err = r.InitConsole()
assert.NoError(t, err)

samples := make(chan stats.SampleContainer, 100)
Expand All @@ -170,7 +175,7 @@ func TestFileConsole(t *testing.T) {
assert.NoError(t, err)

// Test if the file was created.
_, err = mockFs.Stat(logFile)
_, err = os.Stat(logFile)
assert.NoError(t, err)

entry := hook.LastEntry()
Expand All @@ -189,14 +194,16 @@ func TestFileConsole(t *testing.T) {
entryStr, err := entry.String()
assert.NoError(t, err)

f, err := mockFs.Open(logFile)
f, err := os.Open(logFile)
assert.NoError(t, err)

fileContent, err := ioutil.ReadAll(f)
assert.NoError(t, err)

assert.Equal(t, entryStr, string(fileContent))
}

os.Remove(logFile)
})
}
})
Expand Down
34 changes: 22 additions & 12 deletions js/runner.go
Expand Up @@ -84,16 +84,6 @@ func NewFromBundle(b *Bundle) (*Runner, error) {
return nil, err
}

// Initialise a console for the Runner.
var c *Console
if b.Options.RedirectConsoleToFile.Valid {
if c, err = NewFileConsole(b.BaseInitContext.fs, b.Options.RedirectConsoleToFile.String); err != nil {
return nil, err
}
} else {
c = NewConsole()
}

r := &Runner{
Bundle: b,
Logger: log.StandardLogger(),
Expand All @@ -104,10 +94,11 @@ func NewFromBundle(b *Bundle) (*Runner, error) {
DualStack: true,
},
Resolver: dnscache.New(0),
console: c,
}

r.SetOptions(r.Bundle.Options)
return r, nil
err = r.InitConsole()
return r, err
}

func (r *Runner) MakeArchive() *lib.Archive {
Expand Down Expand Up @@ -281,6 +272,25 @@ func (r *Runner) SetOptions(opts lib.Options) {
}
}

// InitConsole initialises a console based on the runner config.
func (r *Runner) InitConsole() error {
var (
c *Console
err error
)

if r.Bundle.Options.ConsoleOutput.Valid {
if c, err = NewFileConsole(r.Bundle.Options.ConsoleOutput.String); err != nil {
return err
}
} else {
c = NewConsole()
}

r.console = c
return nil
}

// Runs an exported function in its own temporary VU, optionally with an argument. Execution is
// interrupted if the context expires. No error is returned if the part does not exist.
func (r *Runner) runPart(ctx context.Context, out chan<- stats.SampleContainer, name string, arg interface{}) (goja.Value, error) {
Expand Down
6 changes: 3 additions & 3 deletions lib/options.go
Expand Up @@ -274,7 +274,7 @@ type Options struct {
DiscardResponseBodies null.Bool `json:"discardResponseBodies" envconfig:"discard_response_bodies"`

// Redirect console logging to a file
RedirectConsoleToFile null.String `json:"redirectConsoleToFile" envconfig:"redirect_console_to_file"`
ConsoleOutput null.String `json:"-" envconfig:"console_output"`
}

// Returns the result of overwriting any fields with any that are set on the argument.
Expand Down Expand Up @@ -388,8 +388,8 @@ func (o Options) Apply(opts Options) Options {
if opts.DiscardResponseBodies.Valid {
o.DiscardResponseBodies = opts.DiscardResponseBodies
}
if opts.RedirectConsoleToFile.Valid {
o.RedirectConsoleToFile = opts.RedirectConsoleToFile
if opts.ConsoleOutput.Valid {
o.ConsoleOutput = opts.ConsoleOutput
}

return o
Expand Down
7 changes: 7 additions & 0 deletions lib/runner.go
Expand Up @@ -66,6 +66,9 @@ type Runner interface {
// values and write it back to the runner.
GetOptions() Options
SetOptions(opts Options)

// Initialise a new console for the runner (stdout/file) based on the config.
InitConsole() error
}

// A VU is a Virtual User, that can be scheduled by an Executor.
Expand Down Expand Up @@ -142,6 +145,10 @@ func (r *MiniRunner) SetOptions(opts Options) {
r.Options = opts
}

func (r *MiniRunner) InitConsole() error {
return nil
}

// A VU spawned by a MiniRunner.
type MiniRunnerVU struct {
R MiniRunner
Expand Down

0 comments on commit 65afa75

Please sign in to comment.