8000 ci: Go code coverage from unit and e2e tests, reported to coveralls.io by Slach · Pull Request #2183 · Altinity/clickhouse-operator · GitHub
[go: up one dir, main page]

Skip to content
Open
Show file tree
Hide file tree
Changes from all 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
56 changes: 53 additions & 3 deletions .github/workflows/run_tests.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,10 @@ on:
pull_request:
branches:
- '*'
# master runs feed the Coveralls badge (README), which shows the default branch's coverage.
push:
branches:
- master
workflow_dispatch:
inputs:
test_mode:
Expand Down Expand Up @@ -35,7 +39,16 @@ jobs:
# -vet=off is the project convention: plain `go test` fails to build a few packages
# on pre-existing vet noise unrelated to the tests.
- name: go test -race
run: go test -vet=off -race -count=1 ./pkg/...
run: go test -vet=off -race -count=1 -cover -covermode=atomic -coverpkg=./pkg/...,./cmd/... -coverprofile=unit.out ./pkg/... ./cmd/...

- name: Report unit test coverage
uses: coverallsapp/github-action@v2
with:
fail-on-error: false
file: unit.out
format: golang
parallel: true
flag-name: unit

run_tests:
name: Run Tests
Expand Down Expand Up @@ -106,6 +119,11 @@ jobs:
sudo apt update
sudo apt install -y conntrack clickhouse-client

# Needed by tests/e2e/coverage.sh collect (go tool covdata).
- uses: actions/setup-go@v7
with:
go-version-file: go.mod

# test_010084 render-tests the Helm chart. The runner image happens to preinstall helm,
# but declaring it keeps the suite from silently skipping that scenario if that changes.
- uses: azure/setup-helm@v5
Expand All @@ -129,8 +147,8 @@ jobs:
echo "current release=$CHO_RELEASE"
echo "current go version=$GO_VERSION"

docker build -f dockerfile/operator/Dockerfile --build-arg GO_VERSION=${GO_VERSION} --build-arg GIT_SHA=$(git rev-parse --short HEAD) --build-arg GOFIPS140=${GOFIPS140} -t altinity/clickhouse-operator:${CHO_RELEASE} --pull .
docker build -f dockerfile/metrics-exporter/Dockerfile --build-arg GO_VERSION=${GO_VERSION} --build-arg GIT_SHA=$(git rev-parse --short HEAD) --build-arg GOFIPS140=${GOFIPS140} -t altinity/metrics-exporter:${CHO_RELEASE} --pull .
docker build -f dockerfile/operator/Dockerfile --build-arg GO_VERSION=${GO_VERSION} --build-arg GIT_SHA=$(git rev-parse --short HEAD) --build-arg GOFIPS140=${GOFIPS140} --build-arg GO_COVER=yes -t altinity/clickhouse-operator:${CHO_RELEASE} --pull .
docker build -f dockerfile/metrics-exporter/Dockerfile --build-arg GO_VERSION=${GO_VERSION} --build-arg GIT_SHA=$(git rev-parse --short HEAD) --build-arg GOFIPS140=${GOFIPS140} --build-arg GO_COVER=yes -t altinity/metrics-exporter:${CHO_RELEASE} --pull .

docker image save altinity/clickhouse-operator:${CHO_RELEASE} -o operator.tar
docker image save altinity/metrics-exporter:${CHO_RELEASE} -o metrics-exporter.tar
Expand Down Expand Up @@ -162,6 +180,9 @@ jobs:
run: |
bash ./deploy/zookeeper/zookeeper-with-zookeeper-operator/install-zookeeper-operator.sh

- name: Reset e2e coverage
run: ./tests/e2e/coverage.sh reset

- name: Run Tests
id: run-tests
continue-on-error: true
Expand All @@ -177,6 +198,8 @@ jobs:

sudo ln -snvf ~/venv/qa/bin/tfs /bin/tfs
export IMAGE_PULL_POLICY="IfNotPresent"
# Operator pods run the GO_COVER=yes images and flush Go coverage counters to a node hostPath.
export E2E_COVERAGE=yes
echo " image pull policy: ${IMAGE_PULL_POLICY}"
echo

Expand Down Expand Up @@ -208,6 +231,20 @@ jobs:
echo "test_result=$test_result" >> $GITHUB_OUTPUT
exit "$test_result"

- name: Collect e2e coverage
if: always()
run: ./tests/e2e/coverage.sh collect _coverage_/e2e

- name: Report e2e coverage
if: always()
uses: coverallsapp/github-action@v2
with:
fail-on-error: false
file: _coverage_/e2e/e2e.out
format: golang
parallel: true
flag-name: e2e

