-
Notifications
You must be signed in to change notification settings - Fork 39.2k
/
main.go
352 lines (316 loc) · 9.25 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
/*
Copyright 2018 The Kubernetes Authors.
Licensed 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.
*/
// do a fast type check of kubernetes code, for all platforms.
package main
import (
"flag"
"fmt"
"go/ast"
"go/build"
"go/parser"
"go/token"
"log"
"os"
"path/filepath"
"sort"
"strings"
"sync"
"sync/atomic"
"time"
"golang.org/x/crypto/ssh/terminal"
// TODO(rmmh): remove this when golang/go#23712 is fixed, and the
// fix is the current minimum Go version to build Kubernetes.
"k8s.io/kubernetes/test/typecheck/srcimporter"
"k8s.io/kubernetes/third_party/forked/golang/go/types"
)
var (
verbose = flag.Bool("verbose", false, "print more information")
cross = flag.Bool("cross", true, "build for all platforms")
platforms = flag.String("platform", "", "comma-separated list of platforms to typecheck")
timings = flag.Bool("time", false, "output times taken for each phase")
defuses = flag.Bool("defuse", false, "output defs/uses")
serial = flag.Bool("serial", false, "don't type check platforms in parallel")
isTerminal = terminal.IsTerminal(int(os.Stdout.Fd()))
logPrefix = ""
// When processed in order, windows and darwin are early to make
// interesting OS-based errors happen earlier.
crossPlatforms = []string{
"linux/amd64", "windows/386",
"darwin/amd64", "linux/arm",
"linux/386", "windows/amd64",
"linux/arm64", "linux/ppc64le",
"linux/s390x", "darwin/386",
}
)
type analyzer struct {
fset *token.FileSet // positions are relative to fset
conf types.Config
ctx build.Context
failed bool
platform string
donePaths map[string]interface{}
}
func newAnalyzer(platform string) *analyzer {
ctx := build.Default
platSplit := strings.Split(platform, "/")
ctx.GOOS, ctx.GOARCH = platSplit[0], platSplit[1]
ctx.CgoEnabled = true
a := &analyzer{
platform: platform,
fset: token.NewFileSet(),
ctx: ctx,
donePaths: make(map[string]interface{}),
}
a.conf = types.Config{
FakeImportC: true,
Error: a.handleError,
Sizes: types.SizesFor("gc", a.ctx.GOARCH),
}
a.conf.Importer = srcimporter.New(
&a.ctx, a.fset, make(map[string]*types.Package))
if *verbose {
fmt.Printf("context: %#v\n", ctx)
}
return a
}
func (a *analyzer) handleError(err error) {
if e, ok := err.(types.Error); ok {
// useful for some ignores:
// path := e.Fset.Position(e.Pos).String()
ignore := false
// TODO(rmmh): read ignores from a file, so this code can
// be Kubernetes-agnostic. Unused ignores should be treated as
// errors, to ensure coverage isn't overly broad.
if strings.Contains(e.Msg, "GetOpenAPIDefinitions") {
// TODO(rmmh): figure out why this happens.
// cmd/kube-apiserver/app/server.go:392:70
// test/integration/framework/master_utils.go:131:84
ignore = true
}
if ignore {
if *verbose {
fmt.Println("ignoring error:", err)
}
return
}
}
// TODO(rmmh): dedup errors across platforms?
fmt.Fprintf(os.Stderr, "%sERROR(%s) %s\n", logPrefix, a.platform, err)
a.failed = true
}
// collect extracts test metadata from a file.
func (a *analyzer) collect(dir string) {
if _, ok := a.donePaths[dir]; ok {
return
}
a.donePaths[dir] = nil
// Create the AST by parsing src.
fs, err := parser.ParseDir(a.fset, dir, nil, parser.AllErrors)
if err != nil {
fmt.Println(logPrefix+"ERROR(syntax)", err)
a.failed = true
return
}
if len(fs) > 1 && *verbose {
fmt.Println("multiple packages in dir:", dir)
}
for _, p := range fs {
// returns first error, but a.handleError deals with it
files := a.filterFiles(p.Files)
if *verbose {
fmt.Printf("path: %s package: %s files: ", dir, p.Name)
for _, f := range files {
fname := filepath.Base(a.fset.File(f.Pos()).Name())
fmt.Printf("%s ", fname)
}
fmt.Printf("\n")
}
a.typeCheck(dir, files)
}
}
// filterFiles restricts a list of files to only those that should be built by
// the current platform. This includes both build suffixes (_windows.go) and build
// tags ("// +build !linux" at the beginning).
func (a *analyzer) filterFiles(fs map[string]*ast.File) []*ast.File {
files := []*ast.File{}
for _, f := range fs {
fpath := a.fset.File(f.Pos()).Name()
dir, name := filepath.Split(fpath)
matches, err := a.ctx.MatchFile(dir, name)
if err != nil {
fmt.Fprintf(os.Stderr, "%sERROR reading %s: %s\n", logPrefix, fpath, err)
a.failed = true
continue
}
if matches {
files = append(files, f)
}
}
return files
}
func (a *analyzer) typeCheck(dir string, files []*ast.File) error {
info := types.Info{
Defs: make(map[*ast.Ident]types.Object),
Uses: make(map[*ast.Ident]types.Object),
}
// NOTE: this type check does a *recursive* import, but srcimporter
// doesn't do a full type check (ignores function bodies)-- this has
// some additional overhead.
//
// This means that we need to ensure that typeCheck runs on all
// code we will be compiling.
//
// TODO(rmmh): Customize our forked srcimporter to do this better.
pkg, err := a.conf.Check(dir, a.fset, files, &info)
if err != nil {
return err // type error
}
// A significant fraction of vendored code only compiles on Linux,
// but it's only imported by code that has build-guards for Linux.
// Track vendored code to type-check it in a second pass.
for _, imp := range pkg.Imports() {
if strings.HasPrefix(imp.Path(), "k8s.io/kubernetes/vendor/") {
vendorPath := imp.Path()[len("k8s.io/kubernetes/"):]
if *verbose {
fmt.Println("recursively checking vendor path:", vendorPath)
}
a.collect(vendorPath)
}
}
if *defuses {
for id, obj := range info.Defs {
fmt.Printf("%s: %q defines %v\n",
a.fset.Position(id.Pos()), id.Name, obj)
}
for id, obj := range info.Uses {
fmt.Printf("%s: %q uses %v\n",
a.fset.Position(id.Pos()), id.Name, obj)
}
}
return nil
}
type collector struct {
dirs []string
}
// handlePath walks the filesystem recursively, collecting directories,
// ignoring some unneeded directories (hidden/vendored) that are handled
// specially later.
func (c *collector) handlePath(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if info.IsDir() {
// Ignore hidden directories (.git, .cache, etc)
if len(path) > 1 && path[0] == '.' ||
// Staging code is symlinked from vendor/k8s.io, and uses import
// paths as if it were inside of vendor/. It fails typechecking
// inside of staging/, but works when typechecked as part of vendor/.
path == "staging" ||
// OS-specific vendor code tends to be imported by OS-specific
// packages. We recursively typecheck imported vendored packages for
// each OS, but don't typecheck everything for every OS.
path == "vendor" ||
path == "_output" ||
// This is a weird one. /testdata/ is *mostly* ignored by Go,
// and this translates to kubernetes/vendor not working.
// edit/record.go doesn't compile without gopkg.in/yaml.v2
// in $GOSRC/$GOROOT (both typecheck and the shell script).
path == "pkg/kubectl/cmd/testdata/edit" {
return filepath.SkipDir
}
c.dirs = append(c.dirs, path)
}
return nil
}
func main() {
flag.Parse()
args := flag.Args()
if *verbose {
*serial = true // to avoid confusing interleaved logs
}
if len(args) == 0 {
args = append(args, ".")
}
c := collector{}
for _, arg := range args {
err := filepath.Walk(arg, c.handlePath)
if err != nil {
log.Fatalf("Error walking: %v", err)
}
}
sort.Strings(c.dirs)
ps := crossPlatforms[:]
if *platforms != "" {
ps = strings.Split(*platforms, ",")
} else if !*cross {
ps = ps[:1]
}
fmt.Println("type-checking: ", strings.Join(ps, ", "))
var wg sync.WaitGroup
var processedDirs int64
var currentWork int64 // (dir_index << 8) | platform_index
statuses := make([]int, len(ps))
for i, p := range ps {
wg.Add(1)
fn := func(i int, p string) {
start := time.Now()
a := newAnalyzer(p)
for n, dir := range c.dirs {
a.collect(dir)
atomic.AddInt64(&processedDirs, 1)
atomic.StoreInt64(¤tWork, int64(n<<8|i))
}
if a.failed {
statuses[i] = 1
}
if *timings {
fmt.Printf("%s took %.1fs\n", p, time.Since(start).Seconds())
}
wg.Done()
}
if *serial {
fn(i, p)
} else {
go fn(i, p)
}
}
if isTerminal {
logPrefix = "\r" // clear status bar when printing
// Display a status bar so devs can estimate completion times.
wg.Add(1)
go func() {
total := len(ps) * len(c.dirs)
for proc := 0; ; proc = int(atomic.LoadInt64(&processedDirs)) {
work := atomic.LoadInt64(¤tWork)
dir := c.dirs[work>>8]
platform := ps[work&0xFF]
if len(dir) > 80 {
dir = dir[:80]
}
fmt.Printf("\r%d/%d \033[2m%-13s\033[0m %-80s", proc, total, platform, dir)
if proc == total {
fmt.Println()
break
}
time.Sleep(50 * time.Millisecond)
}
wg.Done()
}()
}
wg.Wait()
for _, status := range statuses {
if status != 0 {
os.Exit(status)
}
}
}