Skip to content
Merged
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
4 changes: 4 additions & 0 deletions .github/workflows/ci.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,11 @@ jobs:
cache: true

- name: Generate, vet, and test
# ubuntu-latest ships shellcheck; the flag turns TestShellcheck's skip into a failure if it ever goes missing.
env:
KARKIVE_REQUIRE_SHELLCHECK: "1"
run: |
shellcheck --version
make generate manifests fmt vet test
git diff --exit-code

Expand Down
5 changes: 5 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,11 @@ run: generate manifests
test: generate
go test ./...

# Pipeline scripts only: shellcheck (when installed) plus the script behaviour tests. CI runs the same test with shellcheck required.
.PHONY: test-scripts
test-scripts:
go test ./internal/pipeline/

.PHONY: fmt
fmt:
go fmt ./...
Expand Down
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -508,13 +508,14 @@ kubectl apply -f config/samples/karkive_v1alpha1_backup.yaml
| `make generate` | Deepcopy for `api/` |
| `make manifests` | CRDs, RBAC and webhook manifests, plus the chart's CRD templates |
| `make test` | `go test ./...` |
| `make test-scripts` | Pipeline scripts only: `shellcheck` on each script as the operator composes it (skipped when `shellcheck` is not installed) and the script behaviour tests, which run the scripts under `dash`/`bash` with stub tools |
| `make fmt vet` | `go fmt` / `go vet` |
| `make docker-build` | Operator image (`IMG`, default `ghcr.io/code2z/karkive:dev`) |
| `make install` / `uninstall` | Apply / delete CRDs |

CI:

