aboutsummaryrefslogtreecommitdiff
path: root/tests/integration/reproducibility/reproducibility_test.go
blob: 2e9bc5914471c61a90839212ef891308fb134521 (plain)
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
// Copyright 2019 The Bazel Authors. All rights reserved.
//
// 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.

package reproducibility_test

import (
	"bytes"
	"crypto/sha256"
	"encoding/hex"
	"errors"
	"fmt"
	"io"
	"io/ioutil"
	"os"
	"path/filepath"
	"strings"
	"sync"
	"testing"

	"github.com/bazelbuild/rules_go/go/tools/bazel_testing"
)

func TestMain(m *testing.M) {
	bazel_testing.TestMain(m, bazel_testing.Args{
		Main: `
-- BUILD.bazel --
load("@io_bazel_rules_go//go:def.bzl", "go_binary", "go_library")

go_library(
	name = "empty_lib",
	srcs = [],
	importpath = "empty_lib",
)

go_binary(
    name = "hello",
    srcs = ["hello.go"],
)

go_binary(
    name = "adder",
    srcs = [
        "adder_main.go",
        "adder.go",
        "add.c",
        "add.cpp",
        "add.h",
    ],
    cgo = True,
    linkmode = "c-archive",
)

-- hello.go --
package main

import "fmt"

func main() {
	fmt.Println("hello")
}

-- add.h --
#ifdef __cplusplus
extern "C" {
#endif

int add_c(int a, int b);
int add_cpp(int a, int b);

#ifdef __cplusplus
}
#endif

-- add.c --
#include "add.h"
#include "_cgo_export.h"

int add_c(int a, int b) { return add(a, b); }

-- add.cpp --
#include "add.h"
#include "_cgo_export.h"

int add_cpp(int a, int b) { return add(a, b); }

-- adder.go --
package main

/*
#include "add.h"
*/
import "C"

func AddC(a, b int32) int32 {
	return int32(C.add_c(C.int(a), C.int(b)))
}

func AddCPP(a, b int32) int32 {
	return int32(C.add_cpp(C.int(a), C.int(b)))
}

//export add
func add(a, b int32) int32 {
	return a + b
}

-- adder_main.go --
package main

import "fmt"

func main() {
	// Depend on some stdlib function.
	fmt.Println("In C, 2 + 2 = ", AddC(2, 2))
	fmt.Println("In C++, 2 + 2 = ", AddCPP(2, 2))
}

`,
	})
}

func Test(t *testing.T) {
	wd, err := os.Getwd()
	if err != nil {
		t.Fatal(err)
	}

	// Copy the workspace to three other directories.
	// We'll run bazel commands in those directories, not here. We clean those
	// workspaces at the end of the test, but we don't want to clean this
	// directory because it's shared with other tests.
	dirs := []string{wd + "0", wd + "1", wd + "2"}
	for _, dir := range dirs {
		if err := copyTree(dir, wd); err != nil {
			t.Fatal(err)
		}
		defer func() {
			cmd := bazel_testing.BazelCmd("clean", "--expunge")
			cmd.Dir = dir
			cmd.Run()
			os.RemoveAll(dir)
		}()
	}
	defer func() {
		var wg sync.WaitGroup
		wg.Add(len(dirs))
		for _, dir := range dirs {
			go func(dir string) {
				defer wg.Done()
				cmd := bazel_testing.BazelCmd("clean", "--expunge")
				cmd.Dir = dir
				cmd.Run()
				os.RemoveAll(dir)
			}(dir)
		}
		wg.Wait()
	}()

	// Change the source file in dir2. We should detect a difference here.
	hello2Path := filepath.Join(dirs[2], "hello.go")
	hello2File, err := os.OpenFile(hello2Path, os.O_WRONLY|os.O_APPEND, 0666)
	if err != nil {
		t.Fatal(err)
	}
	defer hello2File.Close()
	if _, err := hello2File.WriteString(`func init() { fmt.Println("init") }`); err != nil {
		t.Fatal(err)
	}
	if err := hello2File.Close(); err != nil {
		t.Fatal(err)
	}

	// Build the targets in each directory.
	var wg sync.WaitGroup
	wg.Add(len(dirs))
	for _, dir := range dirs {
		go func(dir string) {
			defer wg.Done()
			cmd := bazel_testing.BazelCmd("build",
				"//:all",
				"@io_bazel_rules_go//go/tools/builders:go_path",
				"@go_sdk//:builder",
			)
			cmd.Dir = dir
			if err := cmd.Run(); err != nil {
				t.Fatalf("in %s, error running %s: %v", dir, strings.Join(cmd.Args, " "), err)
			}
		}(dir)
	}
	wg.Wait()

	// Hash files in each bazel-bin directory.
	dirHashes := make([][]fileHash, len(dirs))
	errs := make([]error, len(dirs))
	wg.Add(len(dirs))
	for i := range dirs {
		go func(i int) {
			defer wg.Done()
			dirHashes[i], errs[i] = hashFiles(filepath.Join(dirs[i], "bazel-bin"))
		}(i)
	}
	wg.Wait()
	for _, err := range errs {
		if err != nil {
			t.Fatal(err)
		}
	}

	// Compare dir0 and dir1. They should be identical.
	if err := compareHashes(dirHashes[0], dirHashes[1]); err != nil {
		t.Fatal(err)
	}

	// Compare dir0 and dir2. They should be different.
	if err := compareHashes(dirHashes[0], dirHashes[2]); err == nil {
		t.Fatalf("dir0 and dir2 are the same)", len(dirHashes[0]))
	}

	// Check that the go_sdk path doesn't appear in the builder binary. This path is different
	// nominally different per workspace (but in these tests, the go_sdk paths are all set to the same
	// path in WORKSPACE) -- so if this path is in the builder binary, then builds between workspaces
	// would be partially non cacheable.
	builder_file, err := os.Open(filepath.Join(dirs[0], "bazel-bin", "external", "go_sdk", "builder"))
	if err != nil {
		t.Fatal(err)
	}
	defer builder_file.Close()
	builder_data, err := ioutil.ReadAll(builder_file)
	if err != nil {
		t.Fatal(err)
	}
	if bytes.Index(builder_data, []byte("go_sdk")) != -1 {
		t.Fatalf("Found go_sdk path in builder binary, builder tool won't be reproducible")
	}
}

