|
| 1 | +// Copyright 2021 The Go Authors. All rights reserved. |
| 2 | +// Use of this source code is governed by a BSD-style |
| 3 | +// license that can be found in the LICENSE file. |
| 4 | + |
| 5 | +// Locktrigger “locks” a given build trigger, making sure that |
| 6 | +// the currently running build is the only trigger running. |
| 7 | +// |
| 8 | +// Usage: |
| 9 | +// |
| 10 | +// locktrigger -project=$PROJECT_ID -build=$BUILD_ID |
| 11 | +// |
| 12 | +// The $PROJECT_ID and $BUILD_ID are typically written literally in cloudbuild.yaml |
| 13 | +// and then substituted by Cloud Build. |
| 14 | +// |
| 15 | +// When a project uses “continuous deployment powered by Cloud Build”, |
| 16 | +// the deployment is a little bit too continuous: when multiple commits |
| 17 | +// land in a short time window, Cloud Build will run all the triggered |
| 18 | +// build jobs in parallel. If each job does “gcloud app deploy”, there |
| 19 | +// is no guarantee which will win: perhaps an older commit will complete |
| 20 | +// last, resulting in the newest commit not actually being the final |
| 21 | +// deployed version of the site. This should probably be fixed in |
| 22 | +// “continuous deployment powered by Cloud Build”, but until then, |
| 23 | +// locktrigger works around the problem. |
| 24 | +// |
| 25 | +// All triggered builds must run locktrigger to guarantee mutual exclusion. |
| 26 | +// When there is contention—that is, when multiple builds are running and |
| 27 | +// they all run locktrigger—the build corresponding to the newest commit |
| 28 | +// is permitted to continue running, and older builds are canceled. |
| 29 | +// |
| 30 | +// When locktrigger exits successfully, then, at that moment, the current |
| 31 | +// build is (or recently was) the only running build for its trigger. |
| 32 | +// Of course, another build may start immediately after locktrigger exits. |
| 33 | +// As long as that build also runs locktrigger, then either it will cancel |
| 34 | +// itself (if it is older than we are), or it will cancel us before proceeding |
| 35 | +// (if we are older than it is). |
| 36 | +package main |
| 37 | + |
| 38 | +import ( |
| 39 | + "bytes" |
| 40 | + "context" |
| 41 | + "flag" |
| 42 | + "fmt" |
| 43 | + "log" |
| 44 | + "os" |
| 45 | + "os/exec" |
| 46 | + "strings" |
| 47 | + "time" |
| 48 | + |
| 49 | + cloudbuild "cloud.google.com/go/cloudbuild/apiv1/v2" |
| 50 | + "google.golang.org/api/iterator" |
| 51 | + cloudbuildpb "google.golang.org/genproto/googleapis/devtools/cloudbuild/v1" |
| 52 | +) |
| 53 | + |
| 54 | +var ( |
| 55 | + project = flag.String("project", "", "GCP project `name` (required)") |
| 56 | + build = flag.String("build", "", "GCP build `id` (required)") |
| 57 | +) |
| 58 | + |
| 59 | +func usage() { |
| 60 | + fmt.Fprintf(os.Stderr, "usage: locktrigger -project=name -build=id\n") |
| 61 | + os.Exit(2) |
| 62 | +} |
| 63 | + |
| 64 | +func main() { |
| 65 | + flag.Usage = usage |
| 66 | + flag.Parse() |
| 67 | + log.SetPrefix("locktrigger: ") |
| 68 | + log.SetFlags(0) |
| 69 | + |
| 70 | + if *project == "" || *build == "" { |
| 71 | + usage() |
| 72 | + } |
| 73 | + |
| 74 | + ctx := context.Background() |
| 75 | + c, err := cloudbuild.NewClient(ctx) |
| 76 | + if err != nil { |
| 77 | + log.Fatal(err) |
| 78 | + } |
| 79 | + defer c.Close() |
| 80 | + |
| 81 | + // Find commit hash of local Git |
| 82 | + myHash := run("git", "rev-parse", "HEAD") |
| 83 | + log.Printf("my hash: %v", myHash) |
| 84 | + |
| 85 | + // Find build object for current build, check that it matches. |
| 86 | + self := getBuild(c, ctx, *build) |
| 87 | + if hash := self.Substitutions["COMMIT_SHA"]; hash != myHash { |
| 88 | + log.Fatalf("build COMMIT_SHA does not match local hash: %v != %v", hash, myHash) |
| 89 | + } |
| 90 | + log.Printf("my build: %v", self.Id) |
| 91 | + if self.BuildTriggerId == "" { |
| 92 | + log.Fatalf("build has no trigger ID") |
| 93 | + } |
| 94 | + log.Printf("my trigger: %v", self.BuildTriggerId) |
| 95 | + |
| 96 | + // List all builds for our trigger that are still running. |
| 97 | + req := &cloudbuildpb.ListBuildsRequest{ |
| 98 | + ProjectId: *project, |
| 99 | + // Note: Really want "status=WORKING buildTriggerId="+self.BuildTriggerId, |
| 100 | + // but that fails with an InvalidArgument error for unknown reasons. |
| 101 | + // status=WORKING will narrow the list down to something reasonable, |
| 102 | + // and we filter the unrelated triggers below. |
| 103 | + Filter: "status=WORKING", |
| 104 | + } |
| 105 | + it := c.ListBuilds(ctx, req) |
| 106 | + foundSelf := false |
| 107 | + shallow := false |
| 108 | + if _, err := os.Stat(run("git", "rev-parse", "--git-dir") + "/shallow"); err == nil { |
| 109 | + shallow = true |
| 110 | + } |
| 111 | + for { |
| 112 | + b, err := it.Next() |
| 113 | + if err == iterator.Done { |
| 114 | + break |
| 115 | + } |
| 116 | + if err != nil { |
| 117 | + log.Fatalf("reading builds: %v (%q)", err, req.Filter) |
| 118 | + } |
| 119 | + if b.BuildTriggerId != self.BuildTriggerId { |
| 120 | + continue |
| 121 | + } |
| 122 | + |
| 123 | + // Check whether this build is an older or newer commit. |
| 124 | + // If this build is older, cancel it. |
| 125 | + // If this build is newer, cancel ourselves. |
| 126 | + if b.Id == self.Id { |
| 127 | + foundSelf = true |
| 128 | + continue |
| 129 | + } |
| 130 | + hash := b.Substitutions["COMMIT_SHA"] |
| 131 | + if hash == "" { |
| 132 | + log.Fatalf("cannot find COMMIT_SHA for build %v", b.Id) |
| 133 | + } |
| 134 | + if hash == myHash { |
| 135 | + log.Fatalf("found another build %v at same commit %v", b.Id, hash) |
| 136 | + } |
| 137 | + |
| 138 | + // Fetch the full Git repo so we can answer the history questions. |
| 139 | + // This is delayed until now to avoid the expense of fetching the full repo |
| 140 | + // if we are the only build that is running. |
| 141 | + if shallow { |
| 142 | + log.Printf("git fetch --unshallow") |
| 143 | + run("git", "fetch", "--unshallow") |
| 144 | + shallow = false |
| 145 | + } |
| 146 | + |
| 147 | + // Contention. |
| 148 | + // Find the common ancestor between us and that build, |
| 149 | + // to tell whether we're older, it's older, or we're unrelated. |
| 150 | + log.Printf("checking %v", hash) |
| 151 | + switch run("git", "merge-base", myHash, hash) { |
| 152 | + default: |
| 153 | + log.Fatalf("unexpected build for unrelated commit %v", hash) |
| 154 | + |
| 155 | + case myHash: |
| 156 | + // myHash is older than b's hash. Cancel self. |
| 157 | + log.Printf("canceling self, for build %v commit %v", b.Id, hash) |
| 158 | + cancel(c, ctx, self.Id) |
| 159 | + |
| 160 | + case hash: |
| 161 | + // b's hash is older than myHash. Cancel b. |
| 162 | + log.Printf("canceling build %v commit %v", b.Id, hash) |
| 163 | + cancel(c, ctx, b.Id) |
| 164 | + } |
| 165 | + } |
| 166 | + |
| 167 | + // If we listed all the in-progress builds, we should have seen ourselves. |
| 168 | + if !foundSelf { |
| 169 | + log.Fatalf("reading builds: didn't find self") |
| 170 | + } |
| 171 | +} |
| 172 | + |
| 173 | +// getBuild returns the build info for the build with the given id. |
| 174 | +func getBuild(c *cloudbuild.Client, ctx context.Context, id string) *cloudbuildpb.Build { |
| 175 | + req := &cloudbuildpb.GetBuildRequest{ |
| 176 | + ProjectId: *project, |
| 177 | + Id: id, |
| 178 | + } |
| 179 | + b, err := c.GetBuild(ctx, req) |
| 180 | + if err != nil { |
| 181 | + log.Fatalf("getbuild %v: %v", id, err) |
| 182 | + } |
| 183 | + return b |
| 184 | +} |
| 185 | + |
| 186 | +// cancel cancels the build with the given id. |
| 187 | +func cancel(c *cloudbuild.Client, ctx context.Context, id string) { |
| 188 | + req := &cloudbuildpb.CancelBuildRequest{ |
| 189 | + ProjectId: *project, |
| 190 | + Id: id, |
| 191 | + } |
| 192 | + _, err := c.CancelBuild(ctx, req) |
| 193 | + if err != nil { |
| 194 | + // Not Fatal: maybe cancel failed because the build exited. |
| 195 | + // Waiting for it to stop running below will take care of that case. |
| 196 | + log.Printf("cancel %v: %v", id, err) |
| 197 | + } |
| 198 | + |
| 199 | + // Wait for build to report being stopped, |
| 200 | + // in case cancel only queues the cancellation and doesn't actually wait, |
| 201 | + // or in case cancel failed. |
| 202 | + // Willing to wait a few minutes. |
| 203 | + now := time.Now() |
| 204 | + for time.Since(now) < 3*time.Minute { |
| 205 | + b := getBuild(c, ctx, id) |
| 206 | + if b.Status != cloudbuildpb.Build_WORKING { |
| 207 | + log.Printf("canceled %v: now %v", id, b.Status) |
| 208 | + return |
| 209 | + } |
| 210 | + time.Sleep(10 * time.Second) |
| 211 | + } |
| 212 | + log.Fatalf("cancel %v: did not stop", id) |
| 213 | +} |
| 214 | + |
| 215 | +// run runs the given command line and returns the standard output, with spaces trimmed. |
| 216 | +func run(args ...string) string { |
| 217 | + var stdout, stderr bytes.Buffer |
| 218 | + cmd := exec.Command(args[0], args[1:]...) |
| 219 | + cmd.Stdout = &stdout |
| 220 | + cmd.Stderr = &stderr |
| 221 | + if err := cmd.Run(); err != nil { |
| 222 | + log.Fatalf("exec %v: %v\n%s%s", args, err, stdout.String(), stderr.String()) |
| 223 | + } |
| 224 | + return strings.TrimSpace(stdout.String()) |
| 225 | +} |
0 commit comments