From 5318498d9accee919387c1fa5a14c77c8dcece8a Mon Sep 17 00:00:00 2001 From: Bryan Boreham Date: Tue, 9 Jun 2020 21:21:56 +0000 Subject: [PATCH] improvement: make command-line parsing more robust --- app/multitenant/billing_emitter.go | 15 +++++++++------ app/multitenant/billing_emitter_test.go | 3 +++ 2 files changed, 12 insertions(+), 6 deletions(-) diff --git a/app/multitenant/billing_emitter.go b/app/multitenant/billing_emitter.go index 946f44daa..0e74d397d 100644 --- a/app/multitenant/billing_emitter.go +++ b/app/multitenant/billing_emitter.go @@ -120,13 +120,16 @@ func (e *BillingEmitter) Add(ctx context.Context, rep report.Report, buf []byte) } func commandParameter(cmd, flag string) (string, bool) { - if strings.Contains(cmd, flag) { - cmds := strings.SplitAfter(cmd, flag) - aft := strings.Split(cmds[1], " ") - if aft[0] == "" { - return aft[1], true + i := strings.Index(cmd, flag) + if i != -1 { + // here we expect the command looks like `-foo=bar` or `-foo bar` + aft := strings.Fields(cmd[i+len(flag):]) + if len(aft) > 0 && len(aft[0]) > 0 { + if aft[0][0] == '=' { + return aft[0][1:], true + } + return aft[0], true } - return aft[0][1:], true } return "", false } diff --git a/app/multitenant/billing_emitter_test.go b/app/multitenant/billing_emitter_test.go index 155744558..5e6b006c2 100644 --- a/app/multitenant/billing_emitter_test.go +++ b/app/multitenant/billing_emitter_test.go @@ -15,6 +15,9 @@ func Test_intervalFromCommand(t *testing.T) { {cmd: "/home/weave/scope --mode=probe --probe-only --probe.kubernetes.role=host --probe.publish.interval=4500ms --probe.spy.interval=10s --probe.docker.bridge=docker0 --probe.docker=true --probe.ebpf.connections=false --probe.conntrack=false https://redacted@cloud.weave.works.", want: "10s", name: "higher-spy-interval"}, {cmd: "/bin/prometheus --config.file=/etc/prometheus/prometheus.yml --web.listen-address=:8080 --storage.tsdb.retention.time=2h --web.enable-lifecycle", want: "", name: "notscope"}, {cmd: "", want: "", name: "blank"}, + {cmd: "/home/weave/scope --probe.publish.interval=3s", want: "3s", name: "at-end"}, + {cmd: "/home/weave/scope --probe.publish.interval=", want: "", name: "equals-blank"}, + {cmd: "/home/weave/scope --probe.publish.interval", want: "", name: "no-value"}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) {