Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[New builder] Introduce Cancelot #271

Merged
merged 4 commits into from
Sep 11, 2019
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
.idea
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should this be in here?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm not 100% sure, just added it cause I was using Goland for it!

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Although I can't imagine we would want to check in intellij config directories, there's no extant gitignore so I'd leave it out of this commit.

15 changes: 15 additions & 0 deletions cancelot/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
FROM gcr.io/cloud-builders/go AS build-env

ADD ./ /go/src/

ENV GOBIN=/go/bin
RUN go get -d -v ./...
RUN go install /go/src/main.go

FROM alpine:latest

RUN apk add --no-cache ca-certificates

COPY --from=build-env /go/bin/main /go/bin/main

ENTRYPOINT [ "/go/bin/main" ]
45 changes: 45 additions & 0 deletions cancelot/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
# Cancelot

Cancelot (thank you Twitter for the name :D) allows you to cancel previous builds running for the same branch,
when you are using VCS triggered builds.

# Purpose

Cancelot was built because there is no out of the box solution by CloudBuild, in order to cancel a previous running
build upon a new commit in the same branch. This can save a lot of build minutes that would be otherwise billed to the
account.

# Deploying Cancelot

* Make any changes you need
* Navigate to Cancelot's folder and execute the following: `gcloud builds submit . --config=cloudbuild.yaml`
* Enjoy

## Using Cancelot

Add the builder as the first step in your project's `cloudbuild.yaml`:

```yaml
steps:
- name: 'gcr.io/$PROJECT_ID/cancelot'
args: [
'--current_build_id', '$BUILD_ID',
'--branch_name', '$BRANCH_NAME'
]
```

Cancelot will be invoked when your build starts and will try to find any running jobs that match the following filter:

```
build_id != "[CURRENT_BUILD_ID]" AND
source.repo_source.branch_name = "[BRANCH_NAME]" AND
status = "WORKING" AND
start_time<"[CURRENT_BUILD_START_TIME]"
```

After successfully fetching the list with the running builds that match the defined criteria, it loops and cancels
each one.

## Inspiration

Cancelot is heavily inspired by `slackbot` from CloudBuilders community
65 changes: 65 additions & 0 deletions cancelot/cancelot/cancelpreviousbuild.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
package cancelot

import (
"context"
"fmt"
"google.golang.org/api/cloudbuild/v1"
"log"
)

// Checks for previous running builds on the same branch, in order to cancel them
func CancelPreviousBuild(ctx context.Context, currentBuildId string, branchName string) {
svc := gcbClient(ctx)
project, err := getProject()
if err != nil {
log.Fatalf("Failed to get project: %v", err)
}

log.Printf("Going to fetch current build details for: %s", currentBuildId)

currentBuildResponse, currentBuildError := svc.Projects.Builds.Get(project, currentBuildId).Do()
if currentBuildError != nil {
log.Fatalf("Failed to get build details from Cloud Build. Will retry in one minute.")
}

log.Printf("Going to check ongoing jobs for branch: %s", branchName)

onGoingJobFilter := fmt.Sprintf(`
build_id != "%s" AND
source.repo_source.branch_name = "%s" AND
status = "WORKING" AND
start_time<"%s"`,
currentBuildId,
branchName,
currentBuildResponse.StartTime)

log.Printf("Builds filter created: %s", onGoingJobFilter)

onGoingBuildsResponse, onGoingBuildsError := svc.Projects.Builds.List(project).Filter(onGoingJobFilter).Do()

if onGoingBuildsError != nil {
log.Fatalf("Failed to get builds from Cloud Build. Will retry in one minute.")
}

onGoingBuilds := onGoingBuildsResponse.Builds
numOfOnGoingBuilds := len(onGoingBuilds)

log.Printf("Ongoing builds for %s has size of: %d", branchName, numOfOnGoingBuilds)

if numOfOnGoingBuilds == 0 {
return
}

for _, build := range onGoingBuilds {
log.Printf("Going to cancel build with id: %s", build.Id)

cancelBuildCall := svc.Projects.Builds.Cancel(project, build.Id, &cloudbuild.CancelBuildRequest{})
buildCancelResponse, buildCancelError := cancelBuildCall.Do()

if buildCancelError != nil {
log.Fatalf("Failed to cancel build with id:%s - %v", build.Id, buildCancelError)
}

log.Printf("Cancelled build with id:%s", buildCancelResponse.Id)
}
}
50 changes: 50 additions & 0 deletions cancelot/cancelot/cloudbuild.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
package cancelot

import (
"bytes"
"context"
"log"
"os/exec"
"strings"

"cloud.google.com/go/compute/metadata"
"golang.org/x/oauth2/google"
cloudbuild "google.golang.org/api/cloudbuild/v1"
)

// getProject gets the project ID.
func getProject() (string, error) {
// Test if we're running on GCE.
if metadata.OnGCE() {
// Use the GCE Metadata service.
projectID, err := metadata.ProjectID()
if err != nil {
log.Printf("Failed to get project ID from instance metadata")
return "", err
}
return projectID, nil
}
// Shell out to gcloud.
cmd := exec.Command("gcloud", "config", "get-value", "project")
var out bytes.Buffer
cmd.Stdout = &out
err := cmd.Run()
if err != nil {
log.Printf("Failed to shell out to gcloud: %+v", err)
return "", err
}
projectID := strings.TrimSuffix(out.String(), "\n")
return projectID, nil
}

func gcbClient(ctx context.Context) *cloudbuild.Service {
client, err := google.DefaultClient(ctx, cloudbuild.CloudPlatformScope)
if err != nil {
log.Fatalf("Caught error creating client: %v", err)
}
svc, err := cloudbuild.New(client)
if err != nil {
log.Fatalf("Caught error creating service: %v", err)
}
return svc
}
6 changes: 6 additions & 0 deletions cancelot/cloudbuild.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
steps:
- name: 'gcr.io/cloud-builders/docker'
args: [ 'build', '-t', 'gcr.io/$PROJECT_ID/cancelot', '.' ]
images:
- 'gcr.io/$PROJECT_ID/cancelot'
tags: ['cloud-builders-community']
33 changes: 33 additions & 0 deletions cancelot/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
// Post build status results to Slack.

package main

import (
"context"
"flag"
"log"

"./cancelot"
)

var (
currentBuildId = flag.String("current_build_id", "", "The current build id, in order to be excluded")
branchName = flag.String("branch_name", "", "BranchName to cancel previous ongoing jobs on")
)

func main() {
log.Print("Starting cancelot")
flag.Parse()
ctx := context.Background()

if *currentBuildId == "" {
log.Fatalf("CurrentBuildId must be provided.")
}

if *branchName == "" {
log.Fatalf("BranchName must be provided.")
}

cancelot.CancelPreviousBuild(ctx, *currentBuildId, *branchName)
return
}