- **CI** (`ci.yaml`, pushes to `main`, tags `v*` and PRs; `docs/` changes skip it): `make generate manifests fmt vet test`, failing on a dirty tree, then builds the `linux/amd64` operator image and lints the chart. Pushes to `main` publish `ghcr.io/code2z/karkive:latest`, `main` and `sha-<sha>`; tags `v*` publish semver tags and push the chart to `oci://ghcr.io/code2z/charts`.
- **CI** (`ci.yaml`, pushes to `main`, tags `v*` and PRs; `docs/` changes skip it): `make generate manifests fmt vet test`, failing on a dirty tree, with `shellcheck` required, then builds the `linux/amd64` operator image and lints the chart. Pushes to `main` publish `ghcr.io/code2z/karkive:latest`, `main` and `sha-<sha>`; tags `v*` publish semver tags and push the chart to `oci://ghcr.io/code2z/charts`.
- **Runners** (`runners.yaml`): builds `karkive-runner-<engine>` only when `runner/<engine>/` (or the shared rclone installer) changes. The tag comes from `runner/<engine>/TAG`, `<client><version>-rclone<version>-r<revision>`. A published tag is never overwritten, so bump a version or the `-r` revision with every Dockerfile change, then update `internal/config/config.go` and `defaults.runnerImages` in `values.yaml`.
- **Pages** (`pages.yaml`): deploys `docs/` to [karkive.ir](https://karkive.ir).

Expand Down
3 changes: 2 additions & 1 deletion TODO.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@

## Tests

- [ ] envtest for CronJob apply; shellcheck + bats for pipeline scripts
- [ ] envtest for CronJob apply

## Done

Expand Down Expand Up @@ -116,6 +116,7 @@
- [x] The Stream scratch check does the byte arithmetic in bash, not awk: the mawk in the redis runner printed free space above 2^31 as `5.23745e+10`, so Redis restores skipped the check
- [x] Make S3 sync optional (`spec.s3.enabled`, default true). When false: skip the `s3-sync` container, do not require S3 secret keys or endpoint/bucket. Encrypt still writes `retained/` on the PVC.
- [x] Pick the latest restore object by S3 LastModified (rclone `lsf --format tp`), not by name. Stream object names carry seconds
- [x] Script checks in Go instead of bats: `TestShellcheck` lints each script as the operator composes it (helper + stage body, `sh` for Stage and `bash` for Stream) and maps findings back to the source file and line; CI requires shellcheck. Behaviour tests run the shared helpers under `dash`/`bash` with stub tools (step markers, `.step-failed` on error, log file, `truthy`, zstd level, decompress by suffix, `s3_latest` by modification time, best-effort `s3_prune`)

### Speed and size (Stream mode)

Expand Down
212 changes: 212 additions & 0 deletions internal/pipeline/helpers_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,212 @@
package pipeline

import (
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
)

// runHelpers runs body after a helper script under shell, with stub commands first on PATH. Each stub is a /bin/sh script body.
func runHelpers(t *testing.T, shell, helper, body string, env map[string]string, stubs map[string]string) (string, error) {
t.Helper()
sh, err := exec.LookPath(shell)
if err != nil {
t.Skipf("%s not found", shell)
}
bin := t.TempDir()
for name, script := range stubs {
if err := os.WriteFile(filepath.Join(bin, name), []byte("#!/bin/sh\n"+script+"\n"), 0o755); err != nil {
t.Fatal(err)
}
}
cmd := exec.Command(sh, "-c", helper+"\n"+body+"\n")
cmd.Env = []string{"PATH=" + bin + ":" + os.Getenv("PATH")}
for k, v := range env {
cmd.Env = append(cmd.Env, k+"="+v)
}
out, err := cmd.CombinedOutput()
return string(out), err
}

// stageShell is the /bin/sh of the Debian-based images (dash), or sh where dash is missing.
func stageShell(t *testing.T) string {
t.Helper()
if _, err := exec.LookPath("dash"); err == nil {
return "dash"
}
return "sh"
}

func exitCode(err error) int {
if err == nil {
return 0
}
if e, ok := err.(*exec.ExitError); ok {
return e.ExitCode()
}
return -1
}

func fileExists(path string) bool {
_, err := os.Stat(path)
return err == nil
}

func TestStagePipelineInitMarksFailureOnNonZeroExit(t *testing.T) {
for _, tc := range []struct {
exit string
wantFailed bool
}{{"exit 3", true}, {"exit 0", false}} {
work := t.TempDir()
_, err := runHelpers(t, stageShell(t), CommonScript(), "pipeline_init\n"+tc.exit, map[string]string{"WORKDIR": work}, nil)
if tc.wantFailed && exitCode(err) != 3 {
t.Errorf("%s: exit %d, want 3", tc.exit, exitCode(err))
}
if got := fileExists(filepath.Join(work, ".step-failed")); got != tc.wantFailed {
t.Errorf("%s: .step-failed written=%v, want %v", tc.exit, got, tc.wantFailed)
}
}
}

func TestStagePipelineInitNeedsADirectory(t *testing.T) {
out, err := runHelpers(t, stageShell(t), CommonScript(), "pipeline_init\necho after", nil, nil)
if exitCode(err) != 1 || strings.Contains(out, "after") || !strings.Contains(out, "STEP_DIR, DATA_DIR, or WORKDIR required") {
t.Errorf("exit %d, output:\n%s", exitCode(err), out)
}
}

func TestStageUnknownEncryptionMethodFails(t *testing.T) {
out, err := runHelpers(t, stageShell(t), CommonScript(), "echo after", map[string]string{"ENCRYPTION_METHOD": "rot13"}, nil)
if exitCode(err) != 1 || strings.Contains(out, "after") || !strings.Contains(out, "unknown ENCRYPTION_METHOD rot13") {
t.Errorf("exit %d, output:\n%s", exitCode(err), out)
}
}

func TestStageWaitForReturnsOnMarker(t *testing.T) {
work := t.TempDir()
if err := os.WriteFile(filepath.Join(work, ".step-dump-done"), nil, 0o644); err != nil {
t.Fatal(err)
}
out, err := runHelpers(t, stageShell(t), CommonScript(), `pipeline_init
wait_for "$WORKDIR/.step-dump-done" dump
echo after`, map[string]string{"WORKDIR": work}, map[string]string{"sleep": "exit 0"})
if err != nil || !strings.Contains(out, "after") {
t.Errorf("err=%v, output:\n%s", err, out)
}
}

func TestStageWaitForAbortsWhenAPeerFailed(t *testing.T) {
work := t.TempDir()
if err := os.WriteFile(filepath.Join(work, ".step-failed"), nil, 0o644); err != nil {
t.Fatal(err)
}
out, err := runHelpers(t, stageShell(t), CommonScript(), `pipeline_init
wait_for "$WORKDIR/.step-dump-done" dump
echo after`, map[string]string{"WORKDIR": work}, map[string]string{"sleep": "exit 0"})
if exitCode(err) != 1 || strings.Contains(out, "after") || !strings.Contains(out, "peer stage failed") {
t.Errorf("exit %d, output:\n%s", exitCode(err), out)
}
}

func TestStageAlreadyDoneExitSkipsWork(t *testing.T) {
work := t.TempDir()
marker := filepath.Join(work, ".step-fetch-done")
if err := os.WriteFile(marker, nil, 0o644); err != nil {
t.Fatal(err)
}
out, err := runHelpers(t, stageShell(t), CommonScript(), `pipeline_init
already_done_exit "$MARKER" fetch
echo work`, map[string]string{"WORKDIR": work, "MARKER": marker}, nil)
if err != nil || strings.Contains(out, "work") {
t.Errorf("err=%v, output:\n%s", err, out)
}
if fileExists(filepath.Join(work, ".step-failed")) {
t.Error("a skipped stage must not write .step-failed")
}
}

func TestStageLogFileOnTheVolume(t *testing.T) {
root := t.TempDir()
for _, tc := range []struct {
enabled string
want bool
}{{"true", true}, {"yes", true}, {"1", true}, {"false", false}, {"", false}} {
logFile := filepath.Join(root, "logs", "pod.log")
_ = os.Remove(logFile)
_, err := runHelpers(t, stageShell(t), CommonScript(), `pipeline_init
log "hello"`, map[string]string{"WORKDIR": filepath.Join(root, "pod"), "WORKDIR_ROOT": root, "HOSTNAME": "pod", "LOG_FILE_ENABLED": tc.enabled}, nil)
if err != nil {
t.Fatalf("LOG_FILE_ENABLED=%q: %v", tc.enabled, err)
}
b, _ := os.ReadFile(logFile)
if got := strings.Contains(string(b), "hello"); got != tc.want {
t.Errorf("LOG_FILE_ENABLED=%q: logged to file=%v, want %v", tc.enabled, got, tc.want)
}
}
}

func TestStreamTruthy(t *testing.T) {
out, err := runHelpers(t, "bash", streamCommon(t), `for v in 1 yes YES true TRUE 0 no false True ""; do
if truthy "$v"; then echo "$v=y"; else echo "$v=n"; fi
done`, nil, nil)
if err != nil {
t.Fatalf("%v\n%s", err, out)
}
want := "1=y\nyes=y\nYES=y\ntrue=y\nTRUE=y\n0=n\nno=n\nfalse=n\nTrue=n\n=n\n"
if out != want {
t.Errorf("got:\n%s\nwant:\n%s", out, want)
}
}

func TestStreamZstdLevelFallsBackToThree(t *testing.T) {
for in, want := range map[string]string{"": "3", "9": "9", "19": "19", "-1": "3", "fast": "3", "3 ; rm": "3"} {
out, err := runHelpers(t, "bash", streamCommon(t), "zstd_level", map[string]string{"COMPRESSION_LEVEL": in}, nil)
if err != nil || strings.TrimSpace(out) != want {
t.Errorf("COMPRESSION_LEVEL=%q: got %q (err %v), want %q", in, out, err, want)
}
}
}

func TestStreamDecompressBySuffix(t *testing.T) {
stubs := map[string]string{
"zstd": "cat >/dev/null; echo zstd",
"pigz": "exit 1", // missing pigz: falls back to gzip
"gzip": "cat >/dev/null; echo gzip",
}
for obj, want := range map[string]string{
"mysqldump-db-2026.sql.zst.gpg": "zstd",
"redis-2026.rdb.zst.age": "zstd",
"mysqldump-db-2026.sql.gz.gpg": "gzip",
"pg_dump-db-2026.dump.gpg": "raw",
} {
out, err := runHelpers(t, "bash", streamCommon(t), `echo raw | decompress_stream "$OBJ"`, map[string]string{"OBJ": obj}, stubs)
if err != nil || strings.TrimSpace(out) != want {
t.Errorf("%s: got %q (err %v), want %q", obj, out, err, want)
}
}
}

func TestStreamS3LatestByModTimeNotName(t *testing.T) {
stubs := map[string]string{"rclone": `printf '%s\n' '2026-12-02 03:00:00|pg_dump-app-2026-11-30-03-00-00.dump.gpg' '2026-12-01 03:00:00|pg_dump-app-2026-12-01-03-00-00.dump.gpg'`}
out, err := runHelpers(t, "bash", streamCommon(t), `S3_PREFIX=s3:bucket/app
s3_latest 'pg_dump-*'`, nil, stubs)
if err != nil || strings.TrimSpace(out) != "pg_dump-app-2026-11-30-03-00-00.dump.gpg" {
t.Errorf("got %q (err %v)", out, err)
}
}

func TestStreamS3PruneIsBestEffort(t *testing.T) {
run := t.TempDir()
stubs := map[string]string{"rclone": `case "$1" in
lsf) echo "access denied" >&2; exit 1 ;;
*) echo "unexpected rclone $1" >&2; exit 2 ;;
esac`}
out, err := runHelpers(t, "bash", streamCommon(t), `S3_PREFIX=s3:bucket/app
s3_prune 'pg_dump-*'
echo after`, map[string]string{"RUN_DIR": run}, stubs)
if err != nil || !strings.Contains(out, "WARN: listing for prune failed") || !strings.Contains(out, "access denied") || !strings.Contains(out, "after") || strings.Contains(out, "unexpected") {
t.Errorf("err=%v, output:\n%s", err, out)
}
}
4 changes: 3 additions & 1 deletion internal/pipeline/scripts/backup/compress.sh
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
set -eu
umask 0002
STAGE=compress
STAGE='compress'
# Shared PVC is reused across Jobs; scope scratch to this pod
# so peers never see stale .step-* markers from a prior run.
DATA_ROOT="${DATA_DIR:-${PGDUMP_DIR:?DATA_DIR or PGDUMP_DIR required}}"
Expand All @@ -16,6 +16,8 @@ case "${DUMP_PREFIX}" in
pvcdump) PLAIN_GLOB='pvcdump-*.tar' ;;
*) PLAIN_GLOB='pg_dump-*.pgdump' ;;
esac
# PLAIN_GLOB is a glob and must expand.
# shellcheck disable=SC2086
ls "${DATA_DIR}"/${PLAIN_GLOB} >/dev/null 2>&1 || {
log "ERROR: no ${PLAIN_GLOB} after dump marker" >&2
mark_failed
Expand Down
2 changes: 2 additions & 0 deletions internal/pipeline/scripts/backup/encrypt.sh
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ case "${DUMP_PREFIX}" in
pvcdump) GZ_GLOB='pvcdump-*.tar.gz' ;;
*) GZ_GLOB='pg_dump-*.pgdump.gz' ;;
esac
# GZ_GLOB is a glob and must expand.
# shellcheck disable=SC2086
ls "${DATA_DIR}"/${GZ_GLOB} >/dev/null 2>&1 || {
log "ERROR: no ${GZ_GLOB} after compress marker" >&2
mark_failed
Expand Down
4 changes: 3 additions & 1 deletion internal/pipeline/scripts/common.sh
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
# shellcheck disable=SC3028
# SC3028 above, for every Stage script: HOSTNAME is not a POSIX sh variable, but the container runtime sets it to the pod name, which names each pod's scratch directory.
# Shared pipeline helpers. Callers set STAGE and DATA_DIR (backup) or WORKDIR
# (restore), then pipeline_init.

Expand Down Expand Up @@ -55,7 +57,7 @@ pipeline_init() {
chmod 666 "${LOG_FILE}" 2>/dev/null || true
fi
fi
trap 'ec=$?; [ "$ec" -eq 0 ] || mark_failed' EXIT
trap '[ "$?" -eq 0 ] || mark_failed' EXIT
}

prune_pipeline_logs() {
Expand Down
2 changes: 2 additions & 0 deletions internal/pipeline/scripts/restore/mysqlrestore.sh
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,8 @@ FILTERED="${WORKDIR}/dump.filtered.sql"
echo "SET SESSION unique_checks=0;"
echo "SET SESSION foreign_key_checks=0;"
echo "SET SESSION autocommit=0;"
# The backticks quote MariaDB identifiers; nothing here should expand.
# shellcheck disable=SC2016
sed -E \
-e '/^SET[[:space:]]+@@GLOBAL\.GTID_PURGED/d' \
-e '/^SET[[:space:]]+@@SESSION\.SQL_LOG_BIN/d' \
Expand Down
2 changes: 2 additions & 0 deletions internal/pipeline/scripts/stream/common.sh
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,8 @@ stream_init() {
: > "${LOG_FILE}"
fi
encryption_init
# rc is assigned inside the trap string.
# shellcheck disable=SC2154
trap 'rc=$?; rm -rf "${RUN_DIR}"; [ "$rc" -eq 0 ] || log "ERROR: failed with exit ${rc}"; exit "$rc"' EXIT
}

Expand Down
4 changes: 4 additions & 0 deletions internal/pipeline/scripts/stream/restore.sh
Original file line number Diff line number Diff line change
Expand Up @@ -211,6 +211,8 @@ restore_mariadb() {
{
echo "SET SESSION unique_checks=0; SET SESSION foreign_key_checks=0; SET SESSION autocommit=0;"
# Stage-mode dumps use --databases (CREATE DATABASE + USE <source>): drop those so the data lands in the target name.
# The backticks quote MariaDB identifiers; nothing here should expand.
# shellcheck disable=SC2016
fetch | decompress_stream "${OBJ}" | sed -E \
-e '/^CREATE DATABASE /d' \
-e '/^USE `[^`]*`;$/d' \
Expand Down Expand Up @@ -324,6 +326,8 @@ redis_push_to_target() {
t=$(date +%s)
log "db${db}: pushing ${n} keys to ${REDIS_HOST}:${REDIS_PORT:-6379} with MIGRATE"
if ! {
# RESP framing: $6 is a literal bulk-string length, not a variable.
# shellcheck disable=SC2016
printf '*2\r\n$6\r\nSELECT\r\n$%d\r\n%s\r\n' "${#db}" "${db}"
local_redis -n "${db}" --scan --count 1000 < /dev/null | redis_migrate_resp "${db}"
} | local_redis --pipe --pipe-timeout 0 > "${RUN_DIR}/push.out" 2> "${RUN_DIR}/push.err"; then
Expand Down
Loading