-
Notifications
You must be signed in to change notification settings - Fork 849
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
sanastos
merged 4 commits into
GoogleCloudPlatform:master
from
pavlospt:introduce_cancelot
Sep 11, 2019
Merged
Changes from 2 commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
.idea | ||
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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" ] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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'] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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!
There was a problem hiding this comment.
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.