forked from apache/beam
/
vet.go
598 lines (546 loc) · 17.3 KB
/
vet.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
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Package vet is a Beam runner that "runs" a pipeline by producing
// generated code to avoid symbol table lookups and reflection in pipeline
// execution.
//
// This runner isn't necessarily intended to be run by itself. Other runners
// can use this as a sanity check on whether a given pipeline avoids known
// performance bottlenecks.
//
// TODO(BEAM-7374): Add usage documentation.
package vet
import (
"bytes"
"context"
"fmt"
"reflect"
"strings"
"unicode"
"unicode/utf8"
"github.com/apache/beam/sdks/go/pkg/beam/util/shimx"
"github.com/apache/beam/sdks/go/pkg/beam"
"github.com/apache/beam/sdks/go/pkg/beam/core/funcx"
"github.com/apache/beam/sdks/go/pkg/beam/core/graph"
"github.com/apache/beam/sdks/go/pkg/beam/core/runtime"
"github.com/apache/beam/sdks/go/pkg/beam/core/runtime/exec"
"github.com/apache/beam/sdks/go/pkg/beam/core/typex"
"github.com/apache/beam/sdks/go/pkg/beam/core/util/reflectx"
"github.com/apache/beam/sdks/go/pkg/beam/internal/errors"
)
func init() {
beam.RegisterRunner("vet", Execute)
}
// We want clear failures when looking up symbols so we can tell if something has been
// registered properly or not.
type disabledResolver bool
func (p disabledResolver) Sym2Addr(name string) (uintptr, error) {
return 0, errors.Errorf("%v not found. Use runtime.RegisterFunction in unit tests", name)
}
// Execute evaluates the pipeline on whether it can run without reflection.
func Execute(ctx context.Context, p *beam.Pipeline) error {
e, err := Evaluate(ctx, p)
if err != nil {
return errors.WithContext(err, "validating pipeline with vet runner")
}
if !e.Performant() {
e.summary()
e.Generate("main")
e.diag("*/\n")
err := errors.Errorf("pipeline is not performant, see diagnostic summary:\n%s\n%s", string(e.d.Bytes()), string(e.Bytes()))
err = errors.WithContext(err, "validating pipeline with vet runner")
return errors.SetTopLevelMsg(err, "pipeline is not performant")
}
// Pipeline nas no further tasks.
return nil
}
// Evaluate returns an object that can generate necessary shims and inits.
func Evaluate(_ context.Context, p *beam.Pipeline) (*Eval, error) {
// Disable the resolver so we can see functions that are that are already registered.
r := runtime.Resolver
runtime.Resolver = disabledResolver(false)
// Reinstate the resolver when we're through.
defer func() { runtime.Resolver = r }()
edges, _, err := p.Build()
if err != nil {
return nil, errors.New("can't get data to generate")
}
e := newEval()
e.diag("/**\n")
e.extractFromMultiEdges(edges)
return e, nil
}
func newEval() *Eval {
return &Eval{
functions: make(map[string]*funcx.Fn),
types: make(map[string]reflect.Type),
funcs: make(map[string]reflect.Type),
emits: make(map[string]reflect.Type),
iters: make(map[string]reflect.Type),
imports: make(map[string]struct{}),
allExported: true,
}
}
// Eval contains and uniquifies the cache of types and things that need to be generated.
type Eval struct {
// d is a buffer for the diagnostic information produced when evaluating the pipeline.
// w is the primary output buffer.
d, w bytes.Buffer
// Register and uniquify the needed shims for each kind.
// Functions to Register
functions map[string]*funcx.Fn
// Types to Register (structs, essentially)
types map[string]reflect.Type
// FuncShims needed
funcs map[string]reflect.Type
// Emitter Shims needed
emits map[string]reflect.Type
// Iterator Shims needed
iters map[string]reflect.Type
// list of packages we need to import.
imports map[string]struct{}
allExported bool // Marks if all ptransforms are exported and available in main.
}
// extractFromMultiEdges audits the given pipeline edges so we can determine if
// this pipeline will run without reflection.
func (e *Eval) extractFromMultiEdges(edges []*graph.MultiEdge) {
e.diag("PTransform Audit:\n")
for _, edge := range edges {
switch edge.Op {
case graph.ParDo:
// Gets the ParDo's identifier
e.diagf("pardo %s", edge.Name())
e.extractGraphFn((*graph.Fn)(edge.DoFn))
case graph.Combine:
e.diagf("combine %s", edge.Name())
e.extractGraphFn((*graph.Fn)(edge.CombineFn))
default:
continue
}
e.diag("\n")
}
}
// Performant returns whether this pipeline needs additional registrations
// to avoid reflection, or symbol lookups at runtime.
func (e *Eval) Performant() bool {
return !e.RequiresRegistrations() && !e.UsesDefaultReflectionShims()
}
// RequiresRegistrations returns if there are any types or functions that require
// registrations.
func (e *Eval) RequiresRegistrations() bool {
return (len(e.functions) + len(e.types)) > 0
}
// UsesDefaultReflectionShims returns whether the default reflection shims are going
// to be used by the pipeline.
func (e *Eval) UsesDefaultReflectionShims() bool {
return (len(e.funcs) + len(e.emits) + len(e.iters)) > 0
}
// AllExported returns whether all values in the pipeline are exported,
// and thus it may be possible to patch the pipeline's package with
// generated shims.
// Using exported vs unexported identifiers does not affect pipeline performance
// but does matter on if the pipeline package can do anything about it.
func (e *Eval) AllExported() bool {
return e.allExported
}
func (e *Eval) summary() {
e.diag("\n")
e.diag("Summary\n")
e.diagf("All exported?: %v\n", e.AllExported())
e.diagf("%d\t Imports\n", len(e.imports))
e.diagf("%d\t Functions\n", len(e.functions))
e.diagf("%d\t Types\n", len(e.types))
e.diagf("%d\t Shims\n", len(e.funcs))
e.diagf("%d\t Emits\n", len(e.emits))
e.diagf("%d\t Inputs\n", len(e.iters))
if e.Performant() {
e.diag("Pipeline is performant!\n")
} else {
e.diag("Pipeline is not performant:\n")
if e.RequiresRegistrations() {
e.diag("\trequires additional type or function registration\n")
}
if e.UsesDefaultReflectionShims() {
e.diag("\trequires additional shim generation\n")
}
if e.AllExported() {
e.diag("\tGood News! All identifiers are exported; the pipeline's package can be patched with generated output.\n")
}
}
}
// NameType turns a reflect.Type into a string based on its name.
// It prefixes Emit or Iter if the function satisfies the constraints of those types.
func NameType(t reflect.Type) string {
if emt, ok := makeEmitter(t); ok {
return "Emit" + emt.Name
}
if ipt, ok := makeInput(t); ok {
return "Iter" + ipt.Name
}
return shimx.Name(t.String())
}
// Generate produces a go file under the given package.
func (e *Eval) Generate(packageName string) {
// Here's where we shove everything into the Top template type.
// Need to swap in typex.* for beam.* where appropriate.
e.diag("Diagnostic output pre-amble for the code generator\n")
e.diag("Functions\n")
var functions []string
for fn, t := range e.functions {
e.diagf("%s, %v\n", fn, t)
n := strings.Split(fn, ".")
// If this is the main package, we don't need the package qualifier
if n[0] == "main" {
functions = append(functions, n[1])
} else {
functions = append(functions, fn)
}
}
e.diag("Types\n")
var types []string
for fn, t := range e.types {
e.diagf("%s, %v\n", fn, t)
n := strings.Split(fn, ".")
// If this is the main package, we don't need the package qualifier
if n[0] == "main" {
types = append(types, n[1])
} else {
types = append(types, fn)
}
}
e.diag("Shims\n")
var shims []shimx.Func
for fn, t := range e.funcs {
e.diagf("%s, %v\n", fn, t)
shim := shimx.Func{Type: t.String()}
var inNames []string
for i := 0; i < t.NumIn(); i++ {
s := t.In(i)
shim.In = append(shim.In, s.String())
inNames = append(inNames, NameType(s))
}
var outNames []string
for i := 0; i < t.NumOut(); i++ {
s := t.Out(i)
shim.Out = append(shim.Out, s.String())
outNames = append(outNames, NameType(s))
}
shim.Name = shimx.FuncName(inNames, outNames)
shims = append(shims, shim)
}
e.diag("Emitters\n")
var emitters []shimx.Emitter
for k, t := range e.emits {
e.diagf("%s, %v\n", k, t)
emt, ok := makeEmitter(t)
if !ok {
panic(fmt.Sprintf("%v is not an emit, but we expected it to be one.", t))
}
emitters = append(emitters, emt)
}
e.diag("Iterators \n")
var inputs []shimx.Input
for ipt, t := range e.iters {
e.diagf("%s, %v\n", ipt, t)
itr, ok := makeInput(t)
if !ok {
panic(fmt.Sprintf("%v is not an emit, but we expected it to be one.", t))
}
inputs = append(inputs, itr)
}
var imports []string
for k := range e.imports {
if k == "" {
continue
}
imports = append(imports, k)
}
top := shimx.Top{
Package: packageName,
Imports: imports,
Functions: functions,
Types: types,
Shims: shims,
Emitters: emitters,
Inputs: inputs,
}
shimx.File(&e.w, &top)
}
func makeEmitter(t reflect.Type) (shimx.Emitter, bool) {
types, isEmit := funcx.UnfoldEmit(t)
if !isEmit {
return shimx.Emitter{}, false
}
emt := shimx.Emitter{Type: t.String()}
switch len(types) {
case 1:
emt.Time = false
emt.Val = types[0].String()
case 2:
if types[0] == typex.EventTimeType {
emt.Time = true
} else {
emt.Key = types[0].String()
}
emt.Val = types[1].String()
case 3:
// If there's 3, the first one must be typex.EvalentTime.
emt.Time = true
emt.Key = types[1].String()
emt.Val = types[2].String()
}
if emt.Time {
emt.Name = fmt.Sprintf("ET%s%s", shimx.Name(emt.Key), shimx.Name(emt.Val))
} else {
emt.Name = fmt.Sprintf("%s%s", shimx.Name(emt.Key), shimx.Name(emt.Val))
}
return emt, true
}
func makeInput(t reflect.Type) (shimx.Input, bool) {
itr := shimx.Input{Type: t.String()}
types, isIter := funcx.UnfoldIter(t)
if !isIter {
return shimx.Input{}, false
}
switch len(types) {
case 1:
itr.Time = false
itr.Val = types[0].String()
case 2:
if types[0] == typex.EventTimeType {
itr.Time = true
} else {
itr.Key = types[0].String()
}
itr.Val = types[1].String()
case 3:
// If there's 3, the first one must be typex.EventTime.
itr.Time = true
itr.Key = types[1].String()
itr.Val = types[2].String()
}
if itr.Time {
itr.Name = fmt.Sprintf("ET%s%s", shimx.Name(itr.Key), shimx.Name(itr.Val))
} else {
itr.Name = fmt.Sprintf("%s%s", shimx.Name(itr.Key), shimx.Name(itr.Val))
}
return itr, true
}
// needFunction marks the function itself needs to be registered
func (e *Eval) needFunction(fn *funcx.Fn) {
k := fn.Fn.Name()
if _, ok := e.functions[k]; ok {
e.diag(" FUNCTION_COVERED")
} else {
e.diag(" NEED_FUNCTION") // Needs a RegisterFunction
e.functions[k] = fn
e.needImport(fn.Fn.Name())
}
}
// needImport registers the given identifier's import for including in generation.
func (e *Eval) needImport(p string) {
// If this is a reflect.methodValueCall, this is covered by the type
// check already, so we don't need to do anything.
if p == "reflect.methodValueCall" {
return
}
// Split at last '.' to get full package name and identifier name.
splitInd := strings.LastIndexByte(p, '.')
pp := p[:splitInd]
// If it's ad-hoc, or in main we can't/won't import it.
if pp == "main" || pp == "" {
return
}
// Check if the identifier is exported
r, _ := utf8.DecodeRuneInString(p[splitInd+1:])
if !unicode.IsUpper(r) {
e.allExported = false
return
}
e.imports[pp] = struct{}{}
e.diagf("\n%s\n", pp)
}
// needShim marks the function's type signature as needing to be specialized.
func (e *Eval) needShim(fn *funcx.Fn) {
k := fn.Fn.Type().String()
if _, ok := e.funcs[k]; ok {
e.diag(" SHIM_COVERED")
} else {
e.diag(" NEED_SHIM") // Needs a RegisterFunc
e.funcs[k] = fn.Fn.Type()
e.needImport(fn.Fn.Name())
}
}
// needType marks the struct's type signature as needing to be specialized.
func (e *Eval) needType(k string, rt reflect.Type) {
if _, ok := e.types[k]; ok {
e.diag(" OK")
} else {
e.diag(" NEED_TYPE") // Needs a RegisterType
e.types[k] = rt
e.needImport(k)
}
}
// needEmit marks the emit parameter as needed specialization
func (e *Eval) needEmit(rt reflect.Type) {
k := fmt.Sprintf("%v", rt)
if exec.IsEmitterRegistered(rt) {
e.diag(" OK")
return
}
if _, ok := e.emits[k]; ok {
e.diag(" EMIT_COVERED")
} else {
e.diagf(" NEED_EMIT[%v]", rt) // Needs a RegisterEmit
e.emits[k] = rt
}
}
// needInput marks the iterator parameter as needed specialization
func (e *Eval) needInput(rt reflect.Type) {
k := fmt.Sprintf("%v", rt)
if exec.IsInputRegistered(rt) {
e.diag(" OK")
return
}
if _, ok := e.iters[k]; ok {
e.diag(" INPUT_COVERED")
} else {
e.diagf(" NEED_INPUT[%v]", rt) // Needs a RegisterInput
e.iters[k] = rt
}
}
// diag invokes fmt.Fprint on the diagnostic buffer.
func (e *Eval) diag(s string) {
fmt.Fprint(&e.d, s)
}
// diag invokes fmt.Fprintf on the diagnostic buffer.
func (e *Eval) diagf(f string, args ...interface{}) {
fmt.Fprintf(&e.d, f, args...)
}
// Print invokes fmt.Fprint on the Eval buffer.
func (e *Eval) Print(s string) {
fmt.Fprint(&e.w, s)
}
// Printf invokes fmt.Fprintf on the Eval buffer.
func (e *Eval) Printf(f string, args ...interface{}) {
fmt.Fprintf(&e.w, f, args...)
}
// Bytes returns the Eval buffer's bytes for file writing.
func (e *Eval) Bytes() []byte {
return e.w.Bytes()
}
// We need to take graph.Fns (which can be created from interface{} from graph.NewFn)
// and convert them to all needed function caller signatures,
// and emitters.
//
// The type assertion shim Funcs need to be registered with reflectx.RegisterFunc
// Emitters need to be registered with exec.RegisterEmitter
// Iterators with exec.RegisterInput
// The types need to be registered with beam.RegisterType
// The user functions need to be registered with beam.RegisterFunction
//
// Registrations are all on the concrete element type, rather than the
// pointer type.
// extractGraphFn does the analysis of the function and determines what things need generating.
// A single line is used, unless it's a struct, at which point one line per implemented method
// is used.
func (e *Eval) extractGraphFn(fn *graph.Fn) {
if fn.DynFn != nil {
// TODO(BEAM-7375) handle dynamics if necessary (probably not since it's got general function handling)
e.diag(" dynamic function")
return
}
if fn.Recv != nil {
e.diagf(" struct[[%T]]", fn.Recv)
rt := reflectx.SkipPtr(reflect.TypeOf(fn.Recv)) // We need the value not the pointer that's used.
if tk, ok := runtime.TypeKey(rt); ok {
if t, found := runtime.LookupType(tk); !found {
e.needType(tk, rt)
} else {
e.diagf(" FOUND %v", t) // Doesn't need a RegisterType
}
} else {
e.diagf(" CANT REGISTER %v %v %v", rt, rt.PkgPath(), rt.Name())
}
e.extractFromDoFn((*graph.DoFn)(fn))
e.extractFromCombineFn((*graph.CombineFn)(fn))
}
if fn.Fn != nil {
// This goes here since methods don't need registering. That's handled by the type.
f := fn.Fn.Fn
if _, err := runtime.ResolveFunction(f.Name(), f.Type()); err != nil {
e.needFunction(fn.Fn) // Need a RegisterFunction
}
e.extractFuncxFn(fn.Fn)
}
}
type mthd struct {
m func() *funcx.Fn
name string
}
func (e *Eval) extractFromCombineFn(cmbfn *graph.CombineFn) {
methods := []mthd{
{cmbfn.SetupFn, "SetupFn"},
{cmbfn.CreateAccumulatorFn, "CreateAccumulatorFn"},
{cmbfn.AddInputFn, "AddInputFn"},
{cmbfn.MergeAccumulatorsFn, "MergeAccumulatorsFn"},
{cmbfn.ExtractOutputFn, "ExtractOutputFn"},
{cmbfn.CompactFn, "CompactFn"},
{cmbfn.TeardownFn, "TeardownFn"},
}
e.extractMethods(methods)
}
func (e *Eval) extractFromDoFn(dofn *graph.DoFn) {
methods := []mthd{
{dofn.SetupFn, "SetupFn"},
{dofn.StartBundleFn, "StartBundleFn"},
{dofn.ProcessElementFn, "ProcessElementFn"},
{dofn.FinishBundleFn, "FinishBundleFn"},
{dofn.TeardownFn, "TeardownFn"},
}
e.extractMethods(methods)
}
func (e *Eval) extractMethods(methods []mthd) {
for _, m := range methods {
if mfn := m.m(); mfn != nil {
e.diag("\n\t- ")
e.diag(m.name)
e.extractFuncxFn(mfn)
}
}
}
// extractFuncxFn writes everything to the same line marking things as registered or not as needed.
func (e *Eval) extractFuncxFn(fn *funcx.Fn) {
t := fn.Fn.Type()
e.diagf(" function[[%v]]", t)
// We don't have access to the maps directly, so we can sanity check if we need
// a shim by checking against this type.
if shim := fmt.Sprintf("%T", fn.Fn); shim == "*reflectx.reflectFunc" {
e.needShim(fn) // Need a generated Shim and RegisterFunc
}
// Need to extract emitter types and iterator types for specialization.
// We're "stuck" always generating these all the time, since we
// can't tell what's already registered at this level.
for _, p := range fn.Param {
switch p.Kind {
case funcx.FnEmit:
e.needEmit(p.T) // Need a generated emitter and RegisterEmitter
case funcx.FnIter:
e.needInput(p.T) // Need a generated iter and RegisterInput
case funcx.FnReIter:
e.needInput(p.T) // ???? Might be unnecessary?
}
}
}