Skip to content

ci: Replace DataDog CI with custom upload script #169

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

Merged
merged 5 commits into from
Feb 7, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Next Next commit
ci: Replace DataDog CI with custom upload script
This will reduce CI time by ~6 minutes across all of
our runners. It's a bit janky, but I believe worth
the slight maintainance burden.
  • Loading branch information
kylecarbs committed Feb 6, 2022
commit 4f4f2d7b4186bc8e21c1b9c7b01dffacacfb1ea7
40 changes: 10 additions & 30 deletions .github/workflows/coder.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -159,45 +159,25 @@ jobs:
-covermode=atomic -coverprofile="gotests.coverage"
-timeout=3m -count=5 -race -short -parallel=2

- name: Upload DataDog Trace
if: (success() || failure()) && github.actor != 'dependabot[bot]'
env:
DATADOG_API_KEY: ${{ secrets.DATADOG_API_KEY }}
DD_DATABASE: fake
run: go run scripts/datadog-cireport/main.go gotests.xml

- name: Test with PostgreSQL Database
if: runner.os == 'Linux'
run: DB=true gotestsum --junitfile="gotests.xml" --packages="./..." --
-covermode=atomic -coverprofile="gotests.coverage" -timeout=3m
-count=1 -race -parallel=2

- name: Setup Node for DataDog CLI
uses: actions/setup-node@v2
if: always() && github.actor != 'dependabot[bot]'
with:
node-version: "14"

- name: Cache DataDog CLI
if: always() && github.actor != 'dependabot[bot]'
uses: actions/cache@v2
with:
path: |
~/.npm
%LocalAppData%\npm-cache
key: datadogci-
restore-keys: datadogci-

- name: Upload DataDog Trace
if: always() && github.actor != 'dependabot[bot]'
# See: https://docs.datadoghq.com/continuous_integration/setup_tests/junit_upload/#collecting-environment-configuration-metadata
if: (success() || failure()) && github.actor != 'dependabot[bot]'
env:
DATADOG_API_KEY: ${{ secrets.DATADOG_API_KEY }}
DD_GIT_REPOSITORY_URL: ${{ github.repositoryUrl }}
DD_GIT_BRANCH: ${{ github.head_ref }}
DD_GIT_COMMIT_SHA: ${{ github.sha }}
DD_GIT_COMMIT_MESSAGE: ${{ github.event.head_commit.message }}
DD_GIT_COMMIT_AUTHOR_NAME: ${{ github.event.head_commit.author.name }}
DD_GIT_COMMIT_AUTHOR_EMAIL: ${{ github.event.head_commit.author.email }}
DD_GIT_COMMIT_COMMITTER_NAME: ${{ github.event.head_commit.committer.name }}
DD_GIT_COMMIT_COMMITTER_EMAIL: ${{ github.event.head_commit.committer.email }}
DD_TAGS: ${{ format('os.platform:{0},os.architecture:{1}', runner.os, runner.arch) }}
run: |
npm install -g @datadog/datadog-ci
datadog-ci junit upload --service coder gotests.xml
DD_DATABASE: postgresql
run: go run scripts/datadog-cireport/main.go gotests.xml

- uses: codecov/codecov-action@v2
if: github.actor != 'dependabot[bot]'
Expand Down
1 change: 1 addition & 0 deletions codecov.yml
Original file line number Diff line number Diff line change
Expand Up @@ -31,3 +31,4 @@ ignore:
- peerbroker/proto
- provisionerd/proto
- provisionersdk/proto
- scripts/datadog-cireport
7 changes: 3 additions & 4 deletions rules.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,18 +10,17 @@ func xerrors(m dsl.Matcher) {
m.Import("errors")
m.Import("fmt")
m.Import("golang.org/x/xerrors")
msg := "Use xerrors to provide additional stacktrace information!"

m.Match("fmt.Errorf($*args)").
Suggest("xerrors.New($args)").
Report(msg)
Report("Use xerrors to provide additional stacktrace information!")

m.Match("fmt.Errorf($*args)").
Suggest("xerrors.Errorf($args)").
Report(msg)
Report("Use xerrors to provide additional stacktrace information!")

m.Match("errors.New($msg)").
Where(m["msg"].Type.Is("string")).
Suggest("xerrors.New($msg)").
Report(msg)
Report("Use xerrors to provide additional stacktrace information!")
}
178 changes: 178 additions & 0 deletions scripts/datadog-cireport/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,178 @@
package main