- uses: actions/upload-artifact@v7
with:
name: testflows-logs
Expand All @@ -231,3 +268,16 @@ jobs:
with:
script: |
core.setFailed('Test suite has failures! Check test run status and logs.')

# Merges the parallel unit + e2e coverage reports into one Coveralls build.
coverage:
name: Coverage
needs: [go_unit_tests, run_tests]
if: always()
runs-on: ubuntu-latest
steps:
- name: Coveralls finished
uses: coverallsapp/github-action@v2
with:
fail-on-error: false
parallel-finished: true
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -59,4 +59,6 @@ AGENTS.md
.agents
skills-lock.json

/.cr-release-packages
/.cr-release-packages
# Local go coverage reports (dev/run_coverage_report.sh, tests/e2e/coverage.sh)
_coverage_
1 change: 1 addition & 0 deletions README.md
@@ -7,6 +7,7 @@ The Altinity Kubernetes Operator for ClickHouse creates, configures and manages
Original file line number Diff line number Diff line change
Expand Up
[![tags](https://img.shields.io/github/tag/altinity/clickhouse-operator.svg)](https://github.com/altinity/clickhouse-operator/tags)
[![Docker Pulls](https://img.shields.io/docker/pulls/altinity/clickhouse-operator.svg)](https://hub.docker.com/r/altinity/clickhouse-operator)
[![Go version](https://img.shields.io/github/go-mod/go-version/altinity/clickhouse-operator)](https://img.shields.io/github/go-mod/go-version/altinity/clickhouse-operator)
[![Coverage Status](https://coveralls.io/repos/github/Altinity/clickhouse-operator/badge.svg)](https://coveralls.io/github/Altinity/clickhouse-operator)
[![Go Report Card](https://goreportcard.com/badge/github.com/altinity/clickhouse-operator)](https://goreportcard.com/report/github.com/altinity/clickhouse-operator)
[![issues](https://img.shields.io/github/issues/altinity/clickhouse-operator.svg)](https://github.com/altinity/clickhouse-operator/issues)
<a href="https://altinity.com/slack">
Expand Down
7 changes: 7 additions & 0 deletions cmd/metrics_exporter/app/metrics_exporter.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import (
"fmt"
"os"
"os/signal"
"sync"
"syscall"

log "github.com/golang/glog"
Expand All @@ -32,6 +33,7 @@ import (
chopclientset "github.com/altinity/clickhouse-operator/pkg/client/clientset/versioned"
chopinformers "github.com/altinity/clickhouse-operator/pkg/client/informers/externalversions"
"github.com/altinity/clickhouse-operator/pkg/metrics/clickhouse"
"github.com/altinity/clickhouse-operator/pkg/util/coverage"
"github.com/altinity/clickhouse-operator/pkg/util/fips"
"github.com/altinity/clickhouse-operator/pkg/version"
)
Expand Down Expand Up @@ -121,6 +123,10 @@ func Run() {
os.Exit(1)
}()

// Flushes coverage counters periodically and on shutdown, no-op unless built with -cover and GOCOVERDIR is set
var wg sync.WaitGroup
coverage.Start(ctx, &wg)

log.Infof("Starting metrics exporter. Version:%s GitSHA:%s BuiltAt:%s\n", version.Version, version.GitSHA, version.BuiltAt)

// Initialize k8s API clients
Expand Down Expand Up @@ -158,6 +164,7 @@ func Run() {
startChopConfigRestartWatcher(ctx, chopClient)

<-ctx.Done()
wg.Wait()
}

// startChopConfigRestartWatcher wires a ClickHouseOperatorConfiguration informer
Expand Down
4 changes: 4 additions & 0 deletions cmd/operator/app/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import (

log "github.com/altinity/clickhouse-operator/pkg/announcer"
"github.com/altinity/clickhouse-operator/pkg/util"
"github.com/altinity/clickhouse-operator/pkg/util/coverage"
"github.com/altinity/clickhouse-operator/pkg/util/fips"
"github.com/altinity/clickhouse-operator/pkg/version"
)
Expand Down Expand Up @@ -97,6 +98,9 @@ func Run() {

var wg sync.WaitGroup

// Flushes coverage counters periodically and on shutdown, no-op unless built with -cover and GOCOVERDIR is set
coverage.Start(ctx, &wg)

launchClickHouse(ctx, &wg)
launchClickHouseReconcilerMetricsExporter(ctx, &wg)
launchKeeper(ctx, &wg)
Expand Down
2 changes: 1 addition & 1 deletion dev/go_build_metrics_exporter.sh
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,6 @@ source "${CUR_DIR}/go_build_config.sh"

# Build metrics-exporter
OUTPUT_BINARY="${METRICS_EXPORTER_BIN:-${SRC_ROOT}/dev/bin/metrics-exporter}"
MAIN_SRC_FILE="${SRC_ROOT}/cmd/metrics_exporter/main.go"
MAIN_SRC_FILE="${SRC_ROOT}/cmd/metrics_exporter"

source "${CUR_DIR}/go_build_universal.sh"
2 changes: 1 addition & 1 deletion dev/go_build_operator.sh
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,6 @@ source "${CUR_DIR}/go_build_config.sh"

# Build clickhouse-operator
OUTPUT_BINARY="${OPERATOR_BIN:-"${SRC_ROOT}/dev/bin/clickhouse-operator"}"
MAIN_SRC_FILE="${SRC_ROOT}/cmd/operator/main.go"
MAIN_SRC_FILE="${SRC_ROOT}/cmd/operator"

source "${CUR_DIR}/go_build_universal.sh"
8 changes: 8 additions & 0 deletions dev/go_build_universal.sh
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,20 @@ if [[ ! -d "${SRC_ROOT}/vendor" ]]; then
go mod vendor
fi

# GO_COVER=yes builds a coverage-instrumented binary. Atomic mode is required by
# runtime/coverage.ClearCounters, see pkg/util/coverage.
GO_COVER_FLAGS=""
if [[ "${GO_COVER:-}" == "yes" ]]; then
GO_COVER_FLAGS="-cover -covermode=atomic"
fi

GOOS=${GOOS:-linux}
GOARCH=${GOARCH:-amd64}

if CGO_ENABLED=0 GO111MODULE=on GOOS="${GOOS}" GOARCH="${GOARCH}" GOFIPS140="${GOFIPS140}" go build \
-mod="vendor" \
-a \
${GO_COVER_FLAGS} \
-ldflags " \
-X ${REPO}/pkg/version.Version=${VERSION} \
-X ${REPO}/pkg/version.GitSHA=${GIT_SHA} \
Expand Down
3 changes: 3 additions & 0 deletions dev/image_build_universal.sh
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,9 @@ if [[ -n "${GCFLAGS:-}" ]]; then
DOCKER_CMD="${DOCKER_CMD} --build-arg GCFLAGS='${GCFLAGS}'"
fi

# Append GO_COVER build arg: GO_COVER=yes builds coverage-instrumented binaries (see pkg/util/coverage).
DOCKER_CMD="${DOCKER_CMD} --build-arg GO_COVER=${GO_COVER:-}"

# Append repo push
if [[ "${DOCKERHUB_PUBLISH}" == "yes" ]]; then
DOCKER_CMD="${DOCKER_CMD} --push"
Expand Down
37 changes: 37 additions & 0 deletions dev/run_coverage_report.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
#!/bin/bash
# Local Go coverage totals: unit tests + (optional) e2e, merged.
#
# dev/run_coverage_report.sh [e2e_dir]
#
# e2e_dir is the output of `tests/e2e/coverage.sh collect <e2e_dir>` (default _coverage_/e2e).
# Without it only unit coverage is reported. Outputs go to _coverage_/ (override with COVER_DIR).
set -euo pipefail

CUR_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" >/dev/null 2>&1 && pwd)"
cd "${CUR_DIR}/.."

COVER_DIR="$(pwd)/${COVER_DIR:-_coverage_}"
E2E_DIR="${1:-${COVER_DIR}/e2e}"

rm -rf "${COVER_DIR}/unit" "${COVER_DIR}/merged"
mkdir -p "${COVER_DIR}/unit" "${COVER_DIR}/merged"

go test -vet=off -race -count=1 -cover -covermode=atomic \
-coverpkg=./pkg/...,./cmd/... ./pkg/... ./cmd/... \
-args -test.gocoverdir="${COVER_DIR}/unit"
go tool covdata textfmt -i="${COVER_DIR}/unit" -o="${COVER_DIR}/unit.out"

# Last line of `go tool cover -func` is "total: (statements) NN.N%".
total() { go tool cover -func="$1" | awk '/^total:/ {print $3}'; }

echo
echo "unit tests: $(total "${COVER_DIR}/unit.out")"

if [[ -d "${E2E_DIR}/covdata" ]]; then
echo "e2e tests: $(total "${E2E_DIR}/e2e.out")"
go tool covdata merge -i="${COVER_DIR}/unit,${E2E_DIR}/covdata" -o="${COVER_DIR}/merged"
go tool covdata textfmt -i="${COVER_DIR}/merged" -o="${COVER_DIR}/total.out"
echo "combined: $(total "${COVER_DIR}/total.out")"
else
echo "e2e tests: n/a (no ${E2E_DIR}/covdata, run tests/e2e/coverage.sh collect ${E2E_DIR})"
fi
2 changes: 2 additions & 0 deletions dockerfile/metrics-exporter/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ ARG BUILDARCH=amd64
ARG GCFLAGS
ARG GOFIPS140
ARG GIT_SHA
ARG GO_COVER

# Install required packages
RUN apt-get update && \
Expand All @@ -37,6 +38,7 @@ ENV GOARCH="${TARGETARCH}"
ENV GCFLAGS="${GCFLAGS}"
ENV GOFIPS140="${GOFIPS140}"
ENV GIT_SHA="${GIT_SHA}"
ENV GO_COVER="${GO_COVER}"

# Build operator binary with explicitly specified output
RUN METRICS_EXPORTER_BIN=/tmp/metrics-exporter bash -xe ./dev/go_build_metrics_exporter.sh
Expand Down
2 changes: 2 additions & 0 deletions dockerfile/operator/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ ARG BUILDARCH=amd64
ARG GCFLAGS
ARG GOFIPS140
ARG GIT_SHA
ARG GO_COVER

# Install required packages
RUN apt-get update && \
Expand All @@ -37,6 +38,7 @@ ENV GOARCH="${TARGETARCH}"
ENV GCFLAGS="${GCFLAGS}"
ENV GOFIPS140="${GOFIPS140}"
ENV GIT_SHA="${GIT_SHA}"
ENV GO_COVER="${GO_COVER}"

# Build operator binary with explicitly specified output
RUN OPERATOR_BIN=/tmp/clickhouse-operator bash -xe ./dev/go_build_operator.sh
Expand Down
89 changes: 89 additions & 0 deletions pkg/util/coverage/coverage.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
// Copyright 2019 Altinity Ltd and/or its affiliates. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// Package coverage lets long-running binaries built with "go build -cover -covermode=atomic"
// write their coverage data while they run. Go itself writes counters only on a clean exit,
// but the operator and metrics-exporter are pods that get deleted and restarted by tests.
package coverage

import (
"context"
"os"
"runtime/coverage"
"sync"
"time"

log "github.com/altinity/clickhouse-operator/pkg/announcer"
)

const (
// coverDirEnvName is the standard Go env var naming the directory for coverage data
coverDirEnvName = "GOCOVERDIR"
// flushIntervalEnvName overrides defaultFlushInterval, value is time.ParseDuration format
flushIntervalEnvName = "GOCOVER_FLUSH_INTERVAL"
defaultFlushInterval = 10 * time.Second
)

// Start flushes coverage counters into $GOCOVERDIR every $GOCOVER_FLUSH_INTERVAL
// and once more when ctx is done. wg tracks the flushing goroutine, so the caller can wait for the final flush.
// It does nothing when GOCOVERDIR is empty or the binary is not built with -cover.
func Start(ctx context.Context, wg *sync.WaitGroup) {
dir := os.Getenv(coverDirEnvName)
if dir == "" {
return
}
if err := os.MkdirAll(dir, 0777); err != nil {
log.Warning("coverage: unable to create %s: %v", dir, err)
return
}
if err := coverage.WriteMetaDir(dir); err != nil {
// Binary is not built with -cover, nothing to collect
return
}

flushInterval := defaultFlushInterval
if value := os.Getenv(flushIntervalEnvName); value != "" {
if parsed, err := time.ParseDuration(value); err == nil && parsed > 0 {
flushInterval = parsed
}
}

wg.Add(1)
go func() {
defer wg.Done()
ticker := time.NewTicker(flushInterval)
defer ticker.Stop()
for {
select {
case <-ticker.C:
flushCoverageCounters(dir)
case <-ctx.Done():
flushCoverageCounters(dir)
return
}
}
}()
}

// flushCoverageCounters writes counters collected so far into a new file in dir and zeroes them,
// so that summing all the files of the dir gives exact totals.
func flushCoverageCounters(dir string) {
if err := coverage.WriteCountersDir(dir); err != nil {
log.Warning("coverage: unable to write counters to %s: %v", dir, err)
return
}
if err := coverage.ClearCounters(); err != nil {
log.Warning("coverage: unable to clear counters (build with -covermode=atomic): %v", err)
}
}
Loading
0