build.go 12.5 KB
Newer Older
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
// Binary ci-build locates all Debian-packaged Go packages in a GOPATH, builds
// them, and persists the result. This is used for continuous integration on
// salsa in combination with an overlay for before/after comparisons.
package main

import (
	"encoding/json"
	"flag"
	"fmt"
	"hash/fnv"
	"io/ioutil"
	"log"
	"os"
	"os/exec"
	"path/filepath"
	"regexp"
	"strings"
	"sync"
	"syscall"

	"pault.ag/go/debian/control"
)

var (
	dryRun = flag.Bool("dry_run",
		false,
		"Print go tool command lines instead of actually running commands (for development)")

	parallelExamine = flag.Int("parallel_examine",
		20,
		"Parallelism level for examining packages (finding the Go packages to build)")

	parallelBuild = flag.Int("parallel_build",
		8,
		"Parallelism level for building packages")

	unprivilegedUid = flag.Int("unprivileged_uid",
		1000,
		"system uid (id -u) of an unprivileged user to drop privileges to after setting up the build environment")

	unprivilegedGid = flag.Int("unprivileged_gid",
		1000,
		"system gid (id -g) of an unprivileged user to drop privileges to after setting up the build environment")

	exemptionsPath = flag.String("exemptions",
		"",
		"Path to an exemptions .json file") // TODO: describe format

	examineCache = flag.String("examine_cache",
		"/cache/examine",
		"Path in which to store JSON cache files with Debian package examination results (build targets, etc.)")

	// TODO(stapelberg): remove once Debian is on go1.10
	go19 = flag.Bool("go19",
		false,
		"/usr/bin/go is go 1.9 (prevents -vet=off)")
)

func goEnv() []string {
	return []string{
		"GOPATH=" + os.Getenv("GOPATH"),
		"GOCACHE=" + os.Getenv("GOCACHE"),
		"PATH=/usr/bin:/bin:/usr/games:/usr/sbin:/sbin",
	}
}

func isDir(err error) bool {
	if pe, ok := err.(*os.PathError); ok {
		return pe.Err == syscall.EISDIR
	}
	return false
}

// goImportPath returns the machine-readable XS-Go-Import-Path from the
// debian/control file located at controlPath.
func goImportPath(s control.SourceParagraph) string {
	for key, val := range s.Values {
		if strings.ToLower(key) == "xs-go-import-path" {
			paths := strings.Split(val, ",")
			return strings.TrimSuffix(paths[0], "/")
		}
	}
	return ""
}

var varRe = regexp.MustCompile(`^([^ ]+) :?= (.*)$`)

func buildTargets(packagingDir, importPath string) ([]string, bool, bool, error) {
	disableTests := false
	// Read DH_GO* variables from debian/rules Makefile:
	mk := exec.Command("make", "-Rrnpf", "debian/rules", "dh")
	mk.Dir = packagingDir
	mk.Env = []string{"LC_ALL=C"}
	mk.Stderr = os.Stderr
	out, err := mk.Output()
	if err != nil {
		return nil, false, false, err
	}
	vars := make(map[string]string)
	vars["DH_GOPKG"] = ""
	vars["DH_GOLANG_BUILDPKG"] = ""
	vars["DH_GOLANG_EXCLUDES"] = ""
	vars["DH_GOLANG_GO_GENERATE"] = ""
	vars["DEB_BUILD_OPTIONS"] = ""
	for _, line := range strings.Split(strings.TrimSpace(string(out)), "\n") {
		if !strings.HasPrefix(line, "DH_GO") &&
			!strings.HasPrefix(line, "override_dh_auto_test:") &&
			!strings.HasPrefix(line, "DEB_BUILD_OPTIONS") {
			continue // optimization: skip variables we are not interested in
		}
		if strings.HasPrefix(line, "override_dh_auto_test:") {
			disableTests = true
		}
		matches := varRe.FindStringSubmatch(line)
		if matches == nil {
			continue
		}
		if _, ok := vars[matches[1]]; !ok {
			continue // variable not in map: not interested
		}
		vars[matches[1]] = matches[2]
	}

	// Figure out what to build, just like dh-golang:
	gopkg := vars["DH_GOPKG"]
	if gopkg == "" {
		gopkg = importPath
	}
	buildpkg := vars["DH_GOLANG_BUILDPKG"]
	if buildpkg == "" {
		buildpkg = gopkg + "/..."
	}
	generate := vars["DH_GOLANG_GO_GENERATE"] == "1"
	excludes := vars["DH_GOLANG_EXCLUDES"]
	if excludes == "" {
		// TODO(speed): cannot return early because of (e.g.?)
		// golang-github-sjoerdsimons-ostree-go, which contains packages that
		// cannot be loaded (empty files). The “go list” step will filter those
		// out.
		// return []string{buildpkg}, generate, disableTests, nil
	}

	if vars["DEB_BUILD_OPTIONS"] == "nocheck" {
		disableTests = true
	}

	// TODO: put that go list call into dh-golang, too, then remove the
	// workaround from gogoprotobuf
	list := exec.Command("go", "list", "-f", `{{if or (ne (join .GoFiles "") "") (ne (join .CgoFiles "") "")}}{{.ImportPath}}{{end}}`, buildpkg)
	list.Env = goEnv()
	list.Stderr = os.Stderr
	target, err := list.Output()
	if err != nil {
		return nil, false, false, err
	}
	targets := strings.Split(strings.TrimSpace(string(target)), "\n")

	if excludes == "" {
		return targets, generate, disableTests, nil
	}

	for _, pattern := range strings.Split(excludes, " ") {
		// TODO(correctness): use PCRE to better approximate Perl regexps
		re, err := regexp.Compile(pattern)
		if err != nil {
			log.Printf("invalid DH_GOLANG_EXCLUDES regexp %q: %v", pattern, err)
			continue
		}
		var filtered []string
		for _, t := range targets {
			if re.MatchString(t) {
				continue
			}
			filtered = append(filtered, t)
		}
		targets = filtered
	}

	return targets, generate, disableTests, nil
}

