• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1// Copyright (c) 2022, Google Inc.
2//
3// Permission to use, copy, modify, and/or distribute this software for any
4// purpose with or without fee is hereby granted, provided that the above
5// copyright notice and this permission notice appear in all copies.
6//
7// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
8// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
9// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
10// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
11// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
12// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
13// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
14
15package runner
16
17import (
18	"fmt"
19	"io/ioutil"
20	"os"
21	"strconv"
22)
23
24const (
25	shardStatusFileEnv = "TEST_SHARD_STATUS_FILE"
26	shardTotalEnv      = "TEST_TOTAL_SHARDS"
27	shardIndexEnv      = "TEST_SHARD_INDEX"
28	shardPrefix        = "RUNNER_"
29)
30
31func init() {
32	// When run under `go test`, init() functions may be run twice if the
33	// test binary ends up forking and execing itself. Therefore we move
34	// the environment variables to names that don't interfere with Go's
35	// own support for sharding. If we recorded and erased them, then they
36	// wouldn't exist the second time the binary runs.
37	for _, key := range []string{shardStatusFileEnv, shardTotalEnv, shardIndexEnv} {
38		value := os.Getenv(key)
39		if len(value) > 0 {
40			os.Setenv(shardPrefix+key, value)
41			os.Setenv(key, "")
42		}
43	}
44}
45
46// getSharding returns the shard index and count, or zeros if sharding is not
47// enabled.
48func getSharding() (index, total int, err error) {
49	statusFile := os.Getenv(shardPrefix + shardStatusFileEnv)
50	totalNumStr := os.Getenv(shardPrefix + shardTotalEnv)
51	indexStr := os.Getenv(shardPrefix + shardIndexEnv)
52	if len(totalNumStr) == 0 || len(indexStr) == 0 {
53		return 0, 0, nil
54	}
55
56	totalNum, err := strconv.Atoi(totalNumStr)
57	if err != nil {
58		return 0, 0, fmt.Errorf("$%s is %q, but expected a number\n", shardTotalEnv, totalNumStr)
59	}
60
61	index, err = strconv.Atoi(indexStr)
62	if err != nil {
63		return 0, 0, fmt.Errorf("$%s is %q, but expected a number\n", shardIndexEnv, indexStr)
64	}
65
66	if index < 0 || index >= totalNum {
67		return 0, 0, fmt.Errorf("shard index/total of %d/%d is invalid\n", index, totalNum)
68	}
69
70	if len(statusFile) > 0 {
71		if err := ioutil.WriteFile(statusFile, nil, 0664); err != nil {
72			return 0, 0, err
73		}
74	}
75
76	return index, totalNum, nil
77}
78