Repository navigation
Expand file tree
/
Copy pathtest.sh
More file actions
executable file
·1987 lines (1900 loc) · 116 KB
/
Copy pathtest.sh
File metadata and controls
executable file
·1987 lines (1900 loc) · 116 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env bash
# The one command: checks, unit tests, image build, and the itest against a
# local k3s node. CI runs this same script; the only difference is how the
# tools below got installed (see .github/workflows).
#
# ./test.sh everything
# ./test.sh checks checks and unit tests only
# ./test.sh itest skip checks and unit tests
# ./test.sh up provision the cluster and deploy the agent, the
# compactor and the sample workloads, print how to
# look around; no checks, no assertions, nothing purged.
# ./test.sh host only the host phase (HOST_MODE.md) against the running
# qemu cluster: itest/host/phase.sh. It also runs at
# the end of the full run, on the qemu backend.
#
# Env:
# SKIP_BUILD=1 reuse target/images/node-agent.tar and
# target/images/compactor-oci
# HOST_TARBALL=file run the host phase with this tarball instead of
# building one (HOST_BUILD_ARGS: extra buildx flags;
# more in itest/host/phase.sh)
# IMAGE_REF=ref load a published image instead of building
# CLUSTER_CONFIG=dir y-cluster config dir (default: itest/cluster/qemu with
# /dev/kvm, itest/cluster/docker otherwise)
# CONTEXT, S3_PORT must match CLUSTER_CONFIG when overriding it
# BUILDKIT_PORT, LOGS_PORT, PUT_LOGS_PORT, SERVE_LOGS_PORT, LOCAL_PORT
# this host's ports for the port-forwards to the
# cluster's BuildKit (default 18234), the logs API of
# the compactor (18080), of the put compactor (18081)
# and of the serve pod (18082), and the host phase's
# gateway (17071, itest/host/run.sh). Two itests on
# one machine need their own, as well as their own
# CLUSTER_CONFIG, CONTEXT and S3_PORT; a port that
# already answers fails the run instead of reading
# the other itest's cluster.
# IMAGE_BUILD_ARGS extra docker buildx flags, e.g. a CI cache
# KUBEBUILDER_ASSETS etcd, kube-apiserver and kubectl at ENVTEST_K8S for
# tools/y-obs's tests (default: setup-envtest
# downloads them; the itest's are the cluster's release)
# IMAGE_BUILDER docker (default when docker is installed), buildkit
# (buildctl against BUILDKIT_HOST, the default when it is
# set; with BUILDKIT_TLS_DIR when that is set too, as
# eval "$(y-cluster dockerhost env)" sets both) or cluster (buildctl
# against a rootless BuildKit pod in the itest cluster,
# default without docker: no daemon on the host at all)
#
# The cluster is left running; y-cluster teardown -c <config dir> removes it.
set -euo pipefail
cd "$(dirname "$0")"
CONTEXT=${CONTEXT:-node-agent}
IMAGE=node-agent:itest
BUCKET=node-agent
# the multi-cluster phase's (further down), on the same gateway
MULTI_BUCKET=node-agent-multi
CLUSTER=itest
# the second compactor, in spool mode, and the stock Fluent Bit that
# uploads to its put endpoint (itest/compactor-put)
PUT_NS=observability-put
PUT_CLUSTER=itest-put
S3_PORT=${S3_PORT:-30070}
# this host's ends of the port-forwards (the Env above)
BUILDKIT_PORT=${BUILDKIT_PORT:-18234}
LOGS_PORT=${LOGS_PORT:-18080}
PUT_LOGS_PORT=${PUT_LOGS_PORT:-18081}
SERVE_LOGS_PORT=${SERVE_LOGS_PORT:-18082}
export LOCAL_PORT=${LOCAL_PORT:-17071}
# the compactor's parquet keys (itest/compactor), kept across runs so that
# a bucket left by `up` stays readable: PARQUET_KEYS_DIR=$PARQUET_KEYS local/blobs.sh
PARQUET_KEYS=target/itest/parquet-keys
export KUBECONFIG=$PWD/itest/cluster/kubeconfig
KUBECTL="kubectl --context=$CONTEXT"
MODE=${1:-all}
case "$MODE" in (all|checks|itest|up|host) ;; (*) echo "usage: $0 [checks|itest|up|host]" >&2; exit 2;; esac
[ "$MODE" != host ] || exec env CONTEXT="$CONTEXT" CLUSTER_CONFIG="${CLUSTER_CONFIG:-itest/cluster/qemu}" itest/host/phase.sh
# one exit trap for the whole script: a second `trap ... EXIT` replaces the
# first, which would leave the BuildKit port-forward running
BUILDKIT_PF=""
INIT=""
# apiserver-at in the background (at_serve below)
AT_PID=""
# the port-forwards to the logs API (logs_forward below)
LOGS_PF_PIDS=()
cleanup() {
[ -z "$BUILDKIT_PF" ] || kill "$BUILDKIT_PF" 2>/dev/null || true
[ -z "$AT_PID" ] || kill "$AT_PID" 2>/dev/null || true
[ ${#LOGS_PF_PIDS[@]} -eq 0 ] || kill "${LOGS_PF_PIDS[@]}" 2>/dev/null || true
# the assertions' temporary files, all named after INIT
[ -z "$INIT" ] || rm -f "$INIT" "$INIT".*
}
trap cleanup EXIT
phase() { printf '\n==> %s\n' "$*"; }
fail() { echo "FAIL: $*" >&2; exit 1; }
# port_free <port> <variable>: nothing listens on 127.0.0.1:<port>, else
# fail: a port-forward to it could not bind, and the run would read
# whatever answers there, such as another itest's cluster
port_free() {
if (exec 3<>"/dev/tcp/127.0.0.1/$1") 2>/dev/null; then
fail "127.0.0.1:$1 is in use (another itest?); set $2 to a free port"
fi
}
need() {
command -v "$1" >/dev/null 2>&1 || fail "missing tool: $1 ($2)"
}
# The Kubernetes release of the API servers in tools/y-obs's
# acceptance test, the source and apiserver-at both. The itest's
# apiserver-at runs the itest cluster's own release instead, which
# itest/cluster/*/y-cluster-provision.yaml pin to the same minor.
ENVTEST_K8S=1.37.0
SETUP_ENVTEST=v0.25.2
# setup_envtest <release>: the path of the release's API server binaries,
# downloaded once into setup-envtest's cache. They come from GitHub's
# release assets, which answer 5xx at times (seen: a 504 on a CI run), so
# up to three attempts, 15 s and 30 s apart.
setup_envtest() {
local attempt path
for attempt in 1 2 3; do
if path=$(GOFLAGS='' go run "sigs.k8s.io/controller-runtime/tools/setup-envtest@$SETUP_ENVTEST" use "$1" -p path); then
echo "$path"
return 0
fi
if [ "$attempt" -lt 3 ]; then
echo "setup-envtest: attempt $attempt for Kubernetes $1 failed, retrying in $((attempt * 15)) s" >&2
sleep $((attempt * 15))
fi
done
return 1
}
# envtest_assets: KUBEBUILDER_ASSETS, downloaded once into setup-envtest's
# cache unless already set
envtest_assets() {
if [ -z "${KUBEBUILDER_ASSETS:-}" ]; then
KUBEBUILDER_ASSETS=$(setup_envtest "$ENVTEST_K8S") \
|| fail "setup-envtest could not provide Kubernetes $ENVTEST_K8S"
fi
export KUBEBUILDER_ASSETS
}
# run_pod <namespace> <name> <image> <overrides JSON, or ""> <command...>:
# a pod that runs to completion; its log is in POD_LOG, and it returns
# non-zero unless the pod succeeded
run_pod() {
local ns=$1 name=$2 image=$3 overrides=$4 phase deadline
shift 4
local args=(--restart=Never --image="$image")
[ -z "$overrides" ] || args+=(--overrides="$overrides")
$KUBECTL -n "$ns" delete pod "$name" --ignore-not-found >/dev/null 2>&1
$KUBECTL -n "$ns" run "$name" "${args[@]}" --command -- "$@" >/dev/null
deadline=$((SECONDS + 300))
while :; do
phase=$($KUBECTL -n "$ns" get pod "$name" -o jsonpath='{.status.phase}')
case "$phase" in (Succeeded|Failed) break;; esac
[ $SECONDS -lt $deadline ] || fail "pod $ns/$name still $phase after 300s"
sleep 2
done
POD_LOG=$($KUBECTL -n "$ns" logs "pod/$name")
$KUBECTL -n "$ns" delete pod "$name" >/dev/null
[ "$phase" = Succeeded ]
}
# spool_sh <command>: a shell command, without double quotes, in a pod
# that mounts the put compactor's spool at /spool (ReadWriteOnce: pods on
# its node share it)
spool_sh() {
run_pod "$PUT_NS" spool-sh busybox:1.37 "{\"apiVersion\": \"v1\", \"spec\": {\"containers\": [{
\"name\": \"spool-sh\", \"image\": \"busybox:1.37\", \"command\": [\"sh\", \"-c\", \"$1\"],
\"volumeMounts\": [{\"name\": \"spool\", \"mountPath\": \"/spool\"}]}],
\"volumes\": [{\"name\": \"spool\", \"persistentVolumeClaim\": {\"claimName\": \"blobs-compactor-spool\"}}]}}" sh -c "$1"
}
need kubectl "https://kubernetes.io/docs/tasks/tools/"
# ---------------------------------------------------------------- checks --
if [ "$MODE" = all ] || [ "$MODE" = checks ]; then
need go "https://go.dev/dl/"
need shellcheck "https://github.com/koalaman/shellcheck"
phase "checks: shell"
shellcheck -x -P SCRIPTDIR test.sh compactor/build.sh local/kubectl-at.sh operator-to-annotations/crds/vendor.sh tools/y-obs/release.sh
# tools/y-obs's acceptance test runs a source API server, the
# watcher, compactor/sql/ in DuckDB and apiserver-at
need duckdb "https://duckdb.org/docs/installation/"
envtest_assets
for mod in images/fluentbit/plugins/cri_scrape images/fluentbit/plugins/k8s_objects images/blobs-to-prometheus \
images/operator-to-annotations tools/rules-manifest tools/y-obs; do
phase "checks: go ($mod)"
(
cd "$mod"
unformatted=$(gofmt -l .)
[ -z "$unformatted" ] || fail "gofmt: $unformatted"
# the code without its tests, which vet and test compile with them
bin=$(mktemp -d)
go build -o "$bin" ./...
rm -rf "$bin"
go vet ./...
go test ./...
)
done
phase "checks: host mode"
need jq "https://jqlang.github.io/jq/"
need python3 "python3"
shellcheck images/fluentbit/host/*.sh itest/host/*.sh itest/host-docker/*.sh
images/fluentbit/host/test-heartbeat.sh
images/fluentbit/host/test-launch.sh
python3 -c 'import ast, sys; ast.parse(open(sys.argv[1]).read())' itest/host/s3-recorder.py
kubectl kustomize itest/host >/dev/null
phase "checks: kustomize"
kubectl kustomize agent >/dev/null
kubectl kustomize k8sagent >/dev/null
kubectl kustomize itest/k8s >/dev/null
kubectl kustomize itest/k8s-docker >/dev/null
kubectl kustomize compactor/deploy/release >/dev/null
kubectl kustomize itest/compactor >/dev/null
kubectl kustomize itest/compactor-put >/dev/null
kubectl kustomize itest/compactor-multi >/dev/null
kubectl kustomize compactor/deploy/spool-networkpolicy >/dev/null
kubectl kustomize itest/buildkit >/dev/null
operator-to-annotations/crds/vendor.sh check
kubectl kustomize operator-to-annotations >/dev/null
kubectl kustomize itest/operator-to-annotations >/dev/null
kubectl kustomize itest/operator-to-annotations/workloads >/dev/null
fi
[ "$MODE" != checks ] || exit 0
need y-cluster "https://github.com/Yolean/y-cluster/releases"
if [ "$MODE" != up ]; then
need duckdb "https://duckdb.org/docs/installation/"
need curl "https://curl.se/download.html"
# the assertions run compactor/sql/, which the compactor runs embedded at
# this version; another CLI version tests the contract on another engine
want=$(sed -n 's/^DUCKDB_VERSION=//p' compactor/build.env)
got=$(duckdb --version | awk '{print $1}')
[ "$got" = "$want" ] || echo "warning: duckdb $got, the compactor embeds $want (compactor/build.env)" >&2
fi
# ----------------------------------------------------------------- build --
if [ -z "${IMAGE_BUILDER:-}" ]; then
if [ -n "${BUILDKIT_HOST:-}" ]; then IMAGE_BUILDER=buildkit
elif command -v docker >/dev/null 2>&1; then IMAGE_BUILDER=docker
else IMAGE_BUILDER=cluster; fi
fi
case "$IMAGE_BUILDER" in (docker|buildkit|cluster) ;; (*) fail "IMAGE_BUILDER: docker, buildkit or cluster";; esac
# a BuildKit that wants client certificates (y-cluster dockerhost); exported
# for compactor/build.sh and images/fluentbit/host/build.sh too
if [ "$IMAGE_BUILDER" = buildkit ] && [ -n "${BUILDKIT_TLS_DIR:-}" ]; then
buildctl() { command buildctl --tlsdir "$BUILDKIT_TLS_DIR" "$@"; }
export -f buildctl
fi
BUILD=yes
if [ -n "${IMAGE_REF:-}" ] || { [ "${SKIP_BUILD:-}" = 1 ] && [ -f target/images/node-agent.tar ]; }; then
BUILD=no
elif [ "$IMAGE_BUILDER" = docker ]; then
need docker "https://docs.docker.com/engine/install/"
else
need buildctl "https://github.com/moby/buildkit/releases"
fi
build_image() {
phase "image: build $IMAGE ($IMAGE_BUILDER)"
mkdir -p target/images
if [ -n "${IMAGE_REF:-}" ]; then
echo "IMAGE_REF=$IMAGE_REF, skipping the build"
elif [ "$BUILD" = no ]; then
echo "SKIP_BUILD=1, reusing target/images/node-agent.tar"
elif [ "$IMAGE_BUILDER" = docker ]; then
read -ra build_args <<< "${IMAGE_BUILD_ARGS:-}"
docker buildx build "${build_args[@]}" \
--output "type=oci,dest=target/images/node-agent.tar,name=docker.io/library/$IMAGE" \
images/fluentbit
else
buildctl build --frontend dockerfile.v0 \
--local context=images/fluentbit --local dockerfile=images/fluentbit \
--output "type=oci,dest=target/images/node-agent.tar,name=docker.io/library/$IMAGE"
fi
}
# operator-to-annotations' controller (operator-to-annotations/README.md)
CONTROLLER_IMAGE=operator-to-annotations:itest
build_controller() {
phase "image: build $CONTROLLER_IMAGE ($IMAGE_BUILDER)"
if [ "${SKIP_BUILD:-}" = 1 ] && [ -f target/images/operator-to-annotations.tar ]; then
echo "SKIP_BUILD=1, reusing target/images/operator-to-annotations.tar"
elif [ "$IMAGE_BUILDER" = docker ]; then
docker buildx build \
--output "type=oci,dest=target/images/operator-to-annotations.tar,name=docker.io/library/$CONTROLLER_IMAGE" \
images/operator-to-annotations
else
buildctl build --frontend dockerfile.v0 \
--local context=images/operator-to-annotations --local dockerfile=images/operator-to-annotations \
--output "type=oci,dest=target/images/operator-to-annotations.tar,name=docker.io/library/$CONTROLLER_IMAGE"
fi
}
# BuildKit in the itest cluster, reached through a port-forward, so a host
# with neither docker nor a BuildKit daemon can build
cluster_builder() {
phase "image: BuildKit in $CONTEXT"
$KUBECTL apply -k itest/buildkit >/dev/null
$KUBECTL -n itest-buildkit rollout status deployment/buildkitd --timeout=300s
port_free "$BUILDKIT_PORT" BUILDKIT_PORT
$KUBECTL -n itest-buildkit port-forward deployment/buildkitd "$BUILDKIT_PORT:1234" >/dev/null 2>&1 &
BUILDKIT_PF=$!
export BUILDKIT_HOST=tcp://127.0.0.1:$BUILDKIT_PORT
for _ in $(seq 1 30); do buildctl debug workers >/dev/null 2>&1 && return 0; sleep 1; done
fail "BuildKit in $CONTEXT does not answer on $BUILDKIT_HOST"
}
# The compactor's image comes from its own build script, for this host's
# arch only (compactor/README.md, "The build script"); the release pin is
# build.sh check's business, not the itest's. Without docker, build.sh's
# image-buildkit runs the same steps through buildctl.
COMPACTOR_IMAGE=ghcr.io/yolean/observability-state:build
build_compactor() {
phase "image: build $COMPACTOR_IMAGE ($IMAGE_BUILDER)"
if [ "${SKIP_BUILD:-}" = 1 ] && [ -f target/images/compactor-oci/index.json ]; then
echo "SKIP_BUILD=1, reusing target/images/compactor-oci"
elif [ "$IMAGE_BUILDER" = docker ]; then
PLATFORMS="linux/$(docker version --format '{{.Server.Arch}}')" compactor/build.sh image target/images/compactor-oci
else
PLATFORMS="linux/$(uname -m | sed 's/x86_64/amd64/;s/aarch64/arm64/')" compactor/build.sh image-buildkit target/images/compactor-oci
fi
}
# the cluster builder needs the cluster first; the others build before it
if [ "$IMAGE_BUILDER" != cluster ]; then
build_image
build_compactor
build_controller
fi
# --------------------------------------------------------------- cluster --
phase "cluster: $CONTEXT"
if [ -z "${CLUSTER_CONFIG:-}" ]; then
if [ -e /dev/kvm ] && command -v qemu-system-x86_64 >/dev/null 2>&1; then
CLUSTER_CONFIG=itest/cluster/qemu
else
CLUSTER_CONFIG=itest/cluster/docker
fi
fi
if y-cluster detect --context "$CONTEXT" >/dev/null 2>&1; then
echo "reusing running cluster"
else
y-cluster provision -c "$CLUSTER_CONFIG"
fi
BACKEND=$(y-cluster detect --context "$CONTEXT")
echo "backend: $BACKEND"
$KUBECTL get nodes -o wide
# the docker node has no journal; see itest/k8s-docker
if [ "$BACKEND" = docker ]; then
MANIFESTS=itest/k8s-docker
else
MANIFESTS=itest/k8s
fi
if [ "$IMAGE_BUILDER" = cluster ]; then
if [ "$BUILD" = yes ] || [ "${SKIP_BUILD:-}" != 1 ] || [ ! -f target/images/compactor-oci/index.json ] \
|| [ ! -f target/images/operator-to-annotations.tar ]; then
cluster_builder
fi
build_image
build_compactor
build_controller
fi
phase "cluster: load image"
# images load skips refs that already exist in containerd, and the tag is
# fixed, so drop the previous build's ref first (running pods keep their
# snapshots; the rollout restart below moves them to the new one)
# (stdin closed: on the docker backend ctr runs through docker exec -i)
y-cluster ctr --context "$CONTEXT" -- -n k8s.io images rm "docker.io/library/$IMAGE" </dev/null >/dev/null 2>&1 || true
if [ -n "${IMAGE_REF:-}" ]; then
y-cluster images load --context "$CONTEXT" "$IMAGE_REF" </dev/null
y-cluster ctr --context "$CONTEXT" -- -n k8s.io images tag "$IMAGE_REF" "docker.io/library/$IMAGE" </dev/null >/dev/null
else
y-cluster images load --context "$CONTEXT" ./target/images/node-agent.tar
fi
y-cluster ctr --context "$CONTEXT" -- -n k8s.io images rm "$COMPACTOR_IMAGE" </dev/null >/dev/null 2>&1 || true
y-cluster images load --context "$CONTEXT" ./target/images/compactor-oci
y-cluster ctr --context "$CONTEXT" -- -n k8s.io images rm "docker.io/library/$CONTROLLER_IMAGE" </dev/null >/dev/null 2>&1 || true
y-cluster images load --context "$CONTEXT" ./target/images/operator-to-annotations.tar
phase "cluster: apply"
# bare test pods are immutable in most fields; on a reused cluster a changed
# manifest must recreate them, so apply always starts from absence
$KUBECTL delete pod metrics-multi metrics-classic metrics-numeric metrics-optout \
--ignore-not-found --grace-period=1 >/dev/null
# and a Job runs once: delete it so that every run scrapes it
$KUBECTL delete job owner-job --ignore-not-found >/dev/null
# the prometheus-operator CRDs, as a cluster without the operator gets them
# (operator-to-annotations/README.md); too large for a client-side apply
$KUBECTL apply --server-side -k operator-to-annotations/crds >/dev/null
# crds_established crd/<name>...: a CRD created a moment ago may have no
# .status.conditions yet, which kubectl wait fails on instead of waiting
crds_established() {
for _ in $(seq 1 15); do $KUBECTL wait --for condition=established --timeout=5s "$@" >/dev/null 2>&1 && return 0; sleep 1; done
$KUBECTL wait --for condition=established --timeout=60s "$@" >/dev/null
}
# shellcheck disable=SC2046 # one crd/<name> per word
crds_established $(sed -n 's/^ name: \(.*\.monitoring\.coreos\.com\)$/crd\/\1/p' operator-to-annotations/crds/*/*.yaml)
$KUBECTL apply -k "$MANIFESTS"
$KUBECTL rollout status statefulset/versitygw --timeout=180s
$KUBECTL wait --for=condition=complete job/create-bucket --timeout=180s
# The image tag is fixed, so apply does not replace a running agent. Restart
# it onto the image just loaded, and wait: the rolling update removes the
# old pod first, so the previous build's last upload lands before the purge
# below, not after it (a reused cluster otherwise keeps one object of the
# old line format in the assertions' corpus).
$KUBECTL -n observability rollout restart daemonset/node-agent deployment/k8sagent >/dev/null
$KUBECTL -n observability rollout status daemonset/node-agent --timeout=180s >/dev/null
$KUBECTL -n observability rollout status deployment/k8sagent --timeout=180s >/dev/null
# operator-to-annotations: cert-manager for the webhook's certificate, the
# controller, then pods that only a PodMonitor asks to scrape
# (operator-to-annotations/README.md)
phase "cluster: operator-to-annotations"
# (recent y-cluster releases install it with the cluster: then that one)
CERT_MANAGER=v1.21.2
CERT_MANAGER_SHA256=e03b668ec8675214af6b0a671699d088f2601fa3878e0dbe1b41d3feafd1879f
CERT_MANAGER_YAML=target/itest/cert-manager-$CERT_MANAGER.yaml
if ! $KUBECTL get crd certificates.cert-manager.io >/dev/null 2>&1; then
if [ ! -f "$CERT_MANAGER_YAML" ]; then
mkdir -p target/itest
curl -sSfLo "$CERT_MANAGER_YAML.tmp" "https://github.com/cert-manager/cert-manager/releases/download/$CERT_MANAGER/cert-manager.yaml"
mv "$CERT_MANAGER_YAML.tmp" "$CERT_MANAGER_YAML"
fi
echo "$CERT_MANAGER_SHA256 $CERT_MANAGER_YAML" | sha256sum -c --quiet || fail "$CERT_MANAGER_YAML is not cert-manager $CERT_MANAGER"
$KUBECTL apply --server-side -f "$CERT_MANAGER_YAML" >/dev/null
fi
for d in cert-manager cert-manager-cainjector cert-manager-webhook; do
$KUBECTL -n cert-manager rollout status "deployment/$d" --timeout=300s >/dev/null
done
# cert-manager's own webhook refuses Certificates until its CA is injected
for _ in $(seq 1 30); do $KUBECTL apply -k itest/operator-to-annotations >/dev/null 2>&1 && break; sleep 2; done
$KUBECTL apply -k itest/operator-to-annotations >/dev/null
$KUBECTL -n observability rollout restart deployment/operator-to-annotations >/dev/null
$KUBECTL -n observability rollout status deployment/operator-to-annotations --timeout=180s
$KUBECTL apply -k itest/operator-to-annotations/workloads >/dev/null
# The webhook answers once cert-manager has injected its CA and the
# Service has the new pod: until then pods are admitted unannotated
# (failurePolicy Ignore). A server-side dry run that the PodMonitor
# selects comes back annotated when it does.
webhook_probe() {
$KUBECTL run webhook-probe --dry-run=server --restart=Never --image=busybox:1.37 --labels=app=podmonitored \
--overrides='{"apiVersion": "v1", "spec": {"containers": [{"name": "probe", "image": "busybox:1.37", "ports": [{"name": "metrics", "containerPort": 9201}]}]}}' \
-o go-template='{{ with .metadata.annotations }}{{ with index . "observability-to-blobs/podmonitors" }}{{ . }}{{ end }}{{ end }}' 2>/dev/null
}
for _ in $(seq 1 60); do [ "$(webhook_probe)" = default/podmonitored ] && break; sleep 2; done
[ "$(webhook_probe)" = default/podmonitored ] || fail "the operator-to-annotations webhook does not annotate a pod its PodMonitor selects"
# the pods start over, admitted by the webhook as it is now
$KUBECTL delete pod podmonitored-preannotated --ignore-not-found --grace-period=1 >/dev/null
$KUBECTL apply -k itest/operator-to-annotations/workloads >/dev/null
$KUBECTL rollout restart deployment/podmonitored >/dev/null
$KUBECTL rollout status deployment/podmonitored --timeout=120s
# Objects from earlier runs would make every assertion scan an unbounded
# corpus. The bucket is test state; start empty. In up mode the bucket is
# the user's data: leave it alone.
if [ "$MODE" != up ]; then
phase "cluster: purge bucket prefix from earlier runs"
# the compactors write hourly/ and daily/: stop them first, their pods gone
$KUBECTL -n observability delete deployment blobs-compactor --ignore-not-found --cascade=foreground >/dev/null
$KUBECTL -n "$PUT_NS" delete deployment blobs-compactor --ignore-not-found --cascade=foreground >/dev/null
$KUBECTL delete pod purge-bucket --ignore-not-found >/dev/null 2>&1
# (the trailing slash: raw1/itest is a prefix of raw1/itest-put too)
$KUBECTL run purge-bucket --restart=Never --image=amazon/aws-cli:2.22.35 \
--env=AWS_ACCESS_KEY_ID=demoaccess --env=AWS_SECRET_ACCESS_KEY=demosecret \
--env=AWS_DEFAULT_REGION=us-east-1 \
--command -- sh -ec "for c in $CLUSTER $PUT_CLUSTER; do for p in raw1 hourly daily; do aws --endpoint-url http://versitygw:7070 s3 rm --recursive --quiet s3://$BUCKET/\$p/\$c/; done; done" >/dev/null
# a failed purge leaves the old corpus under every assertion: stop on it
deadline=$((SECONDS + 600))
while :; do
purge=$($KUBECTL get pod purge-bucket -o jsonpath='{.status.phase}')
case "$purge" in (Succeeded|Failed) break;; esac
[ $SECONDS -lt $deadline ] || fail "purge-bucket still $purge after 600s"
sleep 3
done
if [ "$purge" != Succeeded ]; then
$KUBECTL logs pod/purge-bucket >&2 || true
fail "could not purge s3://$BUCKET/{raw1,hourly,daily}/{$CLUSTER,$PUT_CLUSTER}/ (pod/purge-bucket $purge, logs above)"
fi
$KUBECTL delete pod purge-bucket >/dev/null
# the put compactor's spool outlives its pods: it starts empty too
if $KUBECTL -n "$PUT_NS" get pvc blobs-compactor-spool >/dev/null 2>&1; then
spool_sh "rm -rf /spool/raw1 /spool/_tmp" || fail "could not empty the spool: $POD_LOG"
fi
# Startup output (the burst, the >16 KiB line, restart counting) must land
# after the purge, so the pods that produce it start over. On a reused
# cluster the crash-looper's backoff has also grown to minutes.
$KUBECTL delete pod restarter reused --ignore-not-found >/dev/null
$KUBECTL rollout restart deployment/log-generator >/dev/null
# the cluster agent's first snapshots, the base of every state, too
$KUBECTL -n observability rollout restart deployment/k8sagent >/dev/null
$KUBECTL apply -k "$MANIFESTS" >/dev/null
$KUBECTL rollout status deployment/log-generator --timeout=120s >/dev/null
fi
$KUBECTL -n observability rollout status daemonset/node-agent --timeout=180s
$KUBECTL -n observability rollout status deployment/k8sagent --timeout=180s
$KUBECTL rollout status deployment/log-generator --timeout=120s
$KUBECTL wait pod/metrics-multi pod/metrics-numeric pod/metrics-optout --for=condition=Ready --timeout=120s
# The compactor folds the bucket from here on, writing encrypted Parquet
# with the keys of $PARQUET_KEYS (compactor/README.md, "Encryption"):
# itest-1 at first, itest-2 after the rotation below. Its tag is fixed
# too, so a restart moves it onto the image just loaded.
# A key's content never changes under its id: a key missing here is taken
# from the cluster's Secret when it has one, and only minted when neither
# has it, so a cleaned target/ against a kept bucket keeps its keys.
(umask 077; mkdir -p "$PARQUET_KEYS")
for id in itest-1 itest-2; do
[ -s "$PARQUET_KEYS/$id" ] && continue
existing=$($KUBECTL -n observability get secret blobs-compactor-parquet-keys \
-o go-template="{{ with index .data \"$id\" }}{{ . }}{{ end }}" 2>/dev/null || true)
if [ -n "$existing" ]; then
(umask 077; base64 -d <<< "$existing" > "$PARQUET_KEYS/$id")
else
(umask 077; head -c 32 /dev/urandom | base64 > "$PARQUET_KEYS/$id")
fi
done
$KUBECTL -n observability create secret generic blobs-compactor-parquet-keys --from-file="$PARQUET_KEYS" \
--dry-run=client -o yaml | $KUBECTL apply -f - >/dev/null
$KUBECTL apply -k itest/compactor
$KUBECTL -n observability rollout restart deployment/blobs-compactor >/dev/null
$KUBECTL -n observability rollout status deployment/blobs-compactor --timeout=120s
# The second compactor, in spool mode, and stock Fluent Bit shipping to
# its put endpoint. A new shipper pod reads every pod log from its start.
$KUBECTL apply -k itest/compactor-put
$KUBECTL -n "$PUT_NS" rollout restart deployment/blobs-compactor daemonset/stock-shipper >/dev/null
$KUBECTL -n "$PUT_NS" rollout status deployment/blobs-compactor --timeout=180s
$KUBECTL -n "$PUT_NS" rollout status daemonset/stock-shipper --timeout=180s
if [ "$MODE" = up ]; then
cat <<INFO
The agent, the compactor and the sample workloads are running.
export KUBECONFIG=$PWD/itest/cluster/kubeconfig
kubectl --context=$CONTEXT get pods -A
kubectl --context=$CONTEXT -n observability logs ds/node-agent -f
One blob per node every 30 s lands in versitygw, reachable from this
machine on NodePort $S3_PORT. local/blobs.sh opens a DuckDB session with
a view per table over it:
S3_ENDPOINT=127.0.0.1:$S3_PORT local/blobs.sh -c "SELECT \"table\", count(*) FROM raw GROUP BY 1"
local/blobs.sh $CLUSTER/\$(date -u +%Y-%m-%d/%H) # one hour, interactive
In namespace $PUT_NS, stock Fluent Bit uploads the same container logs
as cluster $PUT_CLUSTER to a second compactor's put endpoint, which spools
them on its volume and folds them into hourly/$PUT_CLUSTER/ (plain):
kubectl --context=$CONTEXT -n $PUT_NS logs deploy/blobs-compactor -f
The compactor folds the raw objects into hourly/$CLUSTER/ every 20 s,
encrypted with the keys in $PARQUET_KEYS (local/blobs.sh adds views
over that tier once it exists, given the keys):
kubectl --context=$CONTEXT -n observability logs deploy/blobs-compactor -f
PARQUET_KEYS_DIR=$PARQUET_KEYS local/blobs.sh -c "SELECT count(*) FROM hourly_logs"
Tear everything down with:
y-cluster teardown -c $CLUSTER_CONFIG
INFO
exit 0
fi
# ------------------------------------------------------------ scenarios --
# The image tag is fixed, so a rebuilt image needs a restart to be picked
# up. The restart doubles as the exit-flush test: a marker written just
# before it must arrive exactly once, from the old pod's shutdown flush.
phase "scenario: restart the agent with a marker in flight"
MARKER="restart-marker-$(date +%s)"
$KUBECTL exec deploy/log-generator -- sh -c "echo '$MARKER' > /proc/1/fd/1"
# a kernel log line for the journal path (privileged: /dev/kmsg is the host's)
KMSG_MARKER="kmsg-marker-$(date +%s)"
# an interrupted run leaves the pod behind, and run would fail on it
$KUBECTL delete pod kmsg-writer --ignore-not-found >/dev/null 2>&1
$KUBECTL run kmsg-writer --rm -i --restart=Never --image=busybox:1.37 \
--overrides='{"spec":{"containers":[{"name":"kmsg","image":"busybox:1.37","command":["sh","-c","echo \"node-agent itest '"$KMSG_MARKER"'\" > /dev/kmsg"],"securityContext":{"privileged":true}}]}}' \
>/dev/null 2>&1 || echo " (could not write to /dev/kmsg; the kernel assertion will fail)"
sleep 8
$KUBECTL -n observability rollout restart daemonset/node-agent
$KUBECTL -n observability rollout status daemonset/node-agent --timeout=180s
# the logs API reads the days before this one from the daily tier
RUN_DATE=$(date -u +%F)
# objects after this minute come from one agent process
SINCE_EPOCH=$(( $(date -u +%s) / 60 * 60 ))
SINCE="TIMESTAMP '$(date -u +'%Y-%m-%d %H:%M:00')'"
echo " SINCE=$SINCE"
# A short-lived pod for podindex lifecycle assertions: it must outlive a
# discovery interval, then its sandbox leaves the ready list.
$KUBECTL delete pod lifecycle-probe --ignore-not-found >/dev/null 2>&1
$KUBECTL run lifecycle-probe --restart=Never --image=busybox:1.37 --command -- sleep 25 >/dev/null
# The bucket goes away for longer than any retry budget of the previous
# generation; the agent must keep buffering and ship everything afterwards.
# The Service is what disappears (the versitygw data is an emptyDir), so
# uploads fail on DNS until it is back.
phase "scenario: bucket unreachable for 100 s"
$KUBECTL delete service versitygw >/dev/null
sleep 30
OUTAGE_MARKER="outage-marker-$(date +%s)"
$KUBECTL exec deploy/log-generator -- sh -c "echo '$OUTAGE_MARKER' > /proc/1/fd/1"
sleep 70
$KUBECTL apply -k "$MANIFESTS" >/dev/null
echo " service restored"
# Three incarnations of one pod name: the index must keep them apart.
phase "scenario: three incarnations of pod 'reused'"
for i in 1 2 3; do
$KUBECTL delete pod reused --ignore-not-found --wait=true >/dev/null
$KUBECTL run reused --restart=Never --image=busybox:1.37 --labels=app=reused --command -- \
sh -c "echo reused incarnation $i; sleep 15" >/dev/null
$KUBECTL wait --for=jsonpath='{.status.phase}'=Succeeded pod/reused --timeout=120s >/dev/null
# exits are observed at the discovery cadence (10 s); a pod deleted
# within one interval of its exit takes its container away before the
# agent sees it (README.md, "Known gaps")
sleep 12
done
# The cluster agent (K8SAGENT.md): an Event about the node, which lives in
# namespace default as every cluster-scoped object's events do, and a
# ConfigMap created, changed and deleted, at times kept for apiserver-at.
phase "scenario: cluster objects: an Event about the node, a ConfigMap's three states"
utc_now() { duckdb -noheader -csv -c "SELECT strftime(now() AT TIME ZONE 'UTC', '%Y-%m-%d %H:%M:%S.%f')"; }
NODE=$($KUBECTL get nodes -o jsonpath='{.items[0].metadata.name}')
NODE_EVENT="k8sagent-node-event-$(date +%s)"
$KUBECTL create -f - >/dev/null <<YAML
apiVersion: v1
kind: Event
metadata: {name: $NODE_EVENT, namespace: default}
involvedObject: {apiVersion: v1, kind: Node, name: $NODE, uid: "$($KUBECTL get node "$NODE" -o jsonpath='{.metadata.uid}')"}
reason: ItestNodeEvent
message: an event about the node, from test.sh
type: Normal
source: {component: test.sh}
YAML
# A CRD of two versions with large schemas (crd_mode redacted ships
# neither) and a custom resource of it, which apiserver-at must still list
# with the CRD's printer columns
BIG_DESCRIPTION=$(head -c 150000 /dev/zero | tr '\0' x)
gadget_version() { # name storage
cat <<YAML
- name: $1
served: true
storage: $2
additionalPrinterColumns:
- {name: Size, type: integer, jsonPath: .spec.size}
- {name: Color, type: string, jsonPath: .spec.color, priority: 1}
- {name: Age, type: date, jsonPath: .metadata.creationTimestamp}
schema:
openAPIV3Schema:
type: object
properties:
spec:
type: object
description: "$1 $BIG_DESCRIPTION"
properties:
size: {type: integer}
color: {type: string}
YAML
}
$KUBECTL delete crd gadgets.itest.example.com --ignore-not-found >/dev/null
{ cat <<YAML
apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata: {name: gadgets.itest.example.com}
spec:
group: itest.example.com
scope: Namespaced
names: {plural: gadgets, singular: gadget, kind: Gadget}
versions:
YAML
gadget_version v1alpha1 false
gadget_version v1 true
} | $KUBECTL create -f - >/dev/null
crds_established crd/gadgets.itest.example.com
$KUBECTL apply -f - >/dev/null <<YAML
apiVersion: itest.example.com/v1
kind: Gadget
metadata: {name: g1, namespace: default}
spec: {size: 3, color: blue}
YAML
$KUBECTL delete configmap k8sagent-probe --ignore-not-found >/dev/null
PROBE_0=$(utc_now)
sleep 3
$KUBECTL create configmap k8sagent-probe --from-literal=v=1 >/dev/null
sleep 5
PROBE_1=$(utc_now)
sleep 5
$KUBECTL patch configmap k8sagent-probe -p '{"data":{"v":"2"}}' >/dev/null
sleep 5
PROBE_2=$(utc_now)
sleep 5
$KUBECTL delete configmap k8sagent-probe >/dev/null
sleep 5
PROBE_3=$(utc_now)
echo " probe states at $PROBE_0 (none), $PROBE_1 (v=1), $PROBE_2 (v=2), $PROBE_3 (deleted)"
# The put endpoint with a client other than out_s3, aws-cli: a raw object
# for an hour three hours ago, which the past pass folds in full, so the
# hour is final and the object goes from the spool; the same PUT with a
# wrong secret, and without a signature, both refused.
phase "scenario: PUTs to the put endpoint: a late object, a wrong signature, none"
LATE_PUT_HOUR=$(duckdb -noheader -csv -c "SELECT strftime(date_trunc('hour', now() AT TIME ZONE 'UTC') - INTERVAL 3 HOUR, '%Y-%m-%d/%H')")
LATE_PUT_UID=$(duckdb -noheader -csv -c "SELECT uuid()")
LATE_PUT_KEY=raw1/$PUT_CLUSTER/$LATE_PUT_HOUR/itest-late/0000-$LATE_PUT_UID.jsonl.zst
late=$(mktemp "${TMPDIR:-/tmp}/itest-late.XXXXXX")
duckdb -c "COPY (
SELECT 'logs' AS \"table\", t AS time, t AS ts, '$PUT_CLUSTER' AS cluster, 'itest-late' AS node, 'itest-late' AS namespace,
'late' AS pod, '$LATE_PUT_UID' AS pod_uid, 'late' AS container, 0 AS restart, 'stdout' AS stream, 'late put line ' || i AS message
FROM (SELECT i, strptime('$LATE_PUT_HOUR', '%Y-%m-%d/%H')::TIMESTAMP_NS + to_seconds(i) AS t FROM range(3) r(i))
) TO '$late' (FORMAT json, COMPRESSION zstd)" >/dev/null || fail "the late object"
late_b64=$(base64 < "$late" | tr -d '\n')
rm -f "$late"
put="aws --endpoint-url http://blobs-compactor-put:9000 s3api put-object --bucket $BUCKET --body /tmp/late.jsonl.zst --key"
run_pod "$PUT_NS" put-probe amazon/aws-cli:2.22.35 "" sh -c "
export AWS_ACCESS_KEY_ID=itestput AWS_SECRET_ACCESS_KEY=itest-put-secret AWS_DEFAULT_REGION=us-east-1
echo $late_b64 | base64 -d > /tmp/late.jsonl.zst
$put $LATE_PUT_KEY >/dev/null && echo late-stored
AWS_SECRET_ACCESS_KEY=wrong $put raw1/$PUT_CLUSTER/$LATE_PUT_HOUR/itest-late/0001-wrong.jsonl.zst 2>&1; echo wrong-exit \$?
$put raw1/$PUT_CLUSTER/$LATE_PUT_HOUR/itest-late/0002-unsigned.jsonl.zst --no-sign-request 2>&1; echo unsigned-exit \$?" || true
PUT_PROBE=$POD_LOG
while IFS= read -r l; do echo " $l"; done <<<"$PUT_PROBE"
# Fluent Bit buffers while the put endpoint is gone and uploads once it is
# back, so a line written while the compactor is down arrives, once.
phase "scenario: the put compactor down for 60 s, a marker in flight"
$KUBECTL -n "$PUT_NS" scale deployment/blobs-compactor --replicas=0 >/dev/null
deadline=$((SECONDS + 330))
while [ -n "$($KUBECTL -n "$PUT_NS" get pods -l app=blobs-compactor -o name)" ]; do
[ $SECONDS -lt $deadline ] || fail "the put compactor's pod is still there 330s after scaling to 0"
sleep 2
done
# the outage window, for the shipper's failed uploads (kubelet log
# timestamps are UTC RFC 3339)
PUT_DOWN_AT=$(date -u +%Y-%m-%dT%H:%M:%SZ)
PUT_MARKER="put-marker-$(date +%s)"
$KUBECTL exec deploy/log-generator -- sh -c "echo '$PUT_MARKER' > /proc/1/fd/1"
sleep 60
$KUBECTL -n "$PUT_NS" scale deployment/blobs-compactor --replicas=1 >/dev/null
$KUBECTL -n "$PUT_NS" rollout status deployment/blobs-compactor --timeout=180s >/dev/null
PUT_UP_AT=$(date -u +%Y-%m-%dT%H:%M:%SZ)
echo " the put compactor is back"
# ---------------------------------------------------------------- assert --
# One DuckDB init for every assertion: the secret, and the views the
# compactor and local/blobs.sh read from the same .sql files, so the
# column contract lives in exactly one place (compactor/sql/raw.sql).
umask 077 # the S3 secret and the parquet keys go into files below
INIT=$(mktemp "${TMPDIR:-/tmp}/itest.XXXXXX")
INIT_S3=$INIT.s3 SCOPED=$INIT.scoped SNAPSHOT=$INIT.raw.csv PODS_BEFORE=$INIT.pods.parquet ROTATED=$INIT.rotated.csv
LOGS_HDR=$INIT.logs.headers LOGS_OUT=$INIT.logs.body
cat >"$INIT_S3" <<SQL
.output /dev/null
INSTALL httpfs; LOAD httpfs; SET TimeZone='UTC';
-- scoped to the bucket, as itest/host-docker does: a persistent secret for
-- s3:// on this machine would otherwise win over SET s3_*
CREATE OR REPLACE SECRET node_itest (TYPE s3, KEY_ID 'demoaccess', SECRET 'demosecret',
REGION 'us-east-1', ENDPOINT '127.0.0.1:$S3_PORT', USE_SSL false, URL_STYLE 'path',
SCOPE 's3://$BUCKET/');
CREATE OR REPLACE SECRET node_itest_multi (TYPE s3, KEY_ID 'demoaccess', SECRET 'demosecret',
REGION 'us-east-1', ENDPOINT '127.0.0.1:$S3_PORT', USE_SSL false, URL_STYLE 'path',
SCOPE 's3://$MULTI_BUCKET/');
SQL
# the compactor's parquet keys; 0600 like the S3 one (umask above)
for f in "$PARQUET_KEYS"/*; do
echo "PRAGMA add_parquet_key('${f##*/}', '$(tr -d '[:space:]' < "$f")');"
done >>"$INIT_S3"
echo ".output" >>"$INIT_S3"
cat >"$INIT" <<SQL
.read $INIT_S3
.output /dev/null
SET VARIABLE raw_files = 's3://$BUCKET/raw1/$CLUSTER/*/*/*/*.jsonl.zst';
.read $PWD/compactor/sql/raw.sql
.read $PWD/compactor/sql/tables.sql
.read $PWD/local/apiserver_at.sql
.output
SQL
RAW_OBJECTS="read_json_objects('s3://$BUCKET/raw1/$CLUSTER/*/*/*/*.jsonl.zst', format='newline_delimited', compression='zstd')"
# the key's time: first record's time in the object
KEYTIME="strptime(regexp_extract(filename, '/([0-9]{4}-[0-9]{2}-[0-9]{2}/[0-9]{2})/[^/]+/([0-9]{4})-', ['d', 't'])['d'] || '/' || regexp_extract(filename, '/([0-9]{4}-[0-9]{2}-[0-9]{2}/[0-9]{2})/[^/]+/([0-9]{4})-', ['d', 't'])['t'], '%Y-%m-%d/%H/%M%S')"
# naive UTC like every time column (now() itself carries a time zone),
# truncated so that per-minute counts only see complete minutes
NOW="date_trunc('minute', now() AT TIME ZONE 'UTC')"
# .read via -c rather than -init: -init prints a banner with an ANSI reset
# that lands in front of the first value line
# (QINIT names another init, scoped() below)
q() { duckdb -noheader -csv -c ".read ${QINIT:-$INIT}" -c "$1" 2>&1; }
show() { duckdb -c ".read $INIT" -c "$1" 2>&1; }
# tier <stem glob> [read_parquet options]: a FROM clause over the tier
# objects <stem>.parquet and <stem>.k-<id>.parquet: one read of the plain
# objects and one per key id, united by name, because one read takes one
# key (compactor/README.md, "Encryption"). A read binds its glob, so only
# the reads that match objects are in it. No '?' in a stem: in an s3 URL
# it starts the query string.
tier() {
local stem=$1 opts=${2:+, $2} id from=""
for id in $(q "SELECT DISTINCT coalesce(nullif(regexp_extract(file, '\\.k-([a-z0-9-]+)\\.parquet\$', 1), ''), '-') FROM glob('$stem*.parquet') ORDER BY 1"); do
if [ "$id" = - ]; then
from="${from:+$from UNION ALL BY NAME }SELECT * FROM read_parquet('$stem.parquet', union_by_name = true$opts)"
else
from="${from:+$from UNION ALL BY NAME }SELECT * FROM read_parquet('$stem.k-$id.parquet', encryption_config = {footer_key: '$id'}$opts)"
fi
done
echo "(${from:-SELECT NULL AS none WHERE false})"
}
ERRORS=0
assert() {
# assert <description> <sql returning a single truthy value>
local out
out=$(q "$2" | tr -d '[:space:]' || true)
if [ "$out" = true ] || [ "$out" = 1 ]; then
echo " PASS: $1"
else
echo " FAIL: $1 (got: $out)" >&2
ERRORS=$((ERRORS + 1))
fi
}
# expect <description> <command...>: PASS when the command succeeds, as
# assert does for SQL
expect() {
local what=$1
shift
if "$@"; then
echo " PASS: $what"
else
echo " FAIL: $what" >&2
ERRORS=$((ERRORS + 1))
fi
}
# logs_expect <description> <command...>: expect, showing the logs API's
# last answer on a failure
logs_expect() {
local what=$1
shift
if "$@"; then
echo " PASS: $what"
else
echo " FAIL: $what, the answer:" >&2
logs_show
ERRORS=$((ERRORS + 1))
fi
}
# The logs API (compactor/README.md, "The logs API"), through a
# port-forward from this host.
# logs_forward <namespace> <resource> <local port> <its variable>: forward
# to port 8080 of svc/... or pod/..., until the script exits, and wait for
# the API
logs_forward() {
local deadline=$((SECONDS + 60))
port_free "$3" "$4"
$KUBECTL -n "$1" port-forward "$2" "$3:8080" >/dev/null 2>&1 &
LOGS_PF_PIDS+=($!)
until curl -sf -o /dev/null "http://127.0.0.1:$3/openapi.json"; do
[ $SECONDS -lt $deadline ] || return 1
sleep 1
done
}
# logs_get <local port> <path>: the answer's status in LOGS_CODE, its
# headers in LOGS_HEADERS, its body in LOGS_BODY (trailing newlines cut)
logs_get() {
LOGS_CODE=$(curl -sS -o "$LOGS_OUT" -D "$LOGS_HDR" -w '%{http_code}' "http://127.0.0.1:$1$2" 2>&1) || LOGS_CODE="curl failed: $LOGS_CODE"
LOGS_HEADERS=$(tr -d '\r' < "$LOGS_HDR")
LOGS_BODY=$(cat "$LOGS_OUT")
}
# logs_header <name>: that header of the last answer
logs_header() {
awk -v k="$(tr '[:upper:]' '[:lower:]' <<<"$1")" -F': ' 'tolower($1) == k { v = $2 } END { print v }' <<<"$LOGS_HEADERS"
}
# logs_is <status> <content type> [header=value...]: the last answer has them
logs_is() {
local kv
[ "$LOGS_CODE" = "$1" ] && [ "$(logs_header Content-Type)" = "$2" ] || return 1
shift 2
for kv in "$@"; do
[ "$(logs_header "${kv%%=*}")" = "${kv#*=}" ] || return 1
done
}
# logs_show: the last answer, for a failure's context
logs_show() { printf ' %s\n' "status $LOGS_CODE" "$LOGS_HEADERS" "${LOGS_BODY:0:600}" >&2; }
# logs_tail_lines <n>: the body is n lines, each a CRI timestamp, a space
# and a message, and X-Logs-Timestamp-End is the last line's timestamp
logs_tail_lines() {
local n
n=$(grep -c . <<<"$LOGS_BODY")
[ "$n" = "$1" ] && ! grep -qvE '^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}\.[0-9]{9}Z ' <<<"$LOGS_BODY" \
&& [ "$(tail -n 1 <<<"$LOGS_BODY" | cut -d' ' -f1)" = "$(logs_header X-Logs-Timestamp-End)" ]
}
phase "assert: waiting for the outage backlog and the incarnations to land"
deadline=$((SECONDS + 420))
while :; do
n=$(q "SELECT count(DISTINCT pod_uid) FROM logs WHERE pod = 'reused'" | tr -d '[:space:]' || true)
m=$(q "SELECT count(*) FROM logs WHERE message = '$OUTAGE_MARKER'" | tr -d '[:space:]' || true)
case "$n" in (''|*[!0-9]*) n=0;; esac
case "$m" in (''|*[!0-9]*) m=0;; esac
echo " incarnations of 'reused' in the blobs: $n, outage marker copies: $m"
if [ "$n" -ge 3 ] && [ "$m" -ge 1 ]; then break; fi
if [ $SECONDS -ge $deadline ]; then
$KUBECTL -n observability logs ds/node-agent --tail=60 || true
fail "blobs incomplete after 420s"
fi
sleep 15
done
# The per-minute assertions look at complete minutes from SINCE+3 (the
# outage backlog has landed by then) up to two minutes ago; give them at
# least two such minutes. The last incarnation's lines are in the agent's
# buffer for up to 36 s as well.
while [ "$(date -u +%s)" -lt $((SINCE_EPOCH + 7 * 60 + 10)) ]; do sleep 10; done
phase "assert: objects"
show "SELECT filename, \"table\", count(*) AS lines FROM raw GROUP BY ALL ORDER BY filename, \"table\""
assert "keys are /raw1/cluster/date/HH/node/MMSS-uuid.jsonl.zst" \
"SELECT bool_and(regexp_matches(filename, '^s3://$BUCKET/raw1/$CLUSTER/\d{4}-\d{2}-\d{2}/\d{2}/[^/]+/\d{4}-[0-9A-Za-z]+\.jsonl\.zst$')) FROM raw"
# every minute of the window, so a minute without objects fails too
MINUTES="range($SINCE + INTERVAL 3 MINUTE, $NOW - INTERVAL 2 MINUTE, INTERVAL 1 MINUTE) AS w(m)"
# the node agents' objects; the cluster agent's are under _k8sagent
NODE_AGENT="filename NOT LIKE '%/_k8sagent/%'"
assert "about two objects per minute per node (upload_timeout 30s)" \
"SELECT bool_and(coalesce(n, 0) BETWEEN 1 AND 3) FROM $MINUTES LEFT JOIN (SELECT date_trunc('minute', $KEYTIME) AS m, count(DISTINCT filename) AS n FROM raw WHERE $KEYTIME > $SINCE + INTERVAL 3 MINUTE AND $KEYTIME < $NOW - INTERVAL 2 MINUTE AND $NODE_AGENT GROUP BY m) USING (m)"
assert "every node agent object after the outage carries logs and metrics lines" \
"SELECT bool_and(has_logs AND has_metrics) FROM (SELECT filename, bool_or(\"table\" = 'logs') AS has_logs, bool_or(\"table\" = 'metrics') AS has_metrics FROM raw WHERE $KEYTIME > $SINCE + INTERVAL 3 MINUTE AND $NODE_AGENT GROUP BY filename)"
# out_s3 renders ts truncated to the microsecond, so it can be 1 us below
# the source's nanosecond time (seen 2026-09-28: .536233 vs ts .536232)
assert "ts is the event time at microseconds on every line" \
"SELECT bool_and(ts IS NOT NULL) AND bool_and(time IS NULL OR abs(epoch_ns(time) - epoch_ns(ts)) <= 1000) FROM raw"
assert "container log lines carry exactly the contract keys (no Lua, no leaked parser fields)" \
"SELECT list_sort(list_distinct(flatten(list(json_keys(json))))) = ['cluster', 'container', 'message', 'namespace', 'node', 'pod', 'pod_uid', 'restart', 'stream', 'table', 'time', 'ts']
FROM $RAW_OBJECTS
WHERE json_extract_string(json, 'table') = 'logs' AND json_extract_string(json, 'pod') IS NOT NULL"
# The contract in both directions: a field the agent emits that raw.sql
# does not pin would be silently ignored, a pinned field no line carries
# is a rename or a typo. Journal-only fields are absent on the docker
# backend; exit_message is only set when the runtime has one.
if [ "$BACKEND" = docker ]; then ABSENT_OK="['unit', 'priority', 'exit_message']"; else ABSENT_OK="['exit_message']"; fi
assert "every field the agent emits is a pinned column of compactor/sql/raw.sql (offenders listed)" \
"WITH seen AS (SELECT list_distinct(flatten(list(json_keys(json)))) AS keys FROM $RAW_OBJECTS),
pinned AS (SELECT list(column_name) AS cols FROM (DESCRIBE raw))
SELECT list_filter(seen.keys, lambda k: NOT list_contains(pinned.cols, k)) = [] FROM seen, pinned"
assert "every pinned column is emitted by some line (missing listed)" \
"WITH seen AS (SELECT list_distinct(flatten(list(json_keys(json)))) AS keys FROM $RAW_OBJECTS),
pinned AS (SELECT list(column_name) AS cols FROM (DESCRIBE raw))
SELECT list_filter(pinned.cols, lambda c: c <> 'filename' AND NOT list_contains(seen.keys, c) AND NOT list_contains($ABSENT_OK, c)) = [] FROM seen, pinned"
assert "a sample carries exactly name, type, labels and value" \
"SELECT list_sort(list_distinct(flatten(list(json_keys(json_extract(json, '\$.samples[0]')))))) = ['labels', 'name', 'type', 'value']
FROM $RAW_OBJECTS WHERE json_extract_string(json, 'table') = 'metrics'"
assert "cluster is on every line, node on every line but the cluster agent's" \
"SELECT bool_and(cluster = '$CLUSTER' AND (\"table\" = 'apiserver' OR (node IS NOT NULL AND node <> ''))) FROM raw"
assert "no line is of an unknown table" \
"SELECT bool_and(\"table\" IN ('logs', 'metrics', 'podindex', 'apiserver')) FROM raw"
# Container logs
assert "log-generator lines present with namespace/pod/container from the path" \
"SELECT count(*) > 0 FROM logs WHERE namespace = 'default' AND pod LIKE 'log-generator-%' AND container = 'app' AND message LIKE '%hello from log-generator%'"
assert "stderr lines keep stream=stderr" \
"SELECT count(*) > 0 FROM logs WHERE pod LIKE 'log-generator-%' AND stream = 'stderr' AND message LIKE 'stack trace example%'"
assert "CRI partial lines are joined (long line > 16 KiB arrives as one message)" \
"SELECT max(length(message)) > 16384 FROM logs WHERE pod LIKE 'log-generator-%' AND message LIKE '%long-line%'"
assert "burst timestamps are strictly increasing with sub-second precision" \
"SELECT count(*) >= 200 AND count(DISTINCT time) = count(*) FROM logs WHERE pod LIKE 'log-generator-%' AND message LIKE '%\"burst\"%'"
assert "pod_uid is filled for container logs" \
"SELECT bool_and(length(pod_uid) = 36) FROM logs WHERE pod IS NOT NULL"
assert "restarts show up as restart > 0 for the crash-looping pod" \
"SELECT max(restart) >= 1 FROM logs WHERE pod = 'restarter'"
assert "a line read before the restart is shipped by the exit flush, exactly once" \
"SELECT count(*) = 1 FROM logs WHERE message = '$MARKER'"
assert "the agent's own logs are excluded" \
"SELECT count(*) = 0 FROM logs WHERE pod LIKE 'node-agent-%'"
# Outage: nothing lost, nothing duplicated
assert "a line written while the bucket was unreachable arrives exactly once" \
"SELECT count(*) = 1 FROM logs WHERE message = '$OUTAGE_MARKER'"
# per pod: a rollout-restarted generator overlaps its predecessor briefly
assert "the generator's counter is contiguous across the outage" \
"WITH c AS (SELECT DISTINCT pod, CAST(json_extract(message, '$.count') AS INTEGER) AS n FROM logs
WHERE pod LIKE 'log-generator-%' AND message LIKE '%hello from log-generator%' AND time > $SINCE),
per_pod AS (SELECT pod, count(*) AS seen, min(n) AS lo, max(n) AS hi FROM c GROUP BY pod)
SELECT bool_and(seen = (SELECT count(*) FROM range(lo, hi + 1) r WHERE r.range % 10 <> 0)) FROM per_pod"
# out_s3 v5.1.2 gives up on a chunk with "... failed to send N/M times, will
# not retry", then "retry-exhausted chunk moved to quarantine" or "...
# deleting retry-exhausted chunk"; the engine's own give-up is "chunk ...
# cannot be retried". The logs are read first: a failed read is a failure,