type pkg struct {
	Source       string   `json:"source,omitempty"`     // e.g. golang-golang-x-oauth2
	Dir          string   `json:"dir,omitempty"`        // e.g. /srv/gopath/src/xi2.org/x/xz
	ImportPath   string   `json:"importpath,omitempty"` // e.g. xi2.org/x/xz
	Targets      []string `json:"targets,omitempty"`    // e.g. xi2.org/x/xz/...
	Generate     bool     `json:"generate,omitempty"`   // call go generate on targets before building?
	DisableTests bool     `json:"disabletests,omitempty"`
}

func (p *pkg) cachePath() (string, error) {
	b, err := ioutil.ReadFile(filepath.Join(p.Dir, "debian", ".hashes"))
	if err != nil {
		return "", err
	}
	h := fnv.New32()
	h.Write(b)
	cacheKey := fmt.Sprintf("%x", h.Sum(nil))
	return filepath.Join(*examineCache, cacheKey[:2], cacheKey+".json"), nil
}

func (p *pkg) loadCached(cachePath string) (bool, error) {
	b, err := ioutil.ReadFile(cachePath)
	if err != nil {
		if os.IsNotExist(err) {
			return false, nil
		}
		return false, err
	}
	if err := json.Unmarshal(b, p); err != nil {
		return false, err
	}
	return true, nil
}

func (p *pkg) storeCache(cachePath string) error {
	b, err := json.Marshal(&pkg{
		Targets:      p.Targets,
		Generate:     p.Generate,
		DisableTests: p.DisableTests,
	})
	if err != nil {
		return err
	}
	if err := os.MkdirAll(filepath.Dir(cachePath), 0755); err != nil {
		return err
	}
	return ioutil.WriteFile(cachePath, b, 0644)
}

func (p *pkg) examine() error {
	cachePath, err := p.cachePath()
	if err != nil {
		return err
	}

	cached, err := p.loadCached(cachePath)
	if err != nil {
		return err
	}
	if cached {
		return nil
	}

	p.Targets, p.Generate, p.DisableTests, err = buildTargets(p.Dir, p.ImportPath)
	if err != nil {
		return err
	}

	if err := p.storeCache(cachePath); err != nil {
		log.Printf("could not persist examine cache entry %s: %v", cachePath, err)
	}

	return nil
}

type exemptions struct {
	// Exemptions maps from importpath (e.g. xi2.org/x/xz) to bug URL
	// (e.g. https://bugs.debian.org/123456, or https://github.com/foo/bar/issues/3).
	Exemptions map[string]string `json:"exemptions"`
}

func locate() ([]pkg, error) {
	var ex exemptions
	if *exemptionsPath != "" {
		b, err := ioutil.ReadFile(*exemptionsPath)
		if err != nil {
			return nil, err
		}
		if err := json.Unmarshal(b, &ex); err != nil {
			return nil, err
		}
		log.Printf("%d exemptions loaded from %s", len(ex.Exemptions), *exemptionsPath)
	}
	toExamine := make(chan pkg)
	var (
		wg      sync.WaitGroup
		mu      sync.Mutex
		targets []pkg
	)

	for i := 0; i < *parallelExamine; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			for p := range toExamine {
				if err := p.examine(); err != nil {
					log.Printf("could not find build targets for %s: %v", p.Dir, err)
					continue
				}
				mu.Lock()
				targets = append(targets, p)
				mu.Unlock()
			}
		}()
	}

	dir, err := filepath.EvalSymlinks(filepath.Join(os.Getenv("GOPATH"), "src"))
	if err != nil {
		return nil, err
	}

	err = filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
		if err != nil {
			return err // stop on walk errors
		}
		if info == nil || !info.IsDir() {
			return nil // skip non-directories
		}
		if info.Name() != "debian" {
			return nil
		}
		ctrl, err := control.ParseControlFile(filepath.Join(path, "control"))
		if err != nil {
			if os.IsNotExist(err) {
				return nil // debian/control not found, skip directory
			}
			if isDir(err) {
				return nil // debian/control is a directory, e.g. pault.ag/go/debian/control/
			}
			return fmt.Errorf("%s: %v", filepath.Join(path, "control"), err)
		}
		// Defense in depth: verify we are dealing with a Debian package (and
		// not, for example, test data) by checking the XS-Go-Import-Path
		// matches the file location.
		importPath := goImportPath(ctrl.Source)
		if importPath == "" {
			return nil
		}
		toplevel := filepath.Dir(path)
		if !strings.HasSuffix(toplevel, importPath) {
			log.Printf("%q does not have suffix %q", toplevel, importPath)
			return nil
		}
		if u, ok := ex.Exemptions[importPath]; ok {
			log.Printf("SKIP %s: %s", importPath, u)
			return nil
		}
		toExamine <- pkg{Source: ctrl.Source.Source, Dir: toplevel, ImportPath: importPath}
		return nil
	})
	if err != nil {
		return nil, err
	}

	close(toExamine)
	wg.Wait()

	return targets, nil
}

