hazine 0.2.2

Runs a DuckDB Quack server for DuckLake on localhost, reached through an SSH tunnel.
Documentation
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
use std::net::SocketAddr;
use std::path::PathBuf;
use std::process::ExitCode;
use std::time::Duration;

use clap::{Args, Parser, Subcommand, ValueEnum};
use tracing_subscriber::EnvFilter;

use hazine::setup::{self, Catalog, SslMode, Storage, UrlStyle};
use hazine::{Config, supervisor, token};

/// Run a DuckDB Quack server for DuckLake on localhost.
///
/// Settings come from flags, then HAZINE_* environment variables, then
/// defaults. Quack listens on a loopback address only: connect through an SSH
/// tunnel (ssh -N -L 1294:127.0.0.1:1294 <host>).
#[derive(Parser)]
#[command(version, about)]
struct Cli {
    /// Log format.
    #[arg(
        long,
        env = "HAZINE_LOG_FORMAT",
        value_enum,
        default_value_t,
        global = true
    )]
    log_format: LogFormat,

    #[command(subcommand)]
    command: Command,
}

#[derive(Clone, Copy, Default, ValueEnum)]
enum LogFormat {
    #[default]
    Text,
    Json,
}

#[derive(Subcommand)]
enum Command {
    /// Start DuckDB with the init file and keep it serving Quack.
    Serve(ServeArgs),
    /// Install and configure hazine, DuckDB and the systemd service (as root,
    /// on Linux). Rerun to change settings; existing secrets are kept.
    ///
    /// Give secrets through environment variables rather than flags, which
    /// other users can see in the process list; missing ones are asked for.
    Setup(Box<SetupArgs>),
    /// Print a new random access token, for QUACK_TOKEN.
    Token {
        /// Characters in the token.
        #[arg(long, default_value_t = 40)]
        length: usize,
    },
}

#[derive(Args)]
struct ServeArgs {
    /// The DuckDB CLI (≥ 2.0, with the quack extension installed): a path,
    /// or a name looked up in PATH.
    #[arg(long, env = "HAZINE_DUCKDB", default_value = "duckdb")]
    duckdb: PathBuf,

    /// SQL run at start: settings, extensions, the DuckLake attach and
    /// quack_serve, which should listen on getenv('HAZINE_QUACK_ADDR').
    #[arg(long, env = "HAZINE_INIT", default_value = "/etc/hazine/init.sql")]
    init: PathBuf,

    /// The main database: a DuckDB file, or a DuckLake such as
    /// ducklake:postgres: (what hazine setup configures); in memory without
    /// one. Every Quack session uses it by default.
    #[arg(long, env = "HAZINE_DATABASE")]
    database: Option<PathBuf>,

    /// Where Quack listens; handed to the init file as HAZINE_QUACK_ADDR.
    /// Must be a loopback address.
    #[arg(long, env = "HAZINE_QUACK_ADDR", default_value = "127.0.0.1:1294")]
    quack_addr: SocketAddr,

    /// Seconds DuckDB may take to start listening before hazine warns.
    #[arg(long, env = "HAZINE_READY_TIMEOUT", default_value_t = 60)]
    ready_timeout: u64,

    /// Seconds DuckDB has to exit on shutdown before it is killed.
    #[arg(long, env = "HAZINE_STOP_TIMEOUT", default_value_t = 30)]
    stop_timeout: u64,

    /// Exits in a row before Quack was listening after which hazine gives up
    /// (and exits non-zero, for the service manager to see).
    #[arg(long, env = "HAZINE_MAX_FAILURES", default_value_t = 5)]
    max_failures: u32,
}

#[derive(Args)]
struct SetupArgs {
    /// Postgres host holding the DuckLake catalog [asked for if not given].
    #[arg(long, env = "HAZINE_PG_HOST", help_heading = "Catalog (Postgres)")]
    pg_host: Option<String>,

    /// [default: from the last setup, else 5432]
    #[arg(long, env = "HAZINE_PG_PORT", help_heading = "Catalog (Postgres)")]
    pg_port: Option<u16>,

    /// [default: from the last setup, else ducklake]
    #[arg(long, env = "HAZINE_PG_DATABASE", help_heading = "Catalog (Postgres)")]
    pg_database: Option<String>,

    /// [default: from the last setup, else hazine]
    #[arg(long, env = "HAZINE_PG_USER", help_heading = "Catalog (Postgres)")]
    pg_user: Option<String>,

