Repository navigation
Expand file tree
/
Copy pathjustfile
More file actions
1596 lines (1441 loc) · 64.5 KB
/
Copy pathjustfile
File metadata and controls
1596 lines (1441 loc) · 64.5 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
# SPDX-License-Identifier: Apache-2.0
# Copyright Open Network Fabric Authors
set unstable := true
set shell := ["/usr/bin/env", "bash", "-euo", "pipefail", "-c"]
set script-interpreter := ["/usr/bin/env", "bash", "-euo", "pipefail"]
mod ci
mod miri
# enable to debug just recipes
debug_justfile := "false"
[private]
_just_debuggable_ := if debug_justfile == "true" { "set -x" } else { "" }
# number of nix derivations to build concurrently
jobs := "8"
# threads each nix derivation may use ("0" means every core on the machine).
#
# nix hands this to the builder as NIX_BUILD_CORES, which crane turns into
# CARGO_BUILD_JOBS and nixpkgs' enableParallelBuilding turns into make -j, so
# it is the cap on concurrent compile/link jobs *within* one derivation. The
# cap on the whole build is therefore `jobs` x `cores`; a runner with fewer
# cores than that will oversubscribe itself.
cores := "0"
# libc
libc := if platform == "wasm32-wasip1" { "none" } else { "gnu" }
# kernel (linux or wasip1)
kernel := if platform == "wasm32-wasip1" { "wasip1" } else { "linux" }
# List out the available commands
[private]
[default]
@default:
just --list --justfile {{ justfile() }}
# cargo build profile (debug/release/checked)
profile := "debug"
export callgrind_package := "dataplane-routing"
export callgrind_bench := "fib_lookup_callgrind"
# sanitizers to use, comma-separated (address/cfi/leak/safe-stack/shadow-stack/thread/"")
sanitize := ""
# Bolero's own default budget is one second. A property that spends it on too few draws can
# miss the behaviour its coverage assertions require and fail for being under-run rather than
# for a real gap -- `just coverage` already avoids that with a budget of its own, and the
# plain run is the one that actually asserts. Exported here rather than per recipe so that
# every one of them inherits it; `coverage` assigns its own value in its body, which wins.
# Honour an explicit override if the caller sets one.
export BOLERO_RANDOM_TEST_TIME_MS := env("BOLERO_RANDOM_TEST_TIME_MS", "4000")
bolero_coverage_test_time_ms := env("BOLERO_COVERAGE_TEST_TIME_MS", "15000")
# comma-separated list of cargo features to enable (e.g. "shuttle")
features := ""
fuzz_max_input_length := env("FUZZ_MAX_INPUT_LENGTH", "65536")
fuzz_corpus_root := env("FUZZ_CORPUS_ROOT", justfile_directory() / ".fuzz-corpus")
fuzz_jobs := env("FUZZ_JOBS", `echo $(( ($(nproc) + 1) / 2 ))`)
fuzz_len_control := env("FUZZ_LEN_CONTROL", "0")
# whether to include default cargo features for this workspace (set to "false" to disable)
default_features := "true"
# Private computed cargo flag groups for consistent invocations.
# Recipes should compose these as needed (not all cargo subcommands accept all flags).
[private]
_cargo_feature_flags := \
(if default_features == "false" { "--no-default-features " } else { "" }) \
+ (if features != "" { "--features " + features } else { "" })
[private]
_cargo_profile_flag := if profile == "debug" { "" } else { "--profile " + profile }
# filters for nextest
#
# Under `shuttle`, the legacy `dataplane-quiescent` test layout had a
# `shuttle` binary that hosted the bolero x shuttle suite, and we used
# `--package=shuttle` (now an `-E 'package(shuttle)'`-style filter
# embedded in nextest's argv) to isolate it. Today that suite lives in
# `concurrency/tests/quiescent_shuttle.rs`, and the test binary is
# `quiescent_shuttle`; matching the substring `shuttle` is good enough.
#
# Under `loom`, the legacy filter `-E 'binary(loom)'` matched
# `quiescent_loom`, the single integration-test binary that opted into
# `loom::model`. After the concurrency rework, loom-compatible tests
# are spread across multiple binaries (`quiescent_model`,
# `thread_scope`, `arc_weak`, `stress_dispatch`); the rest are gated
# with `#![cfg(not(any(feature = "loom", ...)))]` and compile down to
# zero tests under the loom feature. An empty filter is therefore the
# right answer: nextest walks every archived binary, the cfg-gated
# ones contain no tests, and the loom-compatible ones run under their
# `#[concurrency::test]`-routed `loom::model` body.
# Match all shuttle variants (`shuttle`, plus the additive
# `shuttle_dfs` opt-in).
# Under any shuttle backend, `concurrency::sync` types ARE shuttle
# primitives, and touching them outside a `shuttle::check_*`-wrapped
# body panics with `ExecutionState NotSet`. Tests that are designed
# to run under shuttle either go through `#[concurrency::test]` (which
# emits a `concurrency_model::<backend>` leaf -- the substring matches)
# or live in a `*_shuttle` module / `*shuttle*` binary by convention.
# Other workspace tests would fail spuriously without this filter.
filter := if features =~ "^shuttle" { "shuttle" } else if features =~ "^loom" { "::concurrency_model::loom" } else { "" }
# instrumentation to add, comma-separated (none/coverage/fuzz)
instrument := "none"
# target platform (x86-64-v3/bluefield2)
platform := "x86-64-v3"
version_extra := ""
version_platform := if platform == "x86-64-v3" { "" } else { "-" + platform }
version_profile := if profile == "release" { "" } else { "-" + profile }
version_san := if sanitize == "" { "" } else { "-san." + replace(sanitize, ",", ".") }
version_feat := if features == "" { "" } else { "-feat." + replace(features, ",", ".") }
version := env("VERSION", `git describe --tags --dirty --always` + version_platform + version_profile + version_san + version_feat + version_extra)
# Print version that will be used in the build
version:
@echo "Using version: {{version}}"
# OCI repo to push images to
oci_repo := "127.0.0.1:30000"
oci_insecure := ""
oci_name := "githedgehog/dataplane"
oci_frr_prefix := "githedgehog/dataplane/frr"
oci_image_dataplane := oci_repo + "/" + oci_name + ":" + version
oci_image_dataplane_debugger := oci_repo + "/" + oci_name + "/debugger:" + version
oci_image_dataplane_validator := oci_repo + "/" + oci_name + "/validator:" + version
oci_image_frr_dataplane := oci_repo + "/" + oci_frr_prefix + ":" + version
oci_image_frr_host := oci_repo + "/" + oci_frr_prefix + "-host:" + version
[private]
_skopeo_dest_insecure := if oci_insecure == "true" { "--dest-tls-verify=false" } else { "" }
[private]
nightly := "false"
[private]
docker_sock := "/var/run/docker.sock"
# Directory the Docker daemon can see, when it cannot see this checkout's
# /nix/store. Empty -- the ordinary case -- means the daemon runs on this host
# and resolves store paths itself.
#
# n-vm's container tier hands the daemon bind-mount *sources*, and the daemon
# resolves them in its own mount namespace. On a CI runner that is itself a
# container talking to the host's daemon, /nix belongs to the runner image and
# the bare metal has nothing at those paths. Because every mount asks Docker to
# create a missing mount point, the daemon answers by creating an *empty*
# directory rather than failing, so the guest root comes up empty and the first
# mount beneath it dies on a read-only filesystem.
#
# Set this to a directory on a filesystem both sides share -- under this
# workspace, which is the one path a containerised runner and its host agree on
# -- and `setup-roots` will export the roots' closure into it. `n-vm` reads the
# same variable and rewrites the mount sources; the targets stay `/nix/store`,
# so rpaths in the guest are unaffected.
n_vm_host_share := env("N_VM_HOST_SHARE_DIR", "")
# Build a nix derivation with standard build arguments
[script]
build target="containers.dataplane" *args:
{{ _just_debuggable_ }}
mkdir -p results
declare -r target="{{target}}"
nix build -f default.nix "${target}" \
--argstr profile '{{ profile }}' \
--argstr sanitize '{{ sanitize }}' \
--argstr libc '{{ libc }}' \
--argstr kernel '{{ kernel }}' \
--argstr features '{{ features }}' \
--argstr default-features '{{ default_features }}' \
--argstr instrumentation '{{ instrument }}' \
--argstr platform '{{ platform }}' \
--argstr tag '{{version}}' \
--argstr nightly '{{nightly}}' \
--print-build-logs \
--show-trace \
--out-link "results/${target}" \
--max-jobs "{{jobs}}" \
--cores "{{cores}}" \
--keep-failed \
{{ args }}
# run formatters for the code used in this project
[script]
fmt *args:
{{ _just_debuggable_ }}
cargo fmt {{args}}
# run a series of pre-flight checks to catch most problems you might find in CI early
[script]
pre-flight: (fmt "--check") (test) (lint) (doctest)
{{ _just_debuggable_ }}
echo "pre flight checks pass"
[script]
test package="tests.all" *args: (setup-roots) (build (if package == "tests.all" { "tests.all" } else { "tests.pkg." + package }) args)
{{ _just_debuggable_ }}
declare -r target="{{ if package == "tests.all" { "tests.all" } else { "tests.pkg." + package } }}"
# Export the scratch-container roots `setup-roots` just built, so that
# `#[n_vm::test]` tests find them. The guard is for a tree where
# `setup-roots` was skipped; the tests fail loudly rather than skip, so
# this is a clearer error, not a fallback.
if [[ -e testroot && -e vmroot ]]; then
export N_VM_TEST_ROOT="$(pwd)/testroot"
export N_VM_VM_ROOT="$(pwd)/vmroot"
fi
just n_vm_host_share="{{ n_vm_host_share }}" _export-test-extras
# `trybuild` (n-vm-macros' compile-fail suite) shells out to
# `cargo --offline` for a scratch project under `target/tests/trybuild`,
# which resolves against the local registry cache rather than the nix
# vendor directory the workspace was built from. CI builds through nix and
# never populates that cache, so the suite fails there with "no matching
# package named `proc-macro2`" while passing on any developer machine.
# `--locked` means every download is checksum-checked against Cargo.lock,
# and a warm cache makes this a no-op.
cargo fetch --locked
# `--no-tests pass`: a single-package archive whose only test(s) are
# `#[cfg_attr(emulated, ignore)]` (e.g. n-vm-macros' trybuild test under
# cross) runs zero tests; treat that as success, matching `test-each`.
cargo nextest run --archive-file results/${target}/*.tar.zst --workspace-remap $(pwd) --no-tests pass {{ filter }}
# List the bolero targets `just fuzz` can run. Args go to `cargo bolero list`
[script]
fuzz-list *args="":
{{ _just_debuggable_ }}
cargo bolero list --profile checked {{ _cargo_feature_flags }} {{ args }}
# Fuzz one bolero target under libfuzzer. See development/code/running-tests.md
[script]
fuzz target time="60s" *args="":
{{ _just_debuggable_ }}
# libfuzzer wants a nightly compiler for its sanitizer coverage flags, while the
# pinned toolchain is stable; --rustc-bootstrap bridges that. cargo-bolero already
# builds with the fuzz profile and links AddressSanitizer unless told otherwise, so
# a plain `just fuzz` is already an asan run. Findings land under
# `{{ fuzz_corpus_root }}` (`.fuzz-corpus` unless `FUZZ_CORPUS_ROOT` says otherwise),
# not in a `__fuzz__` directory beside the test -- that moved when the coverage corpora
# were isolated from the unit tests.
#
# `sanitize=thread` additionally rebuilds std: thread instrumentation changes the
# ABI, so a std left uninstrumented fails the build on a mismatch against `core`.
# asan does not need that, and skipping the std rebuild keeps it far quicker.
# `sanitize=NONE` drops instrumentation altogether, which buys roughly four times
# the executions per second in exchange for only catching what the test asserts.
case "{{ sanitize }}" in
"") want=address ;;
NONE) want=none ;;
*) want="{{ sanitize }}" ;;
esac
sysroot="${DATAPLANE_SYSROOT:-}"
if [ -n "${sysroot}" ] && [ -r "${sysroot}/.sanitize" ]; then
built_with="$(cat "${sysroot}/.sanitize")"
built_with="${built_with:-none}"
if [ "${want}" != "${built_with}" ] && [ -z "{{ sanitize }}" ]; then
printf 'warning: rust is built with %s and this sysroot with %s, so the C dependencies -- dpdk above all -- are not instrumented.\n' \
"${want}" "${built_with}" >&2
printf ' `just sanitize=NONE fuzz ...` instruments neither and runs about four times quicker.\n' >&2
elif [ "${want}" != "${built_with}" ]; then
printf 'refusing to fuzz: sanitize=%s was asked for, but this sysroot was built with sanitize=%s.\n' \
"{{ sanitize }}" "${built_with:-<none>}" >&2
printf 'rebuild the C dependencies and re-enter the shell with:\n' >&2
printf ' just sanitize=%s setup-roots && nix-shell --argstr sanitize %s\n' \
"{{ sanitize }}" "{{ sanitize }}" >&2
exit 1
fi
elif [ -n "{{ sanitize }}" ] && [ "{{ sanitize }}" != "NONE" ]; then
# A sanitizer run requires a readable stamp to verify the sysroot's instrumentation.
printf 'refusing to fuzz: cannot verify sanitize=%s without a readable\n' \
"{{ sanitize }}" >&2
printf '.sanitize stamp (DATAPLANE_SYSROOT=%s).\n' \
"${sysroot:-<unset>}" >&2
printf 'rebuild the sysroot and re-enter the shell with:\n' >&2
printf ' just sanitize=%s setup-roots && nix-shell --argstr sanitize %s\n' \
"{{ sanitize }}" "{{ sanitize }}" >&2
exit 1
fi
inherited="$(cargo config get -Zunstable-options --format json-value build.rustflags 2>/dev/null | jq -r 'join(" ")')"
export RUSTFLAGS="${inherited} ${RUSTFLAGS:-}"
sancov_rt="$(clang -print-file-name=libclang_rt.fuzzer_no_main-$(uname -m).a 2>/dev/null || true)"
if [ -f "${sancov_rt}" ]; then
export RUSTFLAGS="${RUSTFLAGS} -Clink-arg=${sancov_rt} -Clink-arg=-lstdc++"
else
printf 'warning: no libFuzzer runtime beside clang; packages with a non-bolero test binary will not link.\n' >&2
fi
corpus_dir="{{ fuzz_corpus_root }}/$(printf '%s' '{{ target }}' | tr -c 'A-Za-z0-9_.-' '_')"
mkdir -p "${corpus_dir}"
cargo bolero test '{{ target }}' --rustc-bootstrap -T '{{ time }}' \
--profile checked \
--corpus-dir "${corpus_dir}" \
-l '{{ fuzz_max_input_length }}' \
-E='-len_control={{ fuzz_len_control }}' \
-j '{{ fuzz_jobs }}' \
{{ if sanitize != "" { "--sanitizer " + sanitize } else { "" } }} \
{{ if sanitize == "thread" { "--build-std" } else { "" } }} \
{{ _cargo_feature_flags }} {{ args }}
[private]
[script]
_bench-release-only:
{{ _just_debuggable_ }}
if [ '{{ profile }}' != "release" ]; then
echo "error: benchmarks want profile=release, not '{{ profile }}'" >&2
echo " run: just profile=release bench" >&2
exit 1
fi
[doc("Wall-clock time, via criterion")]
[script]
bench *args: _bench-release-only (build "benches")
{{ _just_debuggable_ }}
shopt -s nullglob
for bench in ./results/benches/bin/*; do
case "${bench}" in
*_callgrind) continue ;;
esac
"${bench}" --bench {{ args }}
done
if [ -f target/criterion/report/index.html ]; then
echo
echo "html report: target/criterion/report/index.html"
fi
[doc("Instructions and cache traffic, via iai-callgrind")]
[script]
bench-callgrind *args:
{{ _just_debuggable_ }}
cargo bench -p "${callgrind_package}" --bench "${callgrind_bench}" {{ args }}
[doc("Compare against a baseline and print a markdown report")]
[script]
bench-compare baseline="base" *args:
{{ _just_debuggable_ }}
mkdir -p results/bench
# Scope baseline detection to this suite, allowing an optional target triple.
# Keep benchmark failures out of the save-baseline path.
scope="*/${callgrind_package}/${callgrind_bench}/*"
if find target/iai -type f -path "${scope}" -name '*base@{{ baseline }}*' -print -quit 2>/dev/null | grep -q .; then
cargo bench -p "${callgrind_package}" --bench "${callgrind_bench}" -- \
--baseline='{{ baseline }}' --output-format=json > results/bench/run.jsonl
else
echo "no baseline '{{ baseline }}' for ${callgrind_package}/${callgrind_bench}; recording one" >&2
cargo bench -p "${callgrind_package}" --bench "${callgrind_bench}" -- \
--save-baseline='{{ baseline }}' --output-format=json > results/bench/run.jsonl
fi
./scripts/bench-report.ts results/bench/run.jsonl {{ args }}
[doc("Record a baseline for `bench-compare`, without reporting")]
[script]
bench-baseline name="base":
{{ _just_debuggable_ }}
cargo bench -p "${callgrind_package}" --bench "${callgrind_bench}" -- \
--save-baseline='{{ name }}' > /dev/null
echo "recorded baseline '{{ name }}'"
[doc("Serve the criterion html report over http")]
[script]
bench-serve port="8080":
{{ _just_debuggable_ }}
just serve ./target/criterion '{{ port }}' report/index.html
[script]
build-each *args: (build "workspace" args)
{{ _just_debuggable_ }}
[script]
check package="" *args: (build (if package == "" { "check" } else { "check." + package }) args)
{{ _just_debuggable_ }}
[script]
check-each *args: (build "check" args)
{{ _just_debuggable_ }}
# Check every package on its own, all targets, without building or running anything; see
# `check-each` in `default.nix`.
[script]
check-each-target *args: (build "check-each" args)
{{ _just_debuggable_ }}
[script]
test-each *args: (setup-roots) (build "tests.pkg" args)
{{ _just_debuggable_ }}
# Same two requirements as `test`: the per-package archives include
# `dataplane-n-vm`'s guest-booting suite, and n-vm-macros' trybuild suite
# resolves against the local registry cache.
if [[ -e testroot && -e vmroot ]]; then
export N_VM_TEST_ROOT="$(pwd)/testroot"
export N_VM_VM_ROOT="$(pwd)/vmroot"
fi
just n_vm_host_share="{{ n_vm_host_share }}" _export-test-extras
cargo fetch --locked
declare -a fail=()
for test_archive in results/tests.pkg*/*.tar.zst; do
if ! cargo nextest run --archive-file "${test_archive}" --workspace-remap "$(pwd)" --no-tests pass; then
fail+=("${test_archive} failed")
fi
done
if [ "${#fail[@]}" -gt 0 ]; then
>&2 printf '%s\n' "${fail[@]}"
exit 1
fi
[script]
docs package="" *args: (build (if package == "" { "docs.all" } else { "docs.pkg." + package }) args)
{{ _just_debuggable_ }}
# Build the rustdoc HTML (all crates, or one by directory name) and open it in a browser
[script]
docs-open package="" *args: (docs package args)
{{ _just_debuggable_ }}
index="results/{{ if package == "" { "docs.all" } else { "docs.pkg." + package } }}/index.html"
echo "docs: file://$(realpath "${index}")"
xdg-open "${index}"
# Like docs-open, but runs cargo doc in the dev shell rather than nix, so edits rebuild incrementally.
# Args go to cargo doc (e.g. --document-private-items)
[script]
docs-quick package="" *args:
{{ _just_debuggable_ }}
# Appended rather than set: the dev shell's RUSTDOCFLAGS already carries the KaTeX/Mermaid header.
export RUSTDOCFLAGS="${RUSTDOCFLAGS:-} -Zunstable-options --enable-index-page"
export RUSTC_BOOTSTRAP=1
cargo doc --no-deps {{ _cargo_profile_flag }} {{ _cargo_feature_flags }} \
{{ if package == "" { "--workspace" } else { "--manifest-path " + package / "Cargo.toml" } }} {{ args }}
index="target/${CARGO_BUILD_TARGET:+${CARGO_BUILD_TARGET}/}doc/index.html"
echo "docs: file://$(realpath "${index}")"
xdg-open "${index}"
# Remove test containers n-vm left behind. Args go to n-vm-reap (--force, --list, --all)
[script]
reap *args:
{{ _just_debuggable_ }}
# The host tier cleans up after itself on every route it can reach,
# including SIGTERM and SIGINT, so this is only needed after a SIGKILL, an
# OOM kill, or a reboot -- none of which give a process the chance to tidy
# up. Containers whose creating process is still alive are left alone
# unless `--all` is passed, so this is safe to run while other tests are
# going. Without a tty it refuses to remove anything; CI should pass
# `--force`.
cargo run --quiet -p dataplane-n-vm --features reap --bin n-vm-reap -- {{ args }}
# Create devroot, sysroot, testroot, and vmroot symlinks for local development
[script]
setup-roots *args:
{{ _just_debuggable_ }}
# The toolchain roots take the feature list. The guest roots must not.
#
# `devroot`/`sysroot`: `features` picks the panic runtime. `loom` and `shuttle`
# require `panic = "unwind"` and `-Zbuild-std` has to match (see `mk-needs-unwind`
# in default.nix), so withholding it here would hand a shuttle build a
# `panic_abort` std.
#
# `testroot`/`vmroot`: qemu, cloud-hypervisor, virtiofsd, a kernel, an initramfs
# and the in-VM runner. None of that is the code under test -- the test binaries
# arrive at runtime under `test-bin`. Passing the feature list only asks crates
# that never declared it to build with it, and `just shuttle` consequently died
# in `setup-roots` with "the package 'dataplane-n-preinit' does not contain this
# feature: shuttle", before a single test ran. It is the same trade the pre-init
# already makes for the sanitizer: it is the scaffolding that execs the code
# under test, not the code under test.
#
# `tag` reaches a build as `VERSION`, and the guest roots are the one place
# nothing reads it: the only `option_env!("VERSION")` call sites are in
# `dataplane`, `mgmt`, `config` and `args`, and the guest payload is
# `n-preinit`, `n-it`, the kernel and the initramfs -- whose only internal
# dependency is `n-vm-protocol`. But `version` is
# `git describe --tags --dirty --always`, so it moves on every commit *and*
# on any uncommitted edit anywhere in the tree, and it is an input to both
# root derivations. Left alone, that rebuilds n-preinit -> initramfs ->
# kernel-image -> testroot -> n-it -> vmroot for a change of any kind,
# including one that touches nothing these roots contain.
#
# So pin it for the two guest roots, the same way the feature list is
# already withheld from them. `devroot` and `sysroot` keep the real tag:
# the test binaries built against them do report a version.
for root in devroot sysroot testroot vmroot; do
declare -a featureargs tagargs
case "${root}" in
testroot|vmroot)
featureargs=()
tagargs=( --argstr tag guest ) ;;
*)
featureargs=(
--argstr default-features '{{ default_features }}'
--argstr features '{{ features }}'
)
tagargs=( --argstr tag '{{version}}' ) ;;
esac
nix build -f default.nix "${root}" \
"${featureargs[@]}" \
"${tagargs[@]}" \
--argstr instrumentation '{{ instrument }}' \
--argstr kernel '{{ kernel }}' \
--argstr libc '{{ libc }}' \
--argstr nightly '{{nightly}}' \
--argstr platform '{{ platform }}' \
--argstr profile '{{ profile }}' \
--argstr sanitize '{{ sanitize }}' \
--out-link "${root}" \
{{ args }}
done
if [ -n "{{ n_vm_host_share }}" ]; then
just n_vm_host_share="{{ n_vm_host_share }}" export-scratch-roots
fi
# Export what test archives link beyond the scratch roots (init's gateway image), which is built
# with the archives and so after `setup-roots` has exported the rest. A no-op without the share.
[private]
[script]
_export-test-extras:
{{ _just_debuggable_ }}
if [ -z "{{ n_vm_host_share }}" ]; then
exit 0
fi
shopt -s nullglob
declare -a extras=( results/tests*/gateway-rootfs )
if (( ${#extras[@]} > 0 )); then
just n_vm_host_share="{{ n_vm_host_share }}" export-scratch-roots "${extras[@]}"
fi
# Copy the scratch roots' nix closure somewhere the Docker daemon can read it.
# See `n_vm_host_share`; a no-op unless that is set.
[script]
export-scratch-roots *extra:
{{ _just_debuggable_ }}
declare -r share="{{ n_vm_host_share }}"
if [ -z "${share}" ]; then
echo "n_vm_host_share is unset; nothing to export"
exit 0
fi
declare -r store="${share}/nix/store"
# `tmp` is the other half: the forwarded-environment directory is a bind
# source too, and a container-local /tmp is no more visible than /nix.
mkdir -p "${store}" "${share}/tmp"
# The closure, not the whole store. `/nix/store` is mounted into the
# container whole, so the export has to cover everything the container
# resolves through it, which is three things:
#
# testroot/vmroot the host tier's qemu, cloud-hypervisor and virtiofsd,
# the guest kernel, and n-it inside the guest root
# sysroot what the *test binary* is linked against. Missing this
# is not a missing-file error: the binary is there and
# execs, and the kernel reports ENOENT for its absent
# ELF interpreter, so the container exits 127 with
# "No such file or directory" naming a path that plainly
# exists.
# qemu-user what *runs* the test binary when it is foreign-arch.
# Not a root and not reachable from one; see below.
#
# devroot is deliberately not here. It is the toolchain -- 4.6 GiB against
# sysroot's 2.0 -- and nothing inside the container compiles.
# `extra`: what a test archive needs beyond these, built after them (see `_export-test-extras`).
declare -a roots=( testroot vmroot sysroot {{ extra }} )
declare -a resolved=()
for root in "${roots[@]}"; do
if [ ! -e "${root}" ]; then
>&2 echo "::error::${root} is missing; run setup-roots first"
exit 1
fi
resolved+=( "$(readlink -f "${root}")" )
done
# The third of those, and the one that is in none of the roots: qemu-user is
# a dev-shell package (`default.nix`),
# so it reaches a job through PATH and nothing else. A cross-arch guest
# cannot exec the foreign test binary directly, so n-vm runs it under
# `qemu-<arch>`, resolved with `find_on_path` and handed to the container as
# an absolute /nix/store path (`n-vm/src/container.rs`). Unexported, the
# container starts, every mount lands, and tini dies on the command itself:
#
# [FATAL tini (7)] exec /nix/store/...-qemu-user-11.1.0/bin/qemu-aarch64
# failed: No such file or directory
#
# Export the whole package rather than the one binary this job happens to
# need, so this does not have to know which arch is being cross-tested, and
# export it unconditionally: 19 of its 20 requisites are already in the
# roots' closure, so the marginal cost is one path and 124 MiB against
# 2.7 GiB, and a condition for when it is needed is the same mechanism that
# left `cross` without the share to begin with. Any `qemu-<arch>` name will
# do as a handle on the package.
declare qemu_binary
if qemu_binary="$(command -v qemu-aarch64 2>/dev/null)" \
|| qemu_binary="$(command -v qemu-x86_64 2>/dev/null)"; then
declare qemu_package
qemu_package="$(readlink -f "${qemu_binary}")"
resolved+=( "${qemu_package%/bin/*}" )
else
>&2 echo "::warning::qemu-user is not on PATH; a cross job's containers will exit 127"
fi
declare -a paths
mapfile -t paths < <(nix-store --query --requisites "${resolved[@]}")
declare -i copied=0 kept=0
for path in "${paths[@]}"; do
declare dest="${store}/$(basename "${path}")"
# A store path is immutable, so an entry that is already here is already
# right. This is what makes the second job on a runner cheap.
if [ -e "${dest}" ]; then
kept+=1
continue
fi
# Copy to a private name and rename, so a concurrent job never observes
# a half-copied path under a name that promises a whole one.
declare staging="${store}/.staging-$$-$(basename "${path}")"
rm -rf -- "${staging}"
cp -a --no-preserve=ownership -- "${path}" "${staging}"
# A store path's directories are r-xr-xr-x, which nix relies on to keep
# them immutable. A copy has no such contract, and inheriting the mode
# makes the export undeletable: `rm -rf` cannot unlink a child of a
# directory it cannot write. Whoever cleans this runner should not have
# to know that.
chmod -R u+w -- "${staging}"
if ! mv -T -- "${staging}" "${dest}" 2>/dev/null; then
# Lost the race; the winner's copy is as good as ours.
chmod -R u+w -- "${staging}" 2>/dev/null || true
rm -rf -- "${staging}"
fi
copied+=1
done
# Reported from nix rather than `du`: on a copy-on-write filesystem `du`
# run straight after the copy reports blocks that are still dirty, which
# made a 1.8 GiB export read as 26 MiB.
printf 'exported %d store paths to %s (%d already present, %s closure)\n' \
"${copied}" "${store}" "${kept}" \
"$(nix path-info -S "${resolved[@]}" 2>/dev/null | awk '{t+=$2} END {printf "%.1f GiB", t/1024/1024/1024}')"
[private]
[script]
_refuse-instrumented-artifact:
if [ -n '{{ instrument }}' ] && [ '{{ instrument }}' != "none" ]; then
printf 'refusing to build a container at instrument=%s: an instrumented build is a diagnostic,\n' '{{ instrument }}' >&2
printf 'not an artifact, and instrumentation is not part of the version -- so this image would\n' >&2
printf 'take a clean image tag and replace it.\n' >&2
exit 1
fi
# Build the dataplane container image
[script]
build-container target="dataplane" *args: _refuse-instrumented-artifact (build (if target == "validator" { "workspace.validator" } else { "containers." + target }) args)
{{ _just_debuggable_ }}
declare -xr DOCKER_HOST="${DOCKER_HOST:-unix://{{docker_sock}}}"
case "{{target}}" in
"dataplane")
docker load < ./results/containers.dataplane
docker tag "ghcr.io/githedgehog/dataplane:{{version}}" "{{oci_image_dataplane}}"
echo "imported {{ oci_image_dataplane }}"
;;
"dataplane-debugger")
docker load < ./results/containers.dataplane-debugger
docker tag "ghcr.io/githedgehog/dataplane/debugger:{{version}}" "{{oci_image_dataplane_debugger}}"
echo "imported {{ oci_image_dataplane_debugger }}"
;;
"debug-tools")
# Uses nix only to produce a base image with the runtime closure (glibc, bash, etc.)
# then layers locally-compiled cargo binaries on top via Dockerfile.
# See the `build-container-quick` recipe.
docker load < ./results/containers.debug-tools
echo "imported debug-tools:dev"
;;
"frr.dataplane")
docker load < ./results/containers.frr.dataplane
docker tag "ghcr.io/githedgehog/dataplane/frr:{{version}}" "{{oci_image_frr_dataplane}}"
echo "imported {{oci_image_frr_dataplane}}"
;;
"frr.host")
docker load < ./results/containers.frr.host
docker tag "ghcr.io/githedgehog/dataplane/frr-host:{{version}}" "{{oci_image_frr_host}}"
echo "imported {{oci_image_frr_host}}"
;;
"validator")
echo "NOTE: validator image is wasm and not containerized"
;;
*)
>&2 echo "{{target}} is not a valid container"
exit 99
esac
# WARNING: The resulting image must NEVER be pushed to a shared registry.
# NOTE: this recipe intentionally does not depend on build-container "debug-tools" to make the call fast.
# Quick (non-sterile) container build using local cargo artifacts
[script]
build-container-quick:
{{ _just_debuggable_ }}
docker build \
--file ./Dockerfile \
--build-arg PROFILE="{{profile}}" \
--label sterile="false" \
--annotation sterile="false" \
--tag "dataplane:dev" \
.
echo "imported dataplane:dev"
# Build and push the dataplane container
[script]
push-container target="dataplane" *args: (build-container target args) && version
{{ _just_debuggable_ }}
declare -xr DOCKER_HOST="${DOCKER_HOST:-unix://{{docker_sock}}}"
# Preserve completed builds across transient registry failures. Skopeo
# retries blobs; this outer loop retries known-safe, idempotent whole pushes
# and announces them so registry degradation remains visible.
retry() {
declare -r what="$1"
shift
declare -ri attempts=4
declare -i attempt=1
declare -i delay
declare log
log="$(mktemp)"
declare -r log
while true; do
# Stream multi-gigabyte pushes so they do not appear hung.
if "$@" 2>&1 | tee "${log}"; then
rm -f -- "${log}"
return 0
fi
if [ "${attempt}" -ge "${attempts}" ]; then
>&2 echo "::error::${what} failed after ${attempts} attempts"
rm -f -- "${log}"
return 1
fi
# Match registry status and transport vocabulary shared by skopeo
# and oras. Bound 403 so it cannot match inside a digest.
if ! grep -qiE \
-e 'blob upload (unknown|invalid)|blob transfer' \
-e '\b(403|429|500|502|503|504)\b' \
-e 'forbidden|denied|too many requests|rate limit' \
-e 'internal server error|bad gateway|service unavailable|gateway time-?out' \
-e 'temporarily unavailable|try again' \
-e 'unexpected EOF|connection reset|broken pipe|i/o timeout|TLS handshake' \
"${log}"; then
>&2 echo "::error::${what} failed with a non-retryable error"
rm -f -- "${log}"
return 1
fi
delay=$(( 5 * 2 ** (attempt - 1) + RANDOM % 5 ))
>&2 echo "::warning::${what} failed (attempt ${attempt}/${attempts}), retrying in ${delay}s"
sleep "${delay}"
attempt=$(( attempt + 1 ))
done
}
push_image() {
declare -r image="$1"
retry "push of ${image}" \
skopeo copy --retry-times=3 --src-daemon-host="${DOCKER_HOST}" \
{{ _skopeo_dest_insecure }} "docker-daemon:${image}" "docker://${image}"
echo "Pushed ${image}"
}
case "{{target}}" in
"dataplane")
push_image "{{ oci_image_dataplane }}"
;;
"dataplane-debugger")
push_image "{{ oci_image_dataplane_debugger }}"
;;
"debug-tools")
>&2 echo "do not push the debug tools!"
exit 1
;;
"frr.dataplane")
push_image "{{oci_image_frr_dataplane}}"
;;
"frr.host")
push_image "{{oci_image_frr_host}}"
;;
"validator")
if [ "{{platform}}" != "wasm32-wasip1" ]; then
>&2 echo "Pushing non wasm32-wasip1 validator images is not supported, set platform=wasm32-wasip1"
exit 1
fi
pushd ./results/workspace.validator/bin
retry "push of {{ oci_image_dataplane_validator }}" \
oras push --annotation version="{{ version }}" "{{ oci_image_dataplane_validator }}" ./validator.wasm
popd
echo "Pushed {{ oci_image_dataplane_validator }}"
;;
*)
>&2 echo "{{target}} is not a valid container"
exit 99
esac
# Note: deliberately ignores all recipe parameters save version, debug_justfile,
# oci_repo, and the jobs/cores build-parallelism caps.
# Pushes all release container images.
[script]
push:
{{ _just_debuggable_ }}
for container in dataplane frr.dataplane validator; do
if [ "${container}" = "validator" ]; then
platform="wasm32-wasip1"
else
platform="x86-64-v3"
fi
just jobs="{{jobs}}" cores="{{cores}}" debug_justfile="{{debug_justfile}}" oci_repo="{{oci_repo}}" version="{{version}}" profile=release platform="${platform}" sanitize= instrument=none push-container "${container}"
done
# Print names of container images to build or push
[script]
print-container-tags:
echo "{{ oci_image_dataplane }}"
# Check dependency licenses, bans, sources and security advisories
[arg("advisories", long="no-advisories", value="false")]
[script]
check-dependencies advisories="true":
{{ _just_debuggable_ }}
# cargo-deny has no option to skip a check, list the others instead.
cargo deny {{ _cargo_feature_flags }} check {{ if advisories == "false" { "licenses bans sources" } else { "" } }}
# Check security advisories, failing only on those not already reported for "base".
#
# Unlike the other cargo-deny checks, advisories change over time: a new RUSTSEC entry for a
# crate already used on main would otherwise fail every PR and merge queue run. Advisories
# already present on the base are reported as warnings, and passed as output "result" in GitHub
# Actions. With "--all", fail on all advisories instead, without comparing with the base.
[arg("all", long="all", value="true")]
[script]
check-advisories base="origin/main" all="false":
{{ _just_debuggable_ }}
declare tmp
tmp="$(mktemp -d)"
declare -r tmp
trap 'rm -rf "${tmp}"; git worktree prune' EXIT
# Compare with the fork point, so that changes made on the base since then are not ours.
declare fork=""
if [ "{{ all }}" != "true" ]; then
fork="$(git merge-base "{{ base }}" HEAD)"
fi
declare -r fork
# Fetch the database once, then run offline, so that both sides see the same advisories.
cargo deny fetch db
# Print one "<advisory or code> <crate>" line per error; fail if cargo-deny itself failed.
# The version is left out, so that bumping a crate to a version that is still affected
# does not count as a new failure.
deny_errors() {
local -r dir="$1" out="$2"
local -i rc=0
(cd "${dir}" && cargo fetch --locked >/dev/null)
(cd "${dir}" && cargo deny --offline --format json {{ _cargo_feature_flags }} check advisories) \
2>"${out}.json" || rc=$?
jq -rR 'fromjson? | select(.type == "diagnostic" and .fields.severity == "error")
| .fields
| "\(.advisory.id // .code) \(.graphs[]?.Krate.name // "-")"' "${out}.json" \
| sort -u >"${out}"
if [ "${rc}" -ne 0 ] && [ ! -s "${out}" ]; then
>&2 jq -rR 'fromjson? // {fields: {message: .}} | .fields.message' "${out}.json"
return 1
fi
}
if ! deny_errors . "${tmp}/head"; then
>&2 echo "::error::cargo-deny failed to check advisories"
exit 1
fi
if [ -z "${fork}" ]; then
: >"${tmp}/base"
elif [ ! -s "${tmp}/head" ] \
|| git diff --quiet "${fork}" -- Cargo.lock deny.toml ':(glob)**/Cargo.toml'; then
# No change to the dependency graph or to the configuration: nothing can be new.
cp "${tmp}/head" "${tmp}/base"
else
git worktree add --quiet --detach "${tmp}/base-tree" "${fork}"
if ! deny_errors "${tmp}/base-tree" "${tmp}/base"; then
# Fail closed: count everything as new.
>&2 echo "::warning::cargo-deny failed on {{ base }}, cannot tell which advisories are new"
: >"${tmp}/base"
fi
fi
comm -12 "${tmp}/head" "${tmp}/base" >"${tmp}/known"
comm -23 "${tmp}/head" "${tmp}/base" >"${tmp}/new"
declare id crate
while read -r id crate; do
echo "::warning::${id} (${crate}) is already reported on {{ base }}"
done <"${tmp}/known"
if [ -n "${GITHUB_OUTPUT:-}" ]; then
{
echo "result<<EOF"
cat "${tmp}/known"
echo "EOF"
} >>"${GITHUB_OUTPUT}"
fi
while read -r id crate; do
if [ -z "${fork}" ]; then
>&2 echo "::error::${id} (${crate})"
else
>&2 echo "::error::${id} (${crate}) is not reported on {{ base }}"
fi
done <"${tmp}/new"
if [ -s "${tmp}/new" ]; then
# Show the full diagnostics, in human-readable form.
cargo deny --offline {{ _cargo_feature_flags }} check advisories || true
exit 1
fi
# Ensure the shared dependency derivations stay reusable across revisions.
#
# Two things break that, and they are different kinds of thing, so they take
# different questions.
#
# The workspace source is a store path, so "the dependency build must not
# depend on it" is a statement about the derivation graph and nix can answer it
# outright: instantiate once and read the inputs. That is exact, it names the
# offending path, and it needs no edit to the working tree.
#
# The git version is a string. It reaches a derivation as an environment
# variable and never as an input path, so no graph walk can see it; the only
# way to ask is to instantiate under two tags and compare.
#
# Both have regressed before, and both surface as a slow cache miss rather than
# a failure, which is why they are checked at all.
[script]
check-deps-reuse:
{{ _just_debuggable_ }}
# Keep Nix stderr; it is the only diagnostic when instantiation fails.
declare src
src="$(nix eval --raw --impure --expr '(import ./default.nix { }).src.outPath')"
declare -r src
if [ -z "${src}" ]; then
>&2 echo "::error::could not resolve the workspace source path"
exit 1
fi
deps_drv() {
declare drv
drv="$(nix-instantiate default.nix -A "$1" --argstr tag "$3" | tail -1)"
grep -ao "/nix/store/[a-z0-9]\{32\}-$2[^\"]*\.drv" "${drv}" | sort -u
}
# Report through the status; command substitution would run this in a
# subshell and discard failure-count updates.
check_reuse() {
declare -r attr="$1" name="$2"
declare baseline
if ! baseline="$(deps_drv "${attr}" "${name}" dev)" || [ -z "${baseline}" ]; then
>&2 echo "::error::could not resolve ${name} from ${attr}"
return 1
fi
# The source question, put to the graph.
declare drv
while IFS= read -r drv; do
[ -z "${drv}" ] && continue
if nix-store -q --requisites "${drv}" | grep -qxF "${src}"; then
>&2 echo "::error::${name} depends on the workspace source"
>&2 echo " ${src}"
>&2 echo " is a build input of ${drv}"
return 1
fi
done <<<"${baseline}"
# The version question, put to two instantiations.
declare tagged
if ! tagged="$(deps_drv "${attr}" "${name}" v0.25.2-15-gdeadbee-dirty)"; then
>&2 echo "::error::could not resolve ${name} from ${attr} with a release tag"
return 1
fi
if [ "${tagged}" != "${baseline}" ]; then
>&2 echo "::error::${name} depends on the git version"
>&2 echo " tag=dev -> ${baseline}"
>&2 echo " tag=v0.. -> ${tagged}"
return 1
fi
printf '%s is reusable: %s\n' "${name}" "${baseline}"
}
# Check production and test flag sets independently: a regression in a
# production-only flag would sail past a test-only guard.
declare -r -A targets=(
[workspace.dataplane]="dataplane-deps"
[tests.all]="dataplane-tests-deps"
)
declare -i failures=0
for attr in "${!targets[@]}"; do
check_reuse "${attr}" "${targets[${attr}]}" || failures=$(( failures + 1 ))