type result struct {
	Pkg pkg    `json:"pkg"`
	Out string `json:"output"`
	Err string `json:"error"`
}

func generate(p pkg) (string, error) {
	if !p.Generate {
		return "", nil
	}
	g := exec.Command("go", append([]string{"generate"}, p.Targets...)...)
	g.Env = goEnv()
	if *dryRun {
		fmt.Println(g.Args)
		return "", nil
	}
	out, err := g.CombinedOutput()
	return string(out), err
}

func build(p pkg) (string, error) {
	if out, err := generate(p); err != nil {
		return out, err
	}

	var t *exec.Cmd
	if p.DisableTests {
		log.Printf("build only (Debian packaging disables tests): %s", p.ImportPath)
		t = exec.Command("go", append([]string{"build"}, p.Targets...)...)
	} else {
		// -vet=off because many packages across debian have vet issues
		if *go19 {
384
			t = exec.Command("go", append([]string{"test", "-timeout=3m"}, p.Targets...)...)
385
		} else {
386
			t = exec.Command("go", append([]string{"test", "-timeout=3m", "-vet=off"}, p.Targets...)...)
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
		}
	}
	t.Env = goEnv()
	if *dryRun {
		fmt.Println(t.Args)
		return "", nil
	}
	out, err := t.CombinedOutput()
	return string(out), err
}

func buildAll(targets []pkg) error {
	var (
		toBuild = make(chan pkg)
		wg      sync.WaitGroup
		mu      sync.Mutex
		results = make(map[string]result)
	)

	for i := 0; i < *parallelBuild; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			for p := range toBuild {
				out, err := build(p)
				mu.Lock()
				res := result{
					Pkg: p,
					Out: out,
				}
				if err != nil {
					res.Err = err.Error()
				}
				results[p.ImportPath] = res
				mu.Unlock()
			}
		}()
	}

	for _, t := range targets {
		toBuild <- t
	}

	close(toBuild)
	wg.Wait()

	return json.NewEncoder(os.Stdout).Encode(results)
}

func logic() error {
	targets, err := locate()
	if err != nil {
		return err
	}

	// Build packages (in parallel). We cannot shell out to go(1) and xargs(1)
	// for this, as we need to capture the exit codes of individual targets in
	// order to compare them later.
	return buildAll(targets)
}

func setup() error {
	// Create a new network namespace so that there is no internet connectivity
	// during compilation/testing.
	if err := syscall.Unshare(syscall.CLONE_NEWNET); err != nil {
		return fmt.Errorf("creating network namespace: %v", err)
	}

	// Bring up the loopback interface in the new namespace:
	lo := exec.Command("/bin/ip", "link", "set", "dev", "lo", "up")
	lo.Stderr = os.Stderr
	if err := lo.Run(); err != nil {
		return err
	}

	// Execute this binary again, but as an unprivileged user:
	cmd := exec.Command(os.Args[0], os.Args[1:]...)
	cmd.Env = []string{
		"CI_BUILD_PRIVILEGES_DROPPED=1",
		"PATH=" + os.Getenv("PATH"),
		"GOPATH=" + os.Getenv("GOPATH"),
		"GOCACHE=" + os.Getenv("GOCACHE"),
	}
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	cmd.SysProcAttr = &syscall.SysProcAttr{
		Credential: &syscall.Credential{
			Uid: uint32(*unprivilegedUid),
			Gid: uint32(*unprivilegedGid),
		},
	}
	return cmd.Run()
}

func main() {
	flag.Parse()

	for _, key := range []string{"GOPATH", "GOCACHE"} {
		if _, ok := os.LookupEnv(key); !ok {
			log.Fatalf("environment variable %s required, but not set in .gitlab-ci.yml?", key)
		}
	}

	if os.Getenv("CI_BUILD_PRIVILEGES_DROPPED") != "1" {
		if err := setup(); err != nil {
			log.Fatalf("%v, %T, %#v", err, err, err)
		}
		return
	}

	if err := logic(); err != nil {
		log.Fatalf("%v, %T, %#v", err, err, err)
	}
}