diff --git a/.gitea/workflows/ci.yaml b/.gitea/workflows/ci.yaml new file mode 100644 index 0000000..4a9ff4f --- /dev/null +++ b/.gitea/workflows/ci.yaml @@ -0,0 +1,163 @@ +name: ci + +on: + push: + branches: [main] + tags: ["v*"] + pull_request: + +concurrency: + group: ci-${{ github.ref }} + cancel-in-progress: true + +env: + GOLANGCI_LINT_VERSION: v2.12.2 + SQLC_VERSION: v1.31.1 + +jobs: + lint: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + # The runners are ephemeral and clone every action from GitHub, which + # takes minutes; Go comes as a tarball instead, and the job image + # already has the Node version the frontend build needs. + - name: Install Go + run: | + v="$(awk '/^go /{print $2}' go.mod)" + curl -fsSL "https://go.dev/dl/go${v}.linux-amd64.tar.gz" | tar -C /usr/local -xz + echo /usr/local/go/bin >> "$GITHUB_PATH" + echo "$HOME/go/bin" >> "$GITHUB_PATH" + - name: Build frontend + run: npm ci --no-audit --no-fund && npm run build + - name: Generated code is up to date + run: | + go tool templ generate + # The release binary avoids compiling sqlc's cgo parser. + curl -fsSL "https://github.com/sqlc-dev/sqlc/releases/download/${SQLC_VERSION}/sqlc_${SQLC_VERSION#v}_linux_amd64.tar.gz" | tar -xz -C /usr/local/bin sqlc + sqlc generate + git diff --exit-code -- '*.go' + - name: gofmt + run: test -z "$(gofmt -l internal cmd)" || { gofmt -l internal cmd; exit 1; } + - name: go vet + run: go vet ./... + - name: golangci-lint + run: | + go install github.com/golangci/golangci-lint/v2/cmd/golangci-lint@${GOLANGCI_LINT_VERSION} + "$(go env GOPATH)/bin/golangci-lint" run ./... + + test: + runs-on: ubuntu-latest + services: + timescaledb: + image: timescale/timescaledb:2.30.1-pg16 + env: + POSTGRES_PASSWORD: postgres + redis: + image: redis:8-alpine + env: + UPTIME_TEST_DATABASE_URL: postgres://uptime:uptime@timescaledb:5432/uptime_test?sslmode=disable + UPTIME_TEST_REDIS_URL: redis://redis:6379/15 + steps: + - uses: actions/checkout@v7 + # The runners are ephemeral and clone every action from GitHub, which + # takes minutes; Go comes as a tarball instead, and the job image + # already has the Node version the frontend build needs. + - name: Install Go + run: | + v="$(awk '/^go /{print $2}' go.mod)" + curl -fsSL "https://go.dev/dl/go${v}.linux-amd64.tar.gz" | tar -C /usr/local -xz + echo /usr/local/go/bin >> "$GITHUB_PATH" + echo "$HOME/go/bin" >> "$GITHUB_PATH" + - name: Build frontend + run: npm ci --no-audit --no-fund && npm run build + - name: Prepare database + # The same roles and databases as the local environment: the + # application role must not be a superuser, or row-level security + # is bypassed and the isolation tests prove nothing. + run: go run ./internal/devtools/pginit "postgres://postgres:postgres@timescaledb:5432/postgres?sslmode=disable" deploy/dev/postgres-init.sql + - name: Test + # Integration tests share one database, so packages run one at a time. + run: go test -p 1 -count=1 ./... + + build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + # The runners are ephemeral and clone every action from GitHub, which + # takes minutes; Go comes as a tarball instead, and the job image + # already has the Node version the frontend build needs. + - name: Install Go + run: | + v="$(awk '/^go /{print $2}' go.mod)" + curl -fsSL "https://go.dev/dl/go${v}.linux-amd64.tar.gz" | tar -C /usr/local -xz + echo /usr/local/go/bin >> "$GITHUB_PATH" + echo "$HOME/go/bin" >> "$GITHUB_PATH" + - name: Build frontend + run: npm ci --no-audit --no-fund && npm run build + - name: Build binaries + run: | + for platform in linux/amd64 linux/arm64; do + CGO_ENABLED=0 GOOS=${platform%/*} GOARCH=${platform#*/} \ + go build -trimpath -ldflags "-s -w" -o "dist/${platform%/*}_${platform#*/}/" ./cmd/... + done + ls -R dist + + image: + # Kaniko runs rootless from docker:cli, the same way as the other + # repositories on this instance: the default job image has no docker + # CLI, and Kaniko's own image lacks what the runner needs to keep a job + # container alive. Images are pushed only from main and tags, and only + # once the PACKAGE_TOKEN secret (write:package) exists. + runs-on: ubuntu-latest + container: + image: docker:cli + defaults: + run: + shell: sh + steps: + - name: Build (and push from main and tags) + env: + GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }} + PACKAGE_TOKEN: ${{ secrets.PACKAGE_TOKEN }} + run: | + set -eu + REGISTRY="${GITHUB_SERVER_URL#*://}" + IMAGE="$(printf '%s/%s' "$REGISTRY" "$GITHUB_REPOSITORY" | tr 'A-Z' 'a-z')" + SHORT="$(printf '%s' "$GITHUB_SHA" | cut -c1-12)" + case "$GITHUB_REF" in + refs/tags/v*) TAG="$GITHUB_REF_NAME" ;; + *) TAG="$(date -u +%Y%m%d%H%M%S)-$SHORT" ;; + esac + PUSH="--no-push" + DEST="--destination ${IMAGE}:${TAG}" + case "$GITHUB_REF" in + refs/heads/main|refs/tags/v*) + if [ -n "${PACKAGE_TOKEN:-}" ]; then + PUSH="" + [ "$GITHUB_REF" = refs/heads/main ] && DEST="$DEST --destination ${IMAGE}:latest" + else + echo "PACKAGE_TOKEN is not set; building without pushing." + fi ;; + esac + case "$GITHUB_SERVER_URL" in https://*) PULL=https ;; *) PULL=http ;; esac + # Pull requests are built from their head, which Gitea exposes as + # refs/pull//head. + REF="$GITHUB_REF" + case "$REF" in refs/pull/*/merge) REF="${REF%/merge}/head" ;; esac + AUTH="$(printf '%s:%s' "$GITHUB_ACTOR" "${PACKAGE_TOKEN:-none}" | base64 | tr -d '\n')" + CFG="$(printf '{"auths":{"%s":{"auth":"%s"}}}' "$REGISTRY" "$AUTH")" + docker run --rm \ + -e GIT_PULL_METHOD="$PULL" \ + -e GIT_USERNAME="x-access-token" \ + -e GIT_PASSWORD="$GITEA_TOKEN" \ + -e CFG="$CFG" \ + --entrypoint /busybox/sh \ + gcr.io/kaniko-project/executor:v1.23.2-debug \ + -c 'mkdir -p /kaniko/.docker && printf %s "$CFG" > /kaniko/.docker/config.json && exec /kaniko/executor "$@"' _ \ + --context "git://${REGISTRY}/${GITHUB_REPOSITORY}.git#${REF}" \ + --dockerfile Dockerfile \ + --build-arg VERSION="$TAG" \ + --build-arg COMMIT="$SHORT" \ + $DEST $PUSH \ + --compressed-caching=false diff --git a/internal/api/agent.go b/internal/api/agent.go index be0079c..3eff643 100644 --- a/internal/api/agent.go +++ b/internal/api/agent.go @@ -11,6 +11,7 @@ import ( "github.com/gin-gonic/gin" "github.com/google/uuid" "github.com/jackc/pgx/v5" + "github.com/redis/go-redis/v9" "git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi" "git.zb-server.de/ZB-Server/uptimesebi/internal/config" @@ -202,6 +203,12 @@ func (s *Server) agentResults(c *gin.Context) { } ctx := c.Request.Context() region, instance := regionOf(c), instanceOf(c) + fresh, seen, err := s.claimResults(ctx, instance, req.Results) + if err != nil { + internalError(c, err) + return + } + req.Results = fresh ids := make([]uuid.UUID, len(req.Results)) for i, r := range req.Results { ids[i] = r.MonitorID @@ -209,7 +216,7 @@ func (s *Server) agentResults(c *gin.Context) { now := time.Now() monitors := map[uuid.UUID]store.MonitorsForResultsRow{} var accepted []agentapi.Result - err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error { + err = s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error { a := agentOf(c) rows, err := q.MonitorsForResults(ctx, store.MonitorsForResultsParams{RegionID: deref(a.RegionID), Ids: ids, AgentOrg: a.OrgID}) if err != nil { @@ -248,6 +255,8 @@ func (s *Server) agentResults(c *gin.Context) { return err }) if err != nil { + // Unclaimed, the checker's retry is stored instead. + s.unclaimResults(context.WithoutCancel(ctx), seen) internalError(c, err) return } @@ -274,3 +283,48 @@ func truncateValid(s string, n int) string { } return s[:n] } + +// resultClaimTTL covers the retries of a checker that lost the answer to a +// report, which happen within minutes. +const resultClaimTTL = 2 * time.Hour + +// claimResults drops results already received. A checker that does not get +// the answer to a report, say because the connection broke while the API was +// still working, sends the batch again; without this, the retry would be +// stored twice. A run is identified by instance, monitor and schedule time. +// It returns the new results and the claim keys to release if storing fails. +func (s *Server) claimResults(ctx context.Context, instance uuid.UUID, results []agentapi.Result) ([]agentapi.Result, []string, error) { + if len(results) == 0 { + return results, nil, nil + } + keys := make([]string, len(results)) + cmds := make([]*redis.BoolCmd, len(results)) + _, err := s.rdb.Pipelined(ctx, func(p redis.Pipeliner) error { + for i, r := range results { + keys[i] = "result:" + instance.String() + ":" + r.MonitorID.String() + ":" + strconv.FormatInt(r.ScheduledAt.UnixMilli(), 10) + cmds[i] = p.SetNX(ctx, keys[i], 1, resultClaimTTL) + } + return nil + }) + if err != nil { + return nil, nil, err + } + fresh := results[:0:0] + var claimed []string + for i, r := range results { + if cmds[i].Val() { + fresh = append(fresh, r) + claimed = append(claimed, keys[i]) + } + } + return fresh, claimed, nil +} + +func (s *Server) unclaimResults(ctx context.Context, keys []string) { + if len(keys) == 0 { + return + } + if err := s.rdb.Del(ctx, keys...).Err(); err != nil { + s.log.WarnContext(ctx, "releasing result claims failed", "error", err) + } +} diff --git a/internal/api/checker_test.go b/internal/api/checker_test.go index 9bbedf5..b0d2173 100644 --- a/internal/api/checker_test.go +++ b/internal/api/checker_test.go @@ -207,3 +207,38 @@ func waitFor(t *testing.T, d time.Duration, what string, cond func() bool) { time.Sleep(100 * time.Millisecond) } } + +// A checker that lost the answer to a report sends it again; the results +// must not be stored twice. +func TestResultReportIsIdempotent(t *testing.T) { + e := newEnv(t) + tok, region := e.platformChecker(t, uniq("eu-")) + owner := e.browser(t) + owner.signup("o@"+uniq("id")+".test", uniq("id-")) + _, m := owner.do("POST", "/api/v1/org/monitors", map[string]any{ + "name": "m", "type": "tcp", "target": "example.com:443", "interval_seconds": 3600, "regions": []string{region}, + }) + monitor := uuid.MustParse(m["id"].(string)) + client := agentapi.NewClient(e.srv.URL, tok, uuid.New(), "test").WithHTTPClient(e.srv.Client()) + at := time.Now().Truncate(time.Millisecond) + batch := []agentapi.Result{ + {MonitorID: monitor, ScheduledAt: at, StartedAt: at, OK: true}, + {MonitorID: monitor, ScheduledAt: at.Add(time.Second), StartedAt: at.Add(time.Second), OK: false}, + } + for range 3 { + if err := client.Report(context.Background(), batch); err != nil { + t.Fatal(err) + } + } + if n := e.count(t, `SELECT count(*) FROM check_results WHERE monitor_id = $1`, monitor); n != 2 { + t.Errorf("stored results = %d, want 2", n) + } + // Another instance's run of the same schedule time is its own result. + other := agentapi.NewClient(e.srv.URL, tok, uuid.New(), "test").WithHTTPClient(e.srv.Client()) + if err := other.Report(context.Background(), batch[:1]); err != nil { + t.Fatal(err) + } + if n := e.count(t, `SELECT count(*) FROM check_results WHERE monitor_id = $1`, monitor); n != 3 { + t.Errorf("stored results = %d, want 3", n) + } +} diff --git a/internal/devtools/pginit/main.go b/internal/devtools/pginit/main.go new file mode 100644 index 0000000..1759357 --- /dev/null +++ b/internal/devtools/pginit/main.go @@ -0,0 +1,94 @@ +// Command pginit applies a psql-style init script with a superuser +// connection, for databases that cannot mount deploy/dev/postgres-init.sql +// themselves, such as CI service containers. It understands statements +// ending in ";" and "\connect " lines. +// +// go run ./internal/devtools/pginit postgres://postgres:pw@host:5432/postgres deploy/dev/postgres-init.sql +package main + +import ( + "bufio" + "context" + "fmt" + "net/url" + "os" + "strings" + "time" + + "github.com/jackc/pgx/v5" +) + +func main() { + if len(os.Args) != 3 { + fmt.Fprintln(os.Stderr, "usage: pginit