forked from yarpc/yab
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
536 lines (460 loc) · 16.7 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
// Copyright (c) 2016 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
package main
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"os"
"regexp"
"strings"
"github.com/yarpc/yab/encoding"
"github.com/yarpc/yab/peerprovider"
"github.com/yarpc/yab/plugin"
"github.com/yarpc/yab/transport"
"github.com/casimir/xdg-go"
"github.com/jessevdk/go-flags"
"github.com/opentracing/opentracing-go"
opentracing_ext "github.com/opentracing/opentracing-go/ext"
"github.com/uber/jaeger-client-go"
jaeger_config "github.com/uber/jaeger-client-go/config"
"github.com/uber/tchannel-go"
"go.uber.org/zap"
)
var (
errHealthAndProcedure = errors.New("cannot specify procedure and use --health")
// map of caller names we do not want to be used.
warningCallerNames = map[string]struct{}{"tcurl": struct{}{}}
blockedCallerNames = map[string]struct{}{}
)
func findGroup(parser *flags.Parser, group string) *flags.Group {
if g := parser.Group.Find(group); g != nil {
return g
}
panic("no group called " + group + " found.")
}
func setGroupDescs(parser *flags.Parser, groupName, shortDesc, longDesc string) {
g := findGroup(parser, groupName)
g.ShortDescription = shortDesc
g.LongDescription = longDesc
}
func fromPositional(args []string, index int, s *string) bool {
if len(args) <= index {
return false
}
if args[index] != "" {
*s = args[index]
}
return true
}
func main() {
log.SetFlags(0)
parseAndRun(consoleOutput{os.Stdout})
}
var errExit = errors.New("sentinel error used to exit cleanly")
func toGroff(s string) string {
// Expand tabbed lines beginning with "-" as items in a bullet list.
s = strings.Replace(s, "\n\t* ", "\n.IP \\[bu]\n", -1 /* all occurences */)
// Two newlines start a new paragraph.
s = strings.Replace(s, "\n\n", "\n.PP\n", -1)
// Lines beginning with a tab are interpreted as example code.
//
// See http://liw.fi/manpages/ for an explanation of these
// commands -- tl;dr: turn of paragraph filling and indent the
// block one level.
indentRegexp := regexp.MustCompile(`\t(.*)\n`)
s = indentRegexp.ReplaceAllString(s, ".nf\n.RS\n$1\n.RE\n.fi\n")
return s
}
func newParser() (*flags.Parser, *Options) {
opts := newOptions()
return flags.NewParser(opts, flags.HelpFlag|flags.PassDoubleDash), opts
}
func getOptions(args []string, out output) (*Options, error) {
parser, opts := newParser()
parser.Usage = "[<service> <method> <body>] [OPTIONS]"
parser.ShortDescription = "yet another benchmarker"
parser.LongDescription = `
yab is a benchmarking tool for TChannel and HTTP applications. It's primarily intended for Thrift applications but supports other encodings like JSON and binary (raw). It can be used in a curl-like fashion when benchmarking features are disabled.
yab includes a full man page (man yab), which is also available online: http://yarpc.github.io/yab/man.html
`
// Read defaults if they're available, before we change the group names.
if err := parseDefaultConfigs(parser); err != nil {
return nil, fmt.Errorf("error reading defaults: %v", err)
}
// Check if the first argument is a yab template. This is to support using
// yab as a shebang, since flags aren't supported in shebangs.
if len(args) > 0 && isYabTemplate(args[0]) {
args = append([]string{"-y"}, args...)
}
if err := overrideDefaults(opts, args); err != nil {
return nil, err
}
setGroupDescs(parser, "request", "Request Options", toGroff(_reqOptsDesc))
setGroupDescs(parser, "transport", "Transport Options", toGroff(_transportOptsDesc))
setGroupDescs(parser, "benchmark", "Benchmark Options", toGroff(_benchmarkOptsDesc))
if err := plugin.AddToParser(pluginParserAdapter{parser}); err != nil {
out.Warnf("WARNING: Error adding plugin-based custom flags: %+v.", err)
}
remaining, err := parser.ParseArgs(args)
// If there are no arguments specified, write the help.
// We do this after Parse, otherwise the output doesn't show defaults.
if len(args) == 0 {
parser.WriteHelp(out)
return opts, errExit
}
if err != nil {
if ferr, ok := err.(*flags.Error); ok {
if ferr.Type == flags.ErrHelp {
parser.WriteHelp(out)
return opts, errExit
}
}
return opts, err
}
setEncodingOptions(opts)
if opts.DisplayVersion {
out.Printf("yab version %v\n", versionString)
return opts, errExit
}
if opts.ManPage {
parser.LongDescription += `
Default options can be specified in a ~/.config/yab/defaults.ini file (or ~/Library/Preferences/yab/defaults.ini on Mac) with contents similar to this:
[request]
timeout = 2s
[transport]
peer-list = "/path/to/peer/list.json"
[benchmark]
warmup = 10
`
parser.LongDescription = toGroff(parser.LongDescription)
parser.WriteManPage(out)
return opts, errExit
}
fromPositional(remaining, 0, &opts.TOpts.ServiceName)
fromPositional(remaining, 1, &opts.ROpts.Procedure)
// We support both:
// [service] [method] [request]
// [service] [method] [headers] [request]
if fromPositional(remaining, 3, &opts.ROpts.RequestJSON) {
fromPositional(remaining, 2, &opts.ROpts.HeadersJSON)
} else {
fromPositional(remaining, 2, &opts.ROpts.RequestJSON)
}
return opts, nil
}
// parseAndRun is like main, but uses the given output.
func parseAndRun(out output) {
opts, err := getOptions(os.Args[1:], out)
if err != nil {
if err == errExit {
return
}
out.Fatalf("Failed to parse options: %v", err)
}
loggerConfig := configureLoggerConfig(opts)
logger, err := loggerConfig.Build()
if err != nil {
out.Fatalf("failed to setup logger: %v", err)
return
}
logger.Debug("Logger initialized.", zap.Stringer("level", loggerConfig.Level))
runWithOptions(*opts, out, logger)
}
// overrideDefaults clears fields in the default options that may
// clash with user-specified options.
// E.g., if the defaults has a peer list file, and the user has specifed
// a peer through the command line, then the final options should only
// contain the peer specified in the args.
func overrideDefaults(defaults *Options, args []string) error {
argsParser, argsOnly := newParser()
argsParser.ParseArgs(args)
// If there's a YAML request specified, read that now.
if argsOnly.ROpts.YamlTemplate != "" {
if err := readYAMLFile(argsOnly.ROpts.YamlTemplate, argsOnly.ROpts.TemplateArgs, defaults); err != nil {
return fmt.Errorf("failed to read yaml template: %v", err)
}
}
// Clear default peers if the user has specified peer options in args.
if len(argsOnly.TOpts.Peers) > 0 {
defaults.TOpts.PeerList = ""
}
if len(argsOnly.TOpts.PeerList) > 0 {
defaults.TOpts.Peers = nil
}
return nil
}
// findBestConfigFile finds the best config file to use. An empty string will be
// returned if no config file should be used.
func findBestConfigFile() string {
app := xdg.App{Name: "yab"}
// Find the best config path to use, preferring the user's config path and
// falling back to the system config path.
configPaths := []string{app.ConfigPath("defaults.ini")}
configPaths = append(configPaths, app.SystemConfigPaths("defaults.ini")...)
var configFile string
for _, path := range configPaths {
if _, err := os.Stat(path); err == nil {
configFile = path
break
}
}
return configFile
}
// parseDefaultConfigs reads defaults from ~/.config/yab/defaults.ini if they're
// available.
func parseDefaultConfigs(parser *flags.Parser) error {
configFile := findBestConfigFile()
if configFile == "" {
return nil // no defaults file was found
}
iniParser := flags.NewIniParser(parser)
if err := iniParser.ParseFile(configFile); err != nil {
return fmt.Errorf("couldn't read %v: %v", configFile, err)
}
return nil
}
func runWithOptions(opts Options, out output, logger *zap.Logger) {
if opts.TOpts.PeerList == "?" {
for _, scheme := range peerprovider.Schemes() {
out.Printf("%s\n", scheme)
}
return
}
reqReader, err := getRequestInput(opts.ROpts.RequestJSON, opts.ROpts.RequestFile)
if err != nil {
out.Fatalf("Failed while creating request reader: %v\n", err)
}
defer reqReader.Close()
headers, err := getHeaders(opts.ROpts.HeadersJSON, opts.ROpts.HeadersFile, opts.ROpts.Headers)
if err != nil {
out.Fatalf("Failed while loading headers input: %v\n", err)
}
if opts.TOpts.CallerName != "" {
if _, ok := warningCallerNames[opts.TOpts.CallerName]; ok {
// TODO: when logger is hooked up this should use the WARN level message
out.Warnf("WARNING: Deprecated caller name: %q Please change the caller name as it will be blocked in the next release.\n", opts.TOpts.CallerName)
}
if _, ok := blockedCallerNames[opts.TOpts.CallerName]; ok {
out.Fatalf("Disallowed caller name: %v", opts.TOpts.CallerName)
}
if opts.BOpts.enabled() {
out.Fatalf("Cannot override caller name when running benchmarks\n")
}
} else {
opts.TOpts.CallerName = "yab-" + os.Getenv("USER")
}
protocolScheme, peers, err := loadTransportPeers(opts.TOpts)
if err != nil {
out.Fatalf("Failed to load peers: %v\n", err)
}
opts.TOpts.PeerList = ""
opts.TOpts.Peers = peers
resolved := resolveProtocolEncoding(protocolScheme, opts.ROpts)
serializer, err := NewSerializer(opts, resolved)
if err != nil {
out.Fatalf("Failed while parsing input: %v\n", err)
}
if serializerWithClose, ok := serializer.(io.Closer); ok {
defer serializerWithClose.Close()
}
tracer, closer := getTracer(opts, out)
if closer != nil {
defer closer.Close()
}
// transport abstracts the underlying wire protocol used to make the call.
transport, err := getTransport(opts.TOpts, resolved, tracer)
if err != nil {
out.Fatalf("Failed while parsing options: %v\n", err)
}
handler := requestHandler{
out: out,
logger: logger,
opts: opts,
transport: transport,
resolved: resolved,
serializer: serializer,
body: reqReader,
headers: headers,
}
handler.handle()
}
func createJaegerTracer(opts Options, out output) (opentracing.Tracer, io.Closer) {
// yab must set the `SynchronousInitialization` flag to indicate that
// the Jaeger client must fetch debug credits synchronously. In a
// short-lived process like yab, the Jaeger client cannot afford to
// postpone the credit request for later in time.
//
// In the event that no Jaeger agent is found, the client will silently
// ignore debug spans. This behavior is no different than past
// non-throttling behavior, seeing as no Jaeger agent is available to
// receive spans (debug or otherwise). In short, the value of `err` will be
// `nil` regardless of whether or not an agent is present and/or fails to
// dispense credits to the client synchronously.
tracer, closer, err := jaeger_config.Configuration{
ServiceName: opts.TOpts.CallerName,
Throttler: &jaeger_config.ThrottlerConfig{
SynchronousInitialization: true,
},
}.NewTracer(
// SamplingPriority overrides sampler decision when below
// throttling threshold. Better to use "always false" sampling and
// only enable the span when we have not hit the throttling
// threshold.
jaeger_config.Sampler(jaeger.NewConstSampler(opts.TOpts.ForceJaegerSample)),
jaeger_config.Reporter(jaeger.NewNullReporter()),
)
if err != nil {
out.Fatalf("Failed to create Jaeger tracer: %s", err.Error())
}
return tracer, closer
}
func getTracer(opts Options, out output) (opentracing.Tracer, io.Closer) {
if !opts.TOpts.Jaeger && opts.TOpts.ForceJaegerSample {
out.Fatalf("Cannot force Jaeger sampling without enabling Jaeger")
}
if opts.TOpts.Jaeger && !opts.TOpts.NoJaeger {
return createJaegerTracer(opts, out)
}
if len(opts.ROpts.Baggage) > 0 {
out.Fatalf("To propagate baggage, you must opt-into a tracing client, i.e., --jaeger")
}
return opentracing.NoopTracer{}, nil
}
type resolvedProtocolEncoding struct {
protocol transport.Protocol
enc encoding.Encoding
}
func resolveProtocolEncoding(protocolScheme string, rOpts RequestOptions) resolvedProtocolEncoding {
enc := rOpts.detectEncoding()
switch protocolScheme {
case "tchannel":
// TChannel is only really used with Thrift, so use that as the default.
if enc == encoding.UnspecifiedEncoding {
enc = encoding.Thrift
}
return resolvedProtocolEncoding{transport.TChannel, enc}
case "grpc":
// gRPC is expected to be used with protobuf, so use that as the default.
if enc == encoding.UnspecifiedEncoding {
enc = encoding.Protobuf
}
return resolvedProtocolEncoding{transport.GRPC, enc}
case "http", "https":
if enc == encoding.UnspecifiedEncoding {
enc = encoding.JSON
}
return resolvedProtocolEncoding{transport.HTTP, enc}
}
// Try to determine a transport based on the guessed encoding.
switch enc {
case encoding.Thrift:
return resolvedProtocolEncoding{transport.TChannel, encoding.Thrift}
case encoding.Protobuf:
return resolvedProtocolEncoding{transport.GRPC, encoding.Protobuf}
case encoding.JSON:
return resolvedProtocolEncoding{transport.HTTP, encoding.JSON}
case encoding.Raw:
return resolvedProtocolEncoding{transport.HTTP, encoding.Raw}
}
// Special case --health which is for TChannel + Thrift health calls.
// This is for compatibility with tcurl.
if rOpts.Health {
return resolvedProtocolEncoding{transport.TChannel, encoding.Thrift}
}
// unknown transport and unknown encoding
return resolvedProtocolEncoding{transport.Unknown, enc}
}
// makeRequest makes a request using the given transport.
func makeRequest(t transport.Transport, request *transport.Request) (*transport.Response, error) {
return makeRequestWithTracePriority(t, request, 0)
}
func makeRequestWithTracePriority(t transport.Transport, request *transport.Request, trace uint16) (*transport.Response, error) {
ctx, cancel := tchannel.NewContext(request.Timeout)
defer cancel()
ctx = makeContextWithTrace(ctx, t, request, trace)
return t.Call(ctx, request)
}
func makeContextWithTrace(ctx context.Context, t transport.Transport, request *transport.Request, trace uint16) context.Context {
if tracer := t.Tracer(); tracer != nil {
span := tracer.StartSpan(request.Method)
opentracing_ext.SamplingPriority.Set(span, trace)
for k, v := range request.Baggage {
span = span.SetBaggageItem(k, v)
}
ctx = opentracing.ContextWithSpan(ctx, span)
}
return ctx
}
func makeInitialRequest(out output, transport transport.Transport, serializer encoding.Serializer, req *transport.Request) {
response, err := makeRequestWithTracePriority(transport, req, 1)
if err != nil {
buffer := bytes.NewBufferString(err.Error())
if errorSerializer, ok := serializer.(encoding.ProtoErrorDeserializer); ok {
details, derr := errorSerializer.ErrorDetails(err)
if derr != nil {
out.Fatalf("Failed to get protobuf error details %s", derr.Error())
}
if len(details) > 0 {
bs, merr := json.MarshalIndent(map[string]interface{}{"details": details}, "", " ")
if merr != nil {
out.Fatalf("Failed to convert protobuf error details to JSON: %v\nMap: %+v\n", merr, details)
}
buffer.WriteString("\n")
buffer.Write(bs)
buffer.WriteString("\n")
}
}
out.Fatalf("Failed while making call: %s\n", buffer.String())
}
// responseMap converts the Thrift bytes response to a map.
responseMap, err := serializer.Response(response)
if err != nil {
out.Fatalf("Failed while parsing response: %v\n", err)
}
// Print the initial output body.
outSerialized := map[string]interface{}{
"body": responseMap,
}
if len(response.Headers) > 0 {
outSerialized["headers"] = response.Headers
}
for k, v := range response.TransportFields {
outSerialized[k] = v
}
bs, err := json.MarshalIndent(outSerialized, "", " ")
if err != nil {
out.Fatalf("Failed to convert map to JSON: %v\nMap: %+v\n", err, responseMap)
}
out.Printf("%s\n\n", bs)
}
// isYabTemplate is currently very conservative, it requires a file that exists
// that ends with .yab to detect the argument as a template.
func isYabTemplate(s string) bool {
if !strings.HasSuffix(s, ".yab") {
return false
}
_, err := os.Stat(s)
return err == nil
}