func copyTree(dstRoot, srcRoot string) error {
	return filepath.Walk(srcRoot, func(srcPath string, info os.FileInfo, err error) error {
		if err != nil {
			return err
		}

		rel, err := filepath.Rel(srcRoot, srcPath)
		if err != nil {
			return err
		}
		var dstPath string
		if rel == "." {
			dstPath = dstRoot
		} else {
			dstPath = filepath.Join(dstRoot, rel)
		}

		if info.IsDir() {
			return os.Mkdir(dstPath, 0777)
		}
		r, err := os.Open(srcPath)
		if err != nil {
			return nil
		}
		defer r.Close()
		w, err := os.Create(dstPath)
		if err != nil {
			return err
		}
		defer w.Close()
		if _, err := io.Copy(w, r); err != nil {
			return err
		}
		return w.Close()
	})
}

func compareHashes(lhs, rhs []fileHash) error {
	buf := &bytes.Buffer{}
	for li, ri := 0, 0; li < len(lhs) || ri < len(rhs); {
		if li < len(lhs) && (ri == len(rhs) || lhs[li].rel < rhs[ri].rel) {
			fmt.Fprintf(buf, "%s only in left\n", lhs[li].rel)
			li++
			continue
		}
		if ri < len(rhs) && (li == len(lhs) || rhs[ri].rel < lhs[li].rel) {
			fmt.Fprintf(buf, "%s only in right\n", rhs[ri].rel)
			ri++
			continue
		}
		if lhs[li].hash != rhs[ri].hash {
			fmt.Fprintf(buf, "%s is different: %s %s\n", lhs[li].rel, lhs[li].hash, rhs[ri].hash)
		}
		li++
		ri++
	}
	if errStr := buf.String(); errStr != "" {
		return errors.New(errStr)
	}
	return nil
}

type fileHash struct {
	rel, hash string
}

func hashFiles(dir string) ([]fileHash, error) {
	// Follow top-level symbolic link
	root := dir
	for {
		info, err := os.Lstat(root)
		if err != nil {
			return nil, err
		}
		if info.Mode()&os.ModeType != os.ModeSymlink {
			break
		}
		rel, err := os.Readlink(root)
		if err != nil {
			return nil, err
		}
		if filepath.IsAbs(rel) {
			root = rel
		} else {
			root = filepath.Join(filepath.Dir(dir), rel)
		}
	}

	// Gather hashes of files within the tree.
	var hashes []fileHash
	var sum [16]byte
	err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
		if err != nil {
			return err
		}

		// Skip directories and symbolic links to directories.
		if info.Mode()&os.ModeType == os.ModeSymlink {
			info, err = os.Stat(path)
			if err != nil {
				return err
			}
		}
		if info.IsDir() {
			return nil
		}

		// Skip MANIFEST, runfiles_manifest, and .lo files.
		// TODO(jayconrod): find out why .lo files are not reproducible.
		base := filepath.Base(path)
		if base == "MANIFEST" || strings.HasSuffix(base, ".runfiles_manifest") || strings.HasSuffix(base, ".lo") {
			return nil
		}

		rel, err := filepath.Rel(root, path)
		if err != nil {
			return err
		}

		r, err := os.Open(path)
		if err != nil {
			return err
		}
		defer r.Close()
		h := sha256.New()
		if _, err := io.Copy(h, r); err != nil {
			return err
		}
		hashes = append(hashes, fileHash{rel: rel, hash: hex.EncodeToString(h.Sum(sum[:0]))})

		return nil
	})
	if err != nil {
		return nil, err
	}
	return hashes, nil
}