    /// Kept from the existing env file if not given.
    #[arg(
        long,
        env = "HAZINE_PG_PASSWORD",
        hide_env_values = true,
        help_heading = "Catalog (Postgres)"
    )]
    pg_password: Option<String>,

    /// TLS to Postgres (libpq's sslmode) [default: from the last setup, else
    /// require].
    #[arg(
        long,
        env = "HAZINE_PG_SSLMODE",
        value_enum,
        help_heading = "Catalog (Postgres)"
    )]
    pg_sslmode: Option<SslMode>,

    /// Where DuckLake writes Parquet files: s3://bucket/prefix/ [asked for if
    /// not given].
    #[arg(long, env = "HAZINE_DATA_PATH", help_heading = "Data (S3)")]
    data_path: Option<String>,

    /// S3 endpoint, host[:port], e.g. fsn1.your-objectstorage.com for
    /// Hetzner, or "aws" [asked for if not given].
    #[arg(long, env = "HAZINE_S3_ENDPOINT", help_heading = "Data (S3)")]
    s3_endpoint: Option<String>,

    /// S3 region, e.g. fsn1 for Hetzner in Falkenstein [asked for if not
    /// given; default: the Hetzner location, else us-east-1].
    #[arg(long, env = "HAZINE_S3_REGION", help_heading = "Data (S3)")]
    s3_region: Option<String>,

    /// vhost or path [asked for if not given; default: path with an
    /// endpoint, vhost for AWS].
    #[arg(
        long,
        env = "HAZINE_S3_URL_STYLE",
        value_enum,
        help_heading = "Data (S3)"
    )]
    s3_url_style: Option<UrlStyle>,

    /// Use HTTPS to the endpoint.
    #[arg(long, env = "HAZINE_S3_USE_SSL", default_value_t = true, action = clap::ArgAction::Set, help_heading = "Data (S3)")]
    s3_use_ssl: bool,

    /// Kept from the existing env file if not given.
    #[arg(
        long,
        env = "HAZINE_S3_KEY_ID",
        hide_env_values = true,
        help_heading = "Data (S3)"
    )]
    s3_key_id: Option<String>,

    /// Kept from the existing env file if not given.
    #[arg(
        long,
        env = "HAZINE_S3_SECRET",
        hide_env_values = true,
        help_heading = "Data (S3)"
    )]
    s3_secret: Option<String>,

    /// The DuckDB CLI release to install (2.0 or later).
    #[arg(long, env = "HAZINE_DUCKDB_VERSION", default_value = "2.0.1")]
    duckdb_version: String,

    /// Where Quack listens. Must be a loopback address.
    #[arg(long, env = "HAZINE_QUACK_ADDR", default_value = "127.0.0.1:1294")]
    quack_addr: SocketAddr,

    /// DuckDB threads [default: the number of CPUs].
    #[arg(long)]
    threads: Option<usize>,

    /// DuckDB memory_limit, e.g. 100GB [default: 80% of RAM].
    #[arg(long)]
    memory_limit: Option<String>,

    /// systemd MemoryMax for the service, e.g. 112G [default: 90% of RAM].
    #[arg(long)]
    memory_max: Option<String>,

    /// Configure, but do not enable or restart the service.
    #[arg(long)]
    no_start: bool,

    /// Print what would be done and the files that would be written (secrets
    /// redacted); change nothing.
    #[arg(long)]
    dry_run: bool,
}

impl SetupArgs {
    fn into_options(self) -> Result<setup::Options, hazine::Error> {
        // Earlier values are offered as defaults when asking.
        let existing = setup::existing_env(self.dry_run)?;
        let pg_host = setup::setting(
            self.pg_host,
            existing.get("PGHOST").map(String::as_str),
            "--pg-host",
            "Postgres host (DuckLake catalog)",
            setup::host,
        )?;
        let data_path = setup::setting(
            self.data_path,
            existing.get("HAZINE_DATA_PATH").map(String::as_str),
            "--data-path",
            "Data path (s3://bucket/prefix/)",
            setup::render::data_path,
        )?;
        // Given, else from the last setup, else the built-in default.
        let port = match self.pg_port {
            Some(port) => port,
            None => existing_or(&existing, "PGPORT", "5432")
                .parse()
                .map_err(|_| hazine::Error::InvalidSetting {
                    name: "PGPORT in hazine.env",
                    reason: "is not a port number; give --pg-port".into(),
                })?,
        };
        let database = self
            .pg_database
            .unwrap_or_else(|| existing_or(&existing, "PGDATABASE", "ducklake").into());
        let user = self
            .pg_user
            .unwrap_or_else(|| existing_or(&existing, "PGUSER", "hazine").into());
        let sslmode = match self.pg_sslmode {
            Some(sslmode) => sslmode,
            None => SslMode::from_str(existing_or(&existing, "PGSSLMODE", "require"), true)
                .map_err(|_| hazine::Error::InvalidSetting {
                    name: "PGSSLMODE in hazine.env",
                    reason: "is not an sslmode; give --pg-sslmode".into(),
                })?,
        };
        let endpoint = setup::setting(
            self.s3_endpoint,
            Some(existing_or(
                &existing,
                "HAZINE_S3_ENDPOINT",
                setup::render::AWS,
            )),
            "--s3-endpoint",
            "S3 endpoint (fsn1.your-objectstorage.com for Hetzner in Falkenstein; aws for AWS)",
            setup::render::endpoint,
        )?;
        let endpoint = (endpoint != setup::render::AWS).then_some(endpoint);
        // A Hetzner endpoint names its region; otherwise offer the last one.
        let region_default = setup::render::region_of(endpoint.as_deref())
            .unwrap_or_else(|| existing_or(&existing, "HAZINE_S3_REGION", "us-east-1").into());
        let region = setup::setting(
            self.s3_region,
            Some(&region_default),
            "--s3-region",
            "S3 region",
            setup::render::region,
        )?;
        let style_default = if endpoint.is_some() { "path" } else { "vhost" };
        let url_style = setup::setting(
            self.s3_url_style.map(|style| style.as_str().to_string()),
            Some(existing_or(&existing, "HAZINE_S3_URL_STYLE", style_default)),
            "--s3-url-style",
            "S3 URL style (vhost or path)",
            |value| setup::render::url_style(value).map(|style| style.as_str().to_string()),
        )?;
        let url_style = setup::render::url_style(&url_style)?;
        Ok(setup::Options {
            catalog: Catalog {
                host: pg_host,
                port,
                database,
                user,
                sslmode,
            },
            storage: Storage {
                data_path,
                endpoint,
                region,
                url_style,
                use_ssl: self.s3_use_ssl,
            },
            pg_password: self.pg_password,
            s3_key_id: self.s3_key_id,
            s3_secret: self.s3_secret,
            duckdb_version: self.duckdb_version,
            quack_addr: self.quack_addr,
            threads: self.threads,
            memory_limit: self.memory_limit,
            memory_max: self.memory_max,
            start: !self.no_start,
            dry_run: self.dry_run,
        })
    }
}

/// The value of `name` in the existing env file, or `fallback`.
fn existing_or<'a>(
    existing: &'a std::collections::HashMap<String, String>,
    name: &str,
    fallback: &'a str,
) -> &'a str {
    existing
        .get(name)
        .map(String::as_str)
        .filter(|value| !value.is_empty())
        .unwrap_or(fallback)
}

impl From<ServeArgs> for Config {
    fn from(args: ServeArgs) -> Self {
        Config {
            duckdb: args.duckdb,
            init: args.init,
            database: args.database,
            quack_addr: args.quack_addr,
            ready_timeout: Duration::from_secs(args.ready_timeout),
            stop_timeout: Duration::from_secs(args.stop_timeout),
            restart_delay: Duration::from_secs(1),
            max_failures: args.max_failures.max(1),
        }
    }
}

fn init_logging(format: LogFormat) {
    let filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info"));
    let builder = tracing_subscriber::fmt()
        .with_env_filter(filter)
        .with_writer(std::io::stderr);
    match format {
        LogFormat::Text => builder.init(),
        LogFormat::Json => builder.json().init(),
    }
}

/// Complete on SIGTERM or Ctrl-C.
async fn shutdown_signal() {
    #[cfg(unix)]
    {
        use tokio::signal::unix::{SignalKind, signal};
        match signal(SignalKind::terminate()) {
            Ok(mut term) => {
                tokio::select! {
                    _ = term.recv() => {}
                    _ = tokio::signal::ctrl_c() => {}
                }
            }
            Err(error) => {
                tracing::warn!(%error, "cannot listen for SIGTERM; only Ctrl-C stops hazine");
                let _ = tokio::signal::ctrl_c().await;
            }
        }
    }
    #[cfg(not(unix))]
    {
        let _ = tokio::signal::ctrl_c().await;
    }
    tracing::info!("shutting down");
}

#[tokio::main]
async fn main() -> ExitCode {
    let cli = Cli::parse();
    init_logging(cli.log_format);
    match cli.command {
        Command::Serve(args) => match supervisor::run(args.into(), shutdown_signal()).await {
            Ok(()) => ExitCode::SUCCESS,
            Err(error) => {
                tracing::error!(%error, "hazine failed");
                ExitCode::FAILURE
            }
        },
        Command::Setup(args) => match args.into_options().and_then(setup::run) {
            Ok(()) => ExitCode::SUCCESS,
            Err(error) => {
                tracing::error!(%error, "setup failed");
                ExitCode::FAILURE
            }
        },
        Command::Token { length } => match token::generate(length) {
            Ok(token) => {
                println!("{token}");
                ExitCode::SUCCESS
            }
            Err(error) => {
                eprintln!("error: generating a token: {error}");
                ExitCode::FAILURE
            }
        },
    }
}