import (
"bytes"
"compress/gzip"
"context"
"encoding/json"
"fmt"
"log"
"mime/multipart"
"net/http"
"net/textproto"
"os"
"os/exec"
"path/filepath"
"regexp"
"runtime"
"strings"
)

// The DataDog "cireport" API is not publicly documented,
// but implementation is available in their open-source CLI
// built for CI: https://github.com/DataDog/datadog-ci
Comment on lines +21 to +23
Copy link
Contributor

Choose a reason for hiding this comment

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

Nice 👍

Comment on lines +21 to +23
Copy link
Contributor

Choose a reason for hiding this comment

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

thought: I wonder if utilities like this would be good open-source candidates for our org? We ourselves searched for a tool like this, and couldn't find it - so you had to build it!

I figure if this is around and someone else finds it, could be marketing for coder overall

Copy link
Member Author

Choose a reason for hiding this comment

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

I do agree this is a great candidate for OSS!

//
// It's built using node, and took ~3 minutes to install and
// run on our Windows runner, and ~1 minute on all others.
Comment on lines +25 to +26
Copy link
Contributor

Choose a reason for hiding this comment

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

The built binary could probably be cached once it's built, too!

Copy link
Member Author

Choose a reason for hiding this comment

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

I had it cache, but the Windows runner has such slow disk IO it made little difference 😥

//
// This script models that code as much as possible.
func main() {
apiKey := os.Getenv("DATADOG_API_KEY")
if apiKey == "" {
log.Fatal("DATADOG_API_KEY must be set!")
}
if len(os.Args) <= 1 {
log.Fatal("You must supply a filename to upload!")
}

// Code (almost) verbatim translated from:
// https://github.com/DataDog/datadog-ci/blob/78d0da28e1c1af44333deabf1c9486e2ad66b8af/src/helpers/ci.ts#L194-L229
var (
githubServerURL = os.Getenv("GITHUB_SERVER_URL")
githubRepository = os.Getenv("GITHUB_REPOSITORY")
githubSHA = os.Getenv("GITHUB_SHA")
githubRunID = os.Getenv("GITHUB_RUN_ID")
pipelineURL = fmt.Sprintf("%s/%s/actions/runs/%s", githubServerURL, githubRepository, githubRunID)
jobURL = fmt.Sprintf("%s/%s/commit/%s/checks", githubServerURL, githubRepository, githubSHA)
)
if os.Getenv("GITHUB_RUN_ATTEMPT") != "" {
pipelineURL += fmt.Sprintf("/attempts/%s", os.Getenv("GITHUB_RUN_ATTEMPT"))
}

commitMessage, err := exec.Command("git", "show", "-s", "--format=%s").CombinedOutput()
if err != nil {
log.Fatalf("Get commit message: %s", err)
}
commitData, err := exec.Command("git", "show", "-s", "--format=%an,%ae,%ad,%cn,%ce,%cd").CombinedOutput()
if err != nil {
log.Fatalf("Get commit data: %s", err)
}
commitParts := strings.Split(string(commitData), ",")

tags := map[string]string{
"service": "coder",
"_dd.cireport_version": "2",

"database": os.Getenv("DD_DATABASE"),

// Additional tags found in DataDog docs. See:
// https://docs.datadoghq.com/continuous_integration/setup_tests/junit_upload/#collecting-environment-configuration-metadata
"os.platform": runtime.GOOS,
"os.architecture": runtime.GOARCH,

"ci.job.url": jobURL,
"ci.pipeline.id": githubRunID,
"ci.pipeline.name": os.Getenv("GITHUB_WORKFLOW"),
"ci.pipeline.number": os.Getenv("GITHUB_RUN_NUMBER"),
"ci.pipeline.url": pipelineURL,
"ci.provider.name": "github",
"ci.workspace_path": os.Getenv("GITHUB_WORKSPACE"),

"git.branch": os.Getenv("GITHUB_HEAD_REF"),
"git.commit.sha": githubSHA,
"git.repository_url": fmt.Sprintf("%s/%s.git", githubServerURL, githubRepository),

"git.commit.message": strings.TrimSpace(string(commitMessage)),
"git.commit.author.name": commitParts[0],
"git.commit.author.email": commitParts[1],
"git.commit.author.date": commitParts[2],
"git.commit.committer.name": commitParts[3],
"git.commit.committer.email": commitParts[4],
"git.commit.committer.date": commitParts[5],
}

xmlFilePath := filepath.Clean(os.Args[1])
xmlFileData, err := os.ReadFile(xmlFilePath)
if err != nil {
log.Fatalf("Read %q: %s", xmlFilePath, err)
}
// https://github.com/DataDog/datadog-ci/blob/78d0da28e1c1af44333deabf1c9486e2ad66b8af/src/commands/junit/api.ts#L53
var xmlCompressedBuffer bytes.Buffer
xmlGzipWriter := gzip.NewWriter(&xmlCompressedBuffer)
_, err = xmlGzipWriter.Write(xmlFileData)
if err != nil {
log.Fatalf("Write xml: %s", err)
}
err = xmlGzipWriter.Close()
if err != nil {
log.Fatalf("Close xml gzip writer: %s", err)
}

// Represents FormData. See:
// https://github.com/DataDog/datadog-ci/blob/78d0da28e1c1af44333deabf1c9486e2ad66b8af/src/commands/junit/api.ts#L27
var multipartBuffer bytes.Buffer
multipartWriter := multipart.NewWriter(&multipartBuffer)

// Adds the event data. See:
// https://github.com/DataDog/datadog-ci/blob/78d0da28e1c1af44333deabf1c9486e2ad66b8af/src/commands/junit/api.ts#L42
eventMimeHeader := make(textproto.MIMEHeader)
eventMimeHeader.Set("Content-Disposition", `form-data; name="event"; filename="event.json"`)
eventMimeHeader.Set("Content-Type", "application/json")
eventMultipartWriter, err := multipartWriter.CreatePart(eventMimeHeader)
if err != nil {
log.Fatalf("Create event multipart: %s", err)
}
eventJSON, err := json.Marshal(tags)
if err != nil {
log.Fatalf("Marshal tags: %s", err)
}
_, err = eventMultipartWriter.Write(eventJSON)
if err != nil {
log.Fatalf("Write event JSON: %s", err)
}

// This seems really strange, but better to follow the implementation. See:
// https://github.com/DataDog/datadog-ci/blob/78d0da28e1c1af44333deabf1c9486e2ad66b8af/src/commands/junit/api.ts#L44-L55
xmlFilename := fmt.Sprintf("%s-coder-%s-%s-%s", filepath.Base(xmlFilePath), githubSHA, pipelineURL, jobURL)
xmlFilename = regexp.MustCompile("[^a-z0-9]").ReplaceAllString(xmlFilename, "_")

xmlMimeHeader := make(textproto.MIMEHeader)
xmlMimeHeader.Set("Content-Disposition", fmt.Sprintf(`form-data; name="junit_xml_report_file"; filename="%s.xml.gz"`, xmlFilename))
xmlMimeHeader.Set("Content-Type", "application/octet-stream")
inputWriter, err := multipartWriter.CreatePart(xmlMimeHeader)
if err != nil {
log.Fatalf("Create xml.gz multipart: %s", err)
}
_, err = inputWriter.Write(xmlCompressedBuffer.Bytes())
if err != nil {
log.Fatalf("Write xml.gz: %s", err)
}
err = multipartWriter.Close()
if err != nil {
log.Fatalf("Close: %s", err)
}

ctx := context.Background()
req, err := http.NewRequestWithContext(ctx, "POST", "https://cireport-intake.datadoghq.com/api/v2/cireport", &multipartBuffer)
if err != nil {
log.Fatalf("Create request: %s", err)
}
req.Header.Set("Content-Type", multipartWriter.FormDataContentType())
req.Header.Set("DD-API-KEY", apiKey)

res, err := http.DefaultClient.Do(req)
if err != nil {
log.Fatalf("Do request: %s", err)
}
defer res.Body.Close()
var msg json.RawMessage
err = json.NewDecoder(res.Body).Decode(&msg)
if err != nil {
log.Fatalf("Decode response: %s", err)
}
msg, err = json.MarshalIndent(msg, "", "\t")
if err != nil {
log.Fatalf("Pretty print: %s", err)
}
_, _ = fmt.Printf("Status code: %d\nResponse: %s\n", res.StatusCode, msg)
}