forked from ClickHouse/walshadow
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstream.rs
More file actions
3734 lines (3599 loc) · 154 KB
/
Copy pathstream.rs
File metadata and controls
3734 lines (3599 loc) · 154 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
//! `walshadow-stream` — full WAL capture pipeline.
//!
//! Connects to source PG in replication mode, `IDENTIFY_SYSTEM` then
//! `START_REPLICATION PHYSICAL` (optionally bound to a permanent slot),
//! filters every WAL byte, writes filtered segments shadow PG reads via
//! `restore_command`.
//!
//! ```text
//! walshadow-stream \
//! --host /tmp/source_sock --port 5432 --user postgres --dbname postgres \
//! --shadow-socket-dir /tmp/shadow_sock --shadow-port 5433 \
//! --out-dir /var/lib/walshadow/filtered \
//! [--slot walshadow_phys] \
//! [--start-lsn 0/16B3750] \
//! [--metrics-bind 127.0.0.1:9484] \
//! [--retention-bytes 268435456]
//! ```
// The pipeline allocates rows on the decode thread(s) and frees them on the
// batcher thread; mimalloc's per-thread caches handle that produce-here/
// free-there pattern far better than glibc's shared arena (which serializes on
// its arena lock under that cross-thread churn).
#[global_allocator]
static GLOBAL: mimalloc::MiMalloc = mimalloc::MiMalloc;
use std::net::SocketAddr;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{Duration, Instant};
use ahash::HashSet;
use anyhow::{Context, Result};
use clap::{Parser, ValueEnum};
use std::fs;
use std::future::Future;
use std::pin::Pin;
use tokio::sync::{Mutex, watch};
use tokio_postgres::types::PgLsn;
use tokio_util::sync::CancellationToken;
use walrus::pg::backup::{BACKUP_NAME_PREFIX, format_pg_lsn};
use walrus::pg::replication::base_backup::BaseBackupOpts;
use walrus::pg::replication::conn::PgConfig;
use walrus::pg::replication::tls::{SslMode, TlsParams};
use walshadow::backfill_bootstrap::{
BootstrapConfig, BootstrapOutcome, drain_backfill, seed_in_snapshot, spawn_greenfield_bootstrap,
};
use walshadow::backup_source::BackupSource;
use walshadow::backup_source_direct::DirectSource;
use walshadow::backup_source_object_store::ObjectStoreSource;
use walshadow::boundary_hold::{
BoundaryGateConfig, BoundaryHoldSink, BoundaryHoldStats, CatalogBoundaryGate,
};
use walshadow::ch_emitter::{EmitterConfig, EmitterStats};
use walshadow::config::{CliOverrides, ConfigResolver, ResolvedConfig};
use walshadow::decoder_sink::MetricsTupleObserver;
use walshadow::manifest;
use walshadow::mapping::MappingHandle;
use walshadow::metrics::{MetricsRegistry, MetricsSnapshot, RateEstimator};
use walshadow::pg::{quote_ident, socket_conninfo};
use walshadow::pipeline::{Fatal, PipelineConfig, TailKind, bootstrap, tail};
use walshadow::queueing_record_sink::{
DEFAULT_QUEUEING_BATCH_SIZE, DEFAULT_QUEUEING_RECORD_SINK_CAPACITY, QueueingRecordSink,
};
use walshadow::record::{MetricsRecordSink, Record, RecordSink, SinkError, WAL_SEG_SIZE};
use walshadow::retention::{
DEFAULT_RETENTION_BYTES, DEFAULT_TRIM_INTERVAL, max_segment_end, trim_below_lsn,
};
use walshadow::runtime_config::InitialLoadMode;
use walshadow::schema::{RelName, SchemaEvent};
use walshadow::segment_sink::{DirSegmentSink, SegFsync};
use walshadow::shadow::{ResumeOutcome, Shadow, ShadowConfig};
use walshadow::shadow_catalog::{ShadowCatalog, ShadowCatalogConfig, with_transient_retry};
use walshadow::source_feed::{SourceFeed, StandbyStatus};
use walshadow::toast::ToastResolver;
use walshadow::wal_stream::WalStream;
use walshadow::xact_buffer::{BufferingDecoderSink, SubxactTracker, XactBuffer, XactBufferConfig};
/// Choose bootstrap source for empty shadow data dir
/// Initialized data dir resumes regardless of mode
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum, Default)]
enum BootstrapMode {
/// Never bootstrap. Without `--bootstrap-shadow-data-dir`, manage shadow
/// externally. With data dir, manage initialized cluster but reject
/// empty dir
#[default]
Off,
/// Source-PG-driven BASE_BACKUP over the replication protocol,
/// reuses `--host` / `--port` / `--user`, no extra credentials
Direct,
/// wal-g-compatible BASE_BACKUP from a `DynStorage` bucket. Storage
/// config read from `[backup]` in `--ch-config`;
/// `--bootstrap-backup-name` selects the backup (LATEST = newest sentinel)
ObjectStore,
}
/// `decoder + xact_drain` pair as one `RecordSink` for the queueing worker.
///
/// Order matters: decoder absorbs the heap record into the xact buffer
/// before xact_drain flushes the matching commit/abort. A multi-statement
/// xact whose COMMIT lands in the same dispatch batch as its heap records
/// would otherwise miss the latest writes.
struct DecoderXactPair<D: RecordSink + Send> {
decoder: BufferingDecoderSink,
xact_drain: D,
}
impl<D: RecordSink + Send> RecordSink for DecoderXactPair<D> {
fn on_record<'a>(
&'a mut self,
record: &'a Record<'a>,
) -> Pin<Box<dyn Future<Output = Result<(), SinkError>> + Send + 'a>> {
Box::pin(async move {
self.decoder.on_record(record).await?;
self.xact_drain.on_record(record).await?;
Ok(())
})
}
fn on_idle<'a>(
&'a mut self,
) -> Pin<Box<dyn Future<Output = Result<(), SinkError>> + Send + 'a>> {
// Decoder has no time-based work; xact_drain forwards to the
// CH emitter's deadline check.
self.xact_drain.on_idle()
}
fn on_close<'a>(
&'a mut self,
) -> Pin<Box<dyn Future<Output = Result<(), SinkError>> + Send + 'a>> {
// Decoder has no close work; xact_drain forwards the final flush.
self.xact_drain.on_close()
}
fn on_idle_advance<'a>(
&'a mut self,
lsn: u64,
) -> Pin<Box<dyn Future<Output = Result<(), SinkError>> + Send + 'a>> {
self.xact_drain.on_idle_advance(lsn)
}
}
/// Daemon-side `RecordSink` composite.
///
/// `metrics` stays synchronous on the pump task (counter bumps, never
/// await). The decoder/xact-drain pair runs behind a [`QueueingRecordSink`]
/// so its `wait_for_replay` waits don't park the pump task: each gate
/// would freeze wire delivery for a full shadow apply round-trip and
/// couple wire pacing to decode.
struct DaemonSinks {
metrics: MetricsRecordSink,
/// Queueing sink wrapped with the catalog-boundary publication hold:
/// at a catalog-mutating commit the pump parks here until shadow
/// replays through the commit's `next_lsn`, so successor bytes reach
/// neither the shadow wire nor the archive while held.
decoder_xact: BoundaryHoldSink,
/// Shared with the `BufferingDecoderSink` on the queueing worker;
/// status loop polls without contending on the worker.
decoder_stats: Arc<walshadow::decoder_sink::DecoderStats>,
/// Shared with parallel pipeline's inserter pool (bumps counters
/// post-`EndOfStream`). `None` when no CH pipeline is wired.
emitter_stats: Option<Arc<walshadow::ch_emitter::EmitterStats>>,
/// Per-txn span map; `Some` only with OTLP on. Registering at WAL read
/// (here) makes the `txn` span cover the pump→worker channel wait.
span_registry: Option<walshadow::trace::TxnSpanRegistry>,
}
impl RecordSink for DaemonSinks {
fn on_record<'a>(
&'a mut self,
record: &'a Record<'a>,
) -> Pin<Box<dyn Future<Output = Result<(), SinkError>> + Send + 'a>> {
Box::pin(async move {
// Register at WAL read (pre-channel) so the span covers the queue wait.
if let Some(reg) = &self.span_registry {
reg.open(record.parsed.header.xact_id, record.source_lsn);
}
self.metrics.on_record(record).await?;
self.decoder_xact.on_record(record).await?;
Ok(())
})
}
}
/// `walshadow-stream ctl <words…>`: drive a running daemon's control socket.
/// Detected before daemon-arg parsing so `ctl` needn't supply daemon args.
#[derive(Debug, Parser)]
#[command(
name = "walshadow-stream ctl",
about = "Control a running walshadow-stream daemon."
)]
struct CtlArgs {
#[arg(
long,
env = "WALSHADOW_CONTROL_SOCKET",
default_value = "/run/walshadow/control.sock"
)]
socket: PathBuf,
/// Control verb, such as `status` or `apply`, read TOML body from stdin
#[arg(trailing_var_arg = true, required = true)]
request: Vec<String>,
}
#[derive(Debug, Parser)]
#[command(
name = "walshadow-stream",
about = "Stream + filter physical WAL from source PG."
)]
struct Args {
/// Source PG host (TCP) or unix socket directory (leading `/`)
#[arg(long, default_value = "localhost")]
host: String,
#[arg(long, default_value_t = 5432)]
port: u16,
#[arg(long, default_value = "postgres")]
user: String,
#[arg(long, default_value = "postgres")]
dbname: String,
/// Optional cleartext password. Replication-mode auth supports
/// trust / cleartext / SCRAM-SHA-256.
#[arg(long)]
password: Option<String>,
/// SSL mode: `disable`, `allow`, `prefer`, `require`, `verify-ca`,
/// `verify-full`. Skipped on unix sockets regardless. verify-ca /
/// verify-full consult `PGSSLROOTCERT` (else webpki bundle) for the
/// trust anchor, same contract as libpq.
#[arg(long, default_value = "prefer")]
sslmode: String,
/// Where filtered segments + manifests land; shadow PG's
/// `restore_command` reads from here
#[arg(long)]
out_dir: PathBuf,
/// CLI override for the TOML's `[source] slot` (physical replication
/// slot). Unset defers to config; unset in both = slotless.
#[arg(long)]
slot: Option<String>,
/// Start LSN in `X/Y` hex form. Defaults to source's current
/// `pg_current_wal_lsn` (per `IDENTIFY_SYSTEM`), aligned down to a
/// segment boundary.
#[arg(long)]
start_lsn: Option<String>,
#[arg(long, default_value_t = 10)]
status_interval: u64,
/// Stop after this many segments shipped (smoke tests). Zero = forever.
#[arg(long, default_value_t = 0)]
max_segments: u64,
/// Shadow PG unix socket directory. Reused as libpq `host=` since
/// libpq treats a leading `/` as a socket dir.
#[arg(long)]
shadow_socket_dir: PathBuf,
#[arg(long, default_value_t = 5432)]
shadow_port: u16,
#[arg(long, default_value = "postgres")]
shadow_user: String,
#[arg(long, default_value = "postgres")]
shadow_dbname: String,
/// Wall-clock budget for the initial connect against shadow PG.
/// Reused by [`with_transient_retry`] so a still-warming shadow
/// doesn't fail the daemon on first boot.
#[arg(long, default_value_t = 30)]
shadow_connect_timeout: u64,
/// Unix socket of the pgext bridge worker. On a daemon-owned shadow
/// this also writes `shared_preload_libraries` and the
/// `walshadow.*` GUCs into shadow's conf, so the worker starts.
/// Defaults to `<shadow-socket-dir>/walshadow-bridge.sock`.
#[arg(long)]
bridge_socket: Option<PathBuf>,
/// Directory holding `walshadow.so` when it isn't in PG's `$libdir`,
/// ie a build tree instead of `make install`. Written as
/// `dynamic_library_path`.
#[arg(long)]
bridge_lib_dir: Option<PathBuf>,
/// Walsender bind address. `127.0.0.1:0` lets the kernel pick a free
/// port, valid only for externally managed shadow (no
/// `--bootstrap-shadow-data-dir`): operator reads
/// `--walsender-port-file` and configures `primary_conninfo` by hand.
/// Daemon-owned shadow bakes this address into shadow's generated
/// `primary_conninfo` before shadow starts, so it rejects port 0 —
/// pass an explicit port there.
#[arg(long, default_value = "127.0.0.1:0")]
walsender_bind: SocketAddr,
/// File the daemon writes the bound walsender address into (one line
/// `host:port`). For `--walsender-bind` port 0: operator reads it to
/// learn the picked port and configures shadow's `primary_conninfo`.
#[arg(long)]
walsender_port_file: Option<PathBuf>,
/// Slow-client backpressure: bytes queued onto a slow shadow
/// connection before it's dropped + the wire falls back to
/// `restore_command`.
#[arg(long, default_value_t = 64 * 1024 * 1024)]
walsender_slow_threshold: usize,
/// Seconds the pump waits for shadow's walreceiver to attach before
/// processing records. Must be positive; no attachment within it fails
/// startup. Catalog-boundary holds require a live wire: whole archive
/// segments can't stop publication at a mid-segment commit, so
/// archive-only operation (the old `0` escape hatch) is rejected.
/// `ShadowStreamSink` also drops bytes pushed before a connection
/// registers; a pump racing past shadow's `START_REPLICATION` LSN
/// leaves an apply LSN that never advances.
#[arg(long, default_value_t = 60)]
walsender_connect_timeout: u64,
/// Seconds a catalog-boundary publication hold may wait for shadow to
/// replay through a catalog-mutating commit before failing the daemon.
/// Keep well under source's `wal_sender_timeout` (default 60s): the
/// pump answers no source keepalives while parked.
#[arg(long, default_value_t = 30)]
catalog_hold_timeout: u64,
/// Soft cap on in-flight records for the `QueueingRecordSink` feeding
/// the decoder / xact-drain worker. Past this watermark the pump
/// yields to let the worker drain; a stuck worker still surfaces via
/// the catalog `wait_for_replay` timeout on the err slot.
#[arg(long, default_value_t = DEFAULT_QUEUEING_RECORD_SINK_CAPACITY)]
decoder_queue_capacity: usize,
/// Pump-side batch size for the `QueueingRecordSink`. Bigger
/// amortises per-send overhead but adds pump→worker latency (worker's
/// `wait_for_replay` lags one batch behind).
#[arg(long, default_value_t = DEFAULT_QUEUEING_BATCH_SIZE)]
decoder_batch_size: usize,
/// Decode-pool size (M): parallel decode workers (detoast, type
/// coercion, oracle resolution). Only with `--ch-config`. `1` keeps
/// decode serial so per-table WAL order is preserved; M>1 relaxes
/// per-table order, relying on `_lsn` ReplacingMergeTree dedup.
#[arg(long, default_value_t = 1)]
decoder_pool_size: usize,
/// Insert-pool size (N): concurrent ClickHouse INSERT connections.
/// Cloud throughput is RTT/part-commit bound, so N>1 is the main
/// throughput lever. Only with `--ch-config`.
#[arg(long, default_value_t = 1)]
inserter_pool_size: usize,
/// Xact / TOAST buffer spill dir. Wiped every startup per the
/// crash-recovery contract in [plans/xact.md](../../plans/xact.md).
#[arg(long)]
spill_dir: PathBuf,
/// In-memory xact buffer budget in bytes. Default matches PG's
/// `logical_decoding_work_mem` (64 MiB).
#[arg(long, default_value_t = walshadow::xact_buffer::DEFAULT_XACT_BUFFER_MAX)]
xact_buffer_max: usize,
/// CH-Native emitter config (TOML). Set → drained tuples ship to
/// ClickHouse via `clickhouse-c-rs`; unset → metrics-only. Shape: see
/// [`walshadow::ch_emitter::EmitterConfig::from_toml_str`]. Reloaded on
/// SIGHUP (atomic mapping swap; connection params stay boot-only).
#[arg(long)]
ch_config: Option<PathBuf>,
/// CLI override for the TOML's `[ch] flush_timeout_ms`. On the live
/// pipeline `0` (default) selects a 100ms partial-batch deadline so
/// cold tables can't pin the watermark; positive sets it explicitly.
/// No per-xact-close path runs on the live drain (survives only in
/// bootstrap backfill, forced internally). SIGHUP reads `--ch-config`
/// only, so use this flag for the boot value when not maintaining the
/// knob in TOML.
#[arg(long)]
ch_flush_timeout_ms: Option<u64>,
/// CLI override for the TOML's `[ch] drop_table_strategy` (`retain` /
/// `drop` / `warn`). Highest-precedence layer: wins over TOML and
/// survives SIGHUP reload, so an operator can pin the drop policy from
/// the command line without editing TOML. Absent defers to TOML.
#[arg(long)]
drop_table_strategy: Option<String>,
/// HTTP/Prometheus metrics bind address. Disabled when absent.
#[arg(long)]
metrics_bind: Option<SocketAddr>,
/// Control socket path, omit to disable control API
#[arg(long)]
control_socket: Option<PathBuf>,
/// OTLP/gRPC endpoint for traces, e.g. `http://localhost:4317`. Absent
/// disables tracing (zero overhead); falls back to
/// `OTEL_EXPORTER_OTLP_ENDPOINT`. Spans emit at the `walshadow::trace`
/// target.
#[arg(long)]
otlp_endpoint: Option<String>,
/// Fraction of transactions to trace, `[0.0, 1.0]`. Head-sampled per txn
/// (see `trace::should_sample`), so per-record span cost scales with it.
#[arg(long, default_value_t = 0.01)]
trace_sample_ratio: f64,
/// WAL retention horizon in bytes. Segments older than
/// `shadow_replay_lsn - retention_bytes` deleted every trim cycle.
/// `0` disables trim.
#[arg(long, default_value_t = DEFAULT_RETENTION_BYTES)]
retention_bytes: u64,
/// Skip pre-flight validators (server_version_num, wal_level, replica
/// identity / row key, slot existence). For recovery drills.
#[arg(long, default_value_t = false)]
skip_preflight: bool,
/// Ignore `manifest.toml` resume LSNs under `--spill-dir` at boot
/// (greenfield resume even when a prior daemon left one), adopt a
/// changed source timeline, and authorize boot past an unreadable or
/// corrupt manifest (otherwise fatal). Source identity gate still
/// applies; the manifest rewrites as the new daemon progresses. For
/// "wipe + restart from a known LSN" drills.
#[arg(long, default_value_t = false)]
ignore_cursor: bool,
/// Bootstrap source for empty shadow data dir. `off` never bootstraps;
/// `direct` runs BASE_BACKUP over current replication connection;
/// `object_store` reads wal-g-format backup from `[backup]` in
/// `--ch-config`. Initialized data dir resumes without bootstrap
/// regardless of mode
#[arg(long, value_enum, default_value_t = BootstrapMode::Off)]
bootstrap_mode: BootstrapMode,
/// Shadow PG data dir. When set, daemon bootstraps or resumes shadow,
/// writes config, starts and supervises postmaster, then stops it on
/// exit. When unset, manage shadow externally. Required when
/// `--bootstrap-mode != off`
#[arg(long)]
bootstrap_shadow_data_dir: Option<PathBuf>,
/// Object-store backup name. `LATEST` resolves to newest sentinel;
/// otherwise the literal `base_TTTTTTTTLLLLLLLLSSSSSSSS` form. Required
/// when `--bootstrap-mode=object_store`.
#[arg(long, default_value = "LATEST")]
bootstrap_backup_name: String,
/// Object-store fan-out parallelism. Raise for high-bandwidth buckets.
#[arg(long, default_value_t = 4)]
bootstrap_object_store_parallelism: usize,
/// BASE_BACKUP fast-checkpoint flag for `direct` mode. `true` avoids
/// waiting for source's checkpoint_timeout; flip off if checkpoint
/// cost matters more than bootstrap latency.
#[arg(long, default_value_t = true)]
bootstrap_fast_checkpoint: bool,
/// Maximum seconds to wait for shadow replay after bootstrap
/// Abort daemon when timeout expires
#[arg(long, default_value_t = 300)]
bootstrap_shadow_replay_timeout: u64,
}
impl Args {
fn bridge_socket_path(&self) -> PathBuf {
self.bridge_socket
.clone()
.unwrap_or_else(|| self.shadow_socket_dir.join("walshadow-bridge.sock"))
}
}
#[tokio::main(flavor = "multi_thread", worker_threads = 4)]
async fn main() -> Result<()> {
// `ctl` client mode is detected before daemon-arg parsing so it needn't
// supply the daemon's required args.
let argv: Vec<String> = std::env::args().collect();
if argv.get(1).map(String::as_str) == Some("ctl") {
let rest = std::iter::once(format!("{} ctl", argv[0])).chain(argv.into_iter().skip(2));
let ctl = CtlArgs::parse_from(rest);
return run_ctl(ctl.socket, ctl.request).await;
}
let args = Args::parse();
walshadow::trace::set_sample_ratio(args.trace_sample_ratio);
// `--otlp-endpoint` wins; otherwise honor the conventional env var.
let otlp_endpoint = args
.otlp_endpoint
.clone()
.or_else(|| std::env::var("OTEL_EXPORTER_OTLP_ENDPOINT").ok());
let tracer_provider = init_tracing(otlp_endpoint.as_deref());
let result = run(args).await;
// The batch span processor lives on a background thread, so a bare
// process exit drops whatever it hasn't flushed. Drain it before we
// return (best-effort — a failed flush must not mask `run`'s result).
if let Some(provider) = tracer_provider
&& let Err(e) = provider.shutdown()
{
tracing::warn!(target: "walshadow", error = %e, "otlp tracer shutdown");
}
result
}
async fn run_ctl(socket: PathBuf, request: Vec<String>) -> Result<()> {
use std::io::{IsTerminal, Read};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
let verb = request.first().map(String::as_str).unwrap_or_default();
let config: toml::Table = if std::io::stdin().is_terminal() {
toml::Table::new()
} else {
let mut body = String::new();
std::io::stdin().read_to_string(&mut body)?;
body.parse().context("parse config body as TOML")?
};
let doc = walshadow::control::encode_request(verb, config)?;
let mut stream = tokio::net::UnixStream::connect(&socket)
.await
.with_context(|| format!("connect control socket {}", socket.display()))?;
stream.write_all(doc.as_bytes()).await?;
stream.flush().await?;
stream.shutdown().await.ok();
let mut resp = String::new();
stream.read_to_string(&mut resp).await?;
let first = resp.lines().next().unwrap_or("");
if let Some(rest) = first.strip_prefix("OK") {
let rest = rest.trim();
if !rest.is_empty() {
println!("{rest}");
}
for l in resp.lines().skip(1) {
println!("{l}");
}
Ok(())
} else {
eprint!("{resp}");
std::process::exit(1);
}
}
/// OTLP/gRPC batch tracer provider for `endpoint`. Must run inside the tokio
/// runtime (tonic exporter + batch worker need it).
fn build_otlp_provider(
endpoint: &str,
) -> anyhow::Result<opentelemetry_sdk::trace::SdkTracerProvider> {
use opentelemetry_otlp::WithExportConfig;
use opentelemetry_sdk::Resource;
use opentelemetry_sdk::trace::{Sampler, SdkTracerProvider};
let exporter = opentelemetry_otlp::SpanExporter::builder()
.with_tonic()
.with_endpoint(endpoint)
.build()?;
// Head sampling happens at span creation (per txn, see TxnSpanRegistry),
// so the SDK exports everything it's handed.
Ok(SdkTracerProvider::builder()
.with_sampler(Sampler::AlwaysOn)
.with_batch_exporter(exporter)
.with_resource(Resource::builder().with_service_name("walshadow").build())
.build())
}
/// Wire `tracing` once per process (`RUST_LOG` filter, default
/// `warn,walshadow=info`). With `otlp_endpoint` set, stacks an OTel layer on
/// the stderr `fmt` layer; the returned provider must be `.shutdown()` at exit.
fn init_tracing(
otlp_endpoint: Option<&str>,
) -> Option<opentelemetry_sdk::trace::SdkTracerProvider> {
use opentelemetry::trace::TracerProvider as _;
use tracing_subscriber::EnvFilter;
use tracing_subscriber::prelude::*;
let fmt_layer = tracing_subscriber::fmt::layer()
.with_target(true)
.with_writer(std::io::stderr);
// Best-effort: a bad endpoint logs and degrades to no-traces rather
// than refusing to boot — observability never blocks the pipeline.
let provider = if let Some(endpoint) = otlp_endpoint {
match build_otlp_provider(endpoint) {
Ok(p) => {
opentelemetry::global::set_tracer_provider(p.clone());
Some(p)
}
Err(e) => {
eprintln!("walshadow: OTLP exporter init failed for {endpoint}: {e:#}");
None
}
}
} else {
None
};
// `walshadow::trace` spans only feed the OTLP exporter; with none attached
// they are pure per-record overhead, so disable that target — unless the
// user explicitly set it in RUST_LOG.
let user_set_trace = std::env::var("RUST_LOG")
.map(|v| v.contains("walshadow::trace"))
.unwrap_or(false);
let filter =
EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("warn,walshadow=info"));
let filter = if provider.is_some() || user_set_trace {
filter
} else {
filter.add_directive(
"walshadow::trace=off"
.parse()
.expect("static trace-off directive parses"),
)
};
let otel_layer = provider
.as_ref()
.map(|p| tracing_opentelemetry::layer().with_tracer(p.tracer("walshadow")));
let _ = tracing_subscriber::registry()
.with(filter)
.with(fmt_layer)
.with(otel_layer)
.try_init();
provider
}
fn tget(root: &toml::Table, section: &str, key: &str) -> Option<String> {
match root.get(section)?.as_table()?.get(key)? {
toml::Value::String(s) => Some(s.clone()),
v => Some(v.to_string()),
}
}
/// `[source]` defaults from the CLI args — the base layer under the config file
/// for connection resolution, shared by the session and the control surface.
fn cli_source_base(args: &Args) -> toml::Table {
let mut s = toml::Table::new();
s.insert("host".into(), args.host.clone().into());
s.insert("port".into(), (args.port as i64).into());
s.insert("user".into(), args.user.clone().into());
s.insert("dbname".into(), args.dbname.clone().into());
if let Some(p) = &args.password {
s.insert("password".into(), p.clone().into());
}
s.insert("sslmode".into(), args.sslmode.clone().into());
let mut root = toml::Table::new();
root.insert("source".into(), toml::Value::Table(s));
root
}
fn spawn_sighup_reload(
mut sig: tokio::signal::unix::Signal,
reloader: Arc<walshadow::control::Reloader>,
) -> tokio::task::JoinHandle<()> {
tokio::spawn(async move {
while sig.recv().await.is_some() {
tracing::info!(target: "walshadow", "SIGHUP — live reload");
if let Err(e) = reloader.reload().await {
tracing::warn!(target: "walshadow", error = %format!("{e:#}"), "reload failed");
}
}
})
}
/// Enforce capability, not flag value: catalog-boundary holds need an
/// active walreceiver, so archive-only operation is not startable.
fn validate_transport_args(args: &Args) -> Result<()> {
anyhow::ensure!(
args.walsender_connect_timeout > 0,
"--walsender-connect-timeout 0 (archive-only shadow) is unsupported: \
catalog-boundary publication holds require an attached walreceiver",
);
anyhow::ensure!(
args.catalog_hold_timeout > 0,
"--catalog-hold-timeout must be positive",
);
Ok(())
}
/// Process-lifetime entry: bind metrics + control socket + SIGHUP, then stream
/// one session. Every reconfigure (socket / SIGHUP) is a live reload — no
/// restart. Ctrl-C breaks the pump loop and drains gracefully.
async fn run(args: Args) -> Result<()> {
use walshadow::control::{Reloader, SharedCtx};
validate_transport_args(&args)?;
let sighup = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::hangup())
.inspect_err(|e| {
tracing::warn!(
target: "walshadow::sighup",
error = %e,
"SIGHUP install failed",
);
})?;
// Match systemd SIGTERM with ctrl_c shutdown path
let sigterm = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())
.inspect_err(|e| {
tracing::warn!(
target: "walshadow",
error = %e,
"SIGTERM install failed",
);
})?;
let metrics = MetricsRegistry::new();
let reloader = Arc::new(Reloader::default());
let _metrics_server = if let Some(addr) = args.metrics_bind {
let (bound, h) = walshadow::metrics::serve(addr, metrics.clone())
.await
.context("bind metrics endpoint")?;
tracing::info!(target: "walshadow::metrics", addr = %bound, "metrics endpoint serving");
Some(h)
} else {
None
};
let _control_server = if let Some(sock) = args.control_socket.clone() {
let ch_config = args
.ch_config
.clone()
.context("--control-socket requires --ch-config")?;
let ctx = SharedCtx {
ch_config,
source_base: cli_source_base(&args),
metrics: metrics.clone(),
reloader: reloader.clone(),
frag_lock: Arc::new(Mutex::new(())),
};
Some(
walshadow::control::serve(sock, ctx)
.await
.context("bind control socket")?,
)
} else {
None
};
let _sighup = spawn_sighup_reload(sighup, reloader.clone());
run_session(&args, &metrics, &reloader, sigterm).await
}
async fn run_session(
args: &Args,
metrics: &MetricsRegistry,
reloader: &Arc<walshadow::control::Reloader>,
mut sigterm: tokio::signal::unix::Signal,
) -> Result<()> {
// Clone the Arc-backed registry so the body's `&metrics` uses are unchanged.
let metrics = metrics.clone();
let merged: toml::Table = match args.ch_config.as_deref() {
Some(p) => walshadow::ch_emitter::load_effective(p, cli_source_base(args))
.await
.with_context(|| format!("load config {}", p.display()))?,
None => cli_source_base(args),
};
let sslmode = SslMode::parse(&tget(&merged, "source", "sslmode").unwrap_or_default())
.context("--sslmode")?;
let cfg = PgConfig {
host: tget(&merged, "source", "host").unwrap_or_default(),
port: tget(&merged, "source", "port")
.and_then(|v| v.parse().ok())
.unwrap_or(args.port),
user: tget(&merged, "source", "user").unwrap_or_default(),
password: tget(&merged, "source", "password"),
database: tget(&merged, "source", "dbname").unwrap_or_default(),
application_name: "walshadow".into(),
sslmode,
tls: TlsParams::resolve(&walrus::config::Vars::default()),
};
let mut feed = SourceFeed::connect(&cfg)
.await
.context("connect to source PG")?
.with_status_interval(Duration::from_secs(args.status_interval));
let ident = feed.identify_system().await.context("IDENTIFY_SYSTEM")?;
tracing::info!(
target: "walshadow",
sysid = %ident.sysid,
timeline = ident.timeline,
xlogpos = format_pg_lsn(ident.xlogpos).to_string(),
"source identified",
);
// `[ch]` presence decides emitter vs metrics-only.
let ch_config = if merged.contains_key("ch") {
let mut cfg = EmitterConfig::from_table(&merged).context("parse ch config")?;
if let Some(ms) = args.ch_flush_timeout_ms {
cfg.flush_timeout = std::time::Duration::from_millis(ms);
}
// CLI override wins over TOML `[source] slot` (CLI > config).
if args.slot.is_some() {
cfg.source_slot = args.slot.clone();
}
Some(cfg)
} else {
None
};
// Effective physical replication slot (`[source] slot` + --slot override);
// None = slotless.
let source_slot: Option<String> = ch_config.as_ref().and_then(|c| c.source_slot.clone());
let shadow_start = resolve_shadow_start(args)?;
let bootstrap_end_lsn: Option<u64> = if matches!(shadow_start, ShadowStart::Bootstrap(_)) {
Some(
run_bootstrap(&cfg, &mut feed, args, ch_config.clone())
.await
.context("bootstrap")?,
)
} else {
None
};
// Regenerate config because walsender address and port may change
// Read minimum GUC values from shadow pg_control
// Keep shadow alive until pipeline teardown finishes
let shadow_lifecycle: Option<ShadowLifecycle> = match &shadow_start {
ShadowStart::External => None,
ShadowStart::Bootstrap(dir) | ShadowStart::Resume(dir) => {
let shadow = Arc::new(build_owned_shadow(args, dir.clone()));
let conninfo = walsender_primary_conninfo(args.walsender_bind);
shadow
.write_standby_signal()
.context("write standby.signal")?;
start_owned_shadow(
&shadow,
conninfo.clone(),
bootstrap_end_lsn,
Duration::from_secs(args.bootstrap_shadow_replay_timeout),
)
.await?;
Some(ShadowLifecycle::spawn(shadow, conninfo))
}
};
let backup_settings = ch_config.as_ref().and_then(|c| c.backup.clone());
let start_lsn_override = args
.start_lsn
.as_deref()
.map(|s| walshadow::pg::parse_pg_lsn(s).context("--start-lsn"))
.transpose()?;
let live_identity = manifest::SourceIdentity {
system_id: ident.sysid.parse().context("IDENTIFY_SYSTEM sysid")?,
timeline: ident.timeline,
};
// Identity gate runs before `--ignore-cursor`: the flag discards resume
// LSNs, not artifact ownership. Foreign system_id is fatal regardless
// (retire/backfill ledgers would act on another cluster's state); a
// timeline-only change (promoted source) passes under `--ignore-cursor`,
// live identity persists at the next manifest write.
let manifest_at_boot: Option<manifest::Manifest> =
match manifest::load(&args.spill_dir, &live_identity).await {
Ok(m) => m,
Err(manifest::ManifestError::ForeignSource { stored, live })
if args.ignore_cursor && stored.system_id == live.system_id =>
{
tracing::warn!(
target: "walshadow::manifest",
stored_timeline = stored.timeline,
live_timeline = live.timeline,
"--ignore-cursor adopts new source timeline",
);
None
}
Err(e @ manifest::ManifestError::ForeignSource { .. }) => {
anyhow::bail!("{e}");
}
Err(e) if args.ignore_cursor || start_lsn_override.is_some() => {
tracing::warn!(
target: "walshadow::manifest",
error = %e,
spill_dir = %args.spill_dir.display(),
"manifest unreadable; operator override discards it",
);
None
}
Err(e) => {
anyhow::bail!(
"manifest at {} unreadable: {e}; restore it, or authorize \
recovery with --ignore-cursor / --start-lsn",
manifest::manifest_path(&args.spill_dir).display(),
);
}
};
// Resume precedence: `--start-lsn` > bootstrap end > manifest emitter-ack
// > greenfield (source write head). `--ignore-cursor` forces greenfield
// (recovery drills). Bootstrap `end_lsn` outranks the manifest: shadow
// catalog state is at `end_lsn`, so consuming WAL before it double-counts.
let manifest_at_boot = if args.ignore_cursor {
None
} else {
manifest_at_boot
};
let raw_start = manifest::resolve_resume_lsn(
start_lsn_override,
bootstrap_end_lsn,
manifest_at_boot.as_ref().map(|m| m.lsn.emitter_ack.0),
ident.xlogpos,
);
let pinned = bootstrap_end_lsn.is_some() || start_lsn_override.is_some();
let floor_at_boot = manifest_at_boot
.as_ref()
.map(|m| m.floor.0)
.filter(|f| *f != 0);
// Archive-end scan only feeds the greenfield clamp (keep archive
// continuous until live streaming begins: starting after last sealed
// segment leaves shadow missing WAL; re-read from earlier LSN, CH
// removes duplicates using `_lsn`). A persisted floor folded the clamp
// at write time.
let archive_end = if !pinned && floor_at_boot.is_none() {
max_segment_end(&args.out_dir)
.await
.context("scan out-dir for sealed archive end")?
} else {
None
};
let aligned = manifest::resolve_start(raw_start, floor_at_boot, pinned, archive_end);
tracing::info!(
target: "walshadow",
raw = format_pg_lsn(raw_start).to_string(),
aligned = format_pg_lsn(aligned).to_string(),
from_bootstrap = bootstrap_end_lsn.is_some() && args.start_lsn.is_none(),
from_floor = floor_at_boot.is_some() && !pinned,
"start LSN",
);
let mut stream = WalStream::new(ident.timeline, WAL_SEG_SIZE, aligned)?;
// Bind walsender listener BEFORE shadow's walreceiver can connect.
// Without an active sink, the catalog gate inside `BufferingDecoderSink`
// deadlocks: shadow's replay LSN never advances since segment-sink fires
// after per-record dispatch in the current ordering.
let shadow_state = Arc::new(Mutex::new(
walshadow::shadow_stream::ShadowStreamState::new(
ident.timeline,
ident.sysid.clone(),
aligned,
args.walsender_slow_threshold,
),
));
let walsender_listener = tokio::net::TcpListener::bind(args.walsender_bind)
.await
.with_context(|| format!("bind walsender at {}", args.walsender_bind))?;
let walsender_addr = walsender_listener
.local_addr()
.context("walsender local_addr")?;
drop(walsender_listener); // spawn_listener re-binds at the same addr
if let Some(path) = &args.walsender_port_file {
tokio::fs::write(path, format!("{}\n", walsender_addr))
.await
.with_context(|| format!("write walsender port file {}", path.display()))?;
}
let _walsender_task = walshadow::shadow_stream::spawn_listener(
walshadow::shadow_stream::WalSenderAddr::Tcp(walsender_addr),
shadow_state.clone(),
Duration::from_millis(50),
)
.await
.context("spawn walsender listener")?;
tracing::info!(
target: "walshadow",
addr = %walsender_addr,
"walsender listening — point shadow's primary_conninfo here",
);
stream.set_bytes_sink(Box::new(walshadow::shadow_stream::ShadowStreamSink::new(
shadow_state.clone(),
)));
// Seed catalog tracker from source's current pg_class before
// START_REPLICATION. Closes the "source rotated a mapped catalog above
// 16384 pre-attach" hole the < 16384 bootstrap rule misses. Idempotent.
{
let sql_client = feed
.sql_client()
.await
.context("open sidecar sql client for seed_from_source")?;
let added = stream
.filter_mut()
.tracker_mut()
.seed_from_source(sql_client)
.await
.context("seed_from_source")?;
tracing::info!(
target: "walshadow",
added,
"seeded catalog filenodes from source pg_class"
);
}
// Connect bridge and shadow catalog before START_REPLICATION so the
// tracker→drain wire is hot from the first record.
let shadow_conninfo = socket_conninfo(
args.shadow_socket_dir
.to_str()
.context("shadow-socket-dir not UTF-8")?,
args.shadow_port,
&args.shadow_user,
&args.shadow_dbname,
);
let connect_budget = Duration::from_secs(args.shadow_connect_timeout);
let bridge_path = args.bridge_socket_path();
let bridge = Arc::new(
walshadow::bridge::connect_with_budget(&bridge_path, connect_budget)
.await
.with_context(|| format!("connect bridge at {}", bridge_path.display()))?,
);
let info = bridge.info();
tracing::info!(
target: "walshadow::bridge",
socket = %bridge_path.display(),
pg_version = info.map(|i| i.pg_version_num).unwrap_or(0),
in_recovery = info.map(|i| i.in_recovery).unwrap_or(false),
"bridge connected",
);
let cat_cfg = ShadowCatalogConfig::default();
let backoff_initial = cat_cfg.reconnect_backoff_initial;
let backoff_max = cat_cfg.reconnect_backoff_max;
let catalog = with_transient_retry(connect_budget, backoff_initial, backoff_max, async || {
ShadowCatalog::connect(&shadow_conninfo, cat_cfg.clone(), bridge.clone()).await
})
.await
.context("connect to shadow PG")?;
let catalog = Arc::new(Mutex::new(catalog));
tracing::info!(
target: "walshadow",
socket = %args.shadow_socket_dir.display(),
port = args.shadow_port,
user = %args.shadow_user,
dbname = %args.shadow_dbname,
"shadow connected",
);
// Create the configured slot before preflight, which requires it to exist.
if let Some(slot) = source_slot.as_deref() {
feed.ensure_physical_slot(slot)
.await
.with_context(|| format!("ensure physical replication slot {slot}"))?;
tracing::info!(target: "walshadow", slot, "physical replication slot ready");
}
// Pre-flight validators run after both source + shadow SQL clients
// are up so every check has its connection.
if !args.skip_preflight {
let source_version_num = feed.server_version_num();
let source_sql = feed
.sql_client()
.await
.context("source sidecar sql for preflight")?;
let shadow_sql = open_shadow_sql_client(