Move storage initialization into the backend executable

This commit is contained in:
2026-11-30 20:23:23 +08:00
parent 66be7099ec
commit af9f25baa5
11 changed files with 64 additions and 74 deletions
Generated
+1 -9
View File
@@ -146,6 +146,7 @@ version = "0.1.0"
dependencies = [ dependencies = [
"admin_backend", "admin_backend",
"axum", "axum",
"clusters",
"db", "db",
"tokio", "tokio",
] ]
@@ -162,15 +163,6 @@ version = "1.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06"
[[package]]
name = "bedrock"
version = "0.1.0"
dependencies = [
"clusters",
"db",
"tokio",
]
[[package]] [[package]]
name = "bitflags" name = "bitflags"
version = "2.13.2" version = "2.13.2"
-11
View File
@@ -29,14 +29,3 @@ tokio-postgres-rustls = { version = "0.13", default-features = false }
tokio-rusqlite = "0.6" tokio-rusqlite = "0.6"
url = "2" url = "2"
webpki-roots = "1" webpki-roots = "1"
[package]
name = "bedrock"
version = "0.1.0"
edition.workspace = true
rust-version.workspace = true
[dependencies]
clusters.workspace = true
db.workspace = true
tokio.workspace = true
+2 -2
View File
@@ -29,8 +29,8 @@ mode, and the loaded configuration version for the instance that served the
request. `BEDROCK_CONFIG_VERSION` can override the reported version label. The request. `BEDROCK_CONFIG_VERSION` can override the reported version label. The
admin router reads the same resolved configuration the process used to open the admin router reads the same resolved configuration the process used to open the
database. Give every replica the same config file and version label through your database. Give every replica the same config file and version label through your
deployment process. The root `bedrock` binary remains the one-shot storage deployment process. Run `cargo run --locked -p backend -- --init-storage` for one-shot storage
initializer. initialization. The release process uses the same mode.
## Database configuration ## Database configuration
+2 -2
View File
@@ -7,13 +7,13 @@
```mermaid ```mermaid
flowchart TD flowchart TD
M["main 收到提交"] --> W["deploy.yml 在 ces-control 上启动"] M["main 收到提交"] --> W["deploy.yml 在 ces-control 上启动"]
W --> B["build-release.sh 编译发布版"] W --> B["build-release.sh 编译 backend 发布版"]
B -->|Bedrock 二进制和 Git SHA| R B -->|Bedrock 二进制和 Git SHA| R
E["Gitea PostgreSQL Variables 和 Secret"] -->|部署参数| P E["Gitea PostgreSQL Variables 和 Secret"] -->|部署参数| P
subgraph release["release.sh"] subgraph release["release.sh"]
R["暂存待发布版本"] --> P["调用 render-postgres.py 生成私有 bedrock.yaml"] R["暂存待发布版本"] --> P["调用 render-postgres.py 生成私有 bedrock.yaml"]
P -->|配置就绪| I["启动临时容器,由 Bedrock 初始化 PostgreSQL"] P -->|配置就绪| I["临时容器运行 backend 的 --init-storage,初始化 PostgreSQL"]
I -->|成功| S["保存版本并原子切换 current"] I -->|成功| S["保存版本并原子切换 current"]
P -->|失败| F["清理暂存目录,保留现有 current"] P -->|失败| F["清理暂存目录,保留现有 current"]
I -->|失败| F I -->|失败| F
+1 -1
View File
@@ -44,6 +44,6 @@ docker run --rm --name "$prefix-rust" --network "$prefix" \
cargo test --locked --workspace cargo test --locked --workspace
cargo build --locked --workspace cargo build --locked --workspace
cd "$(mktemp -d)" cd "$(mktemp -d)"
/tmp/bedrock-target/debug/bedrock BEDROCK_BACKEND_LISTEN=invalid /tmp/bedrock-target/debug/backend --init-storage
test -f bedrock.sqlite3 test -f bedrock.sqlite3
' '
+1
View File
@@ -7,5 +7,6 @@ rust-version.workspace = true
[dependencies] [dependencies]
admin_backend = { path = "../admin_backend" } admin_backend = { path = "../admin_backend" }
axum.workspace = true axum.workspace = true
clusters.workspace = true
db.workspace = true db.workspace = true
tokio = { workspace = true, features = ["net", "signal", "sync", "time"] } tokio = { workspace = true, features = ["net", "signal", "sync", "time"] }
+48 -6
View File
@@ -1,20 +1,38 @@
use std::{env, error::Error, io, net::SocketAddr, sync::Arc}; use std::{env, error::Error, io, net::SocketAddr, sync::Arc};
use axum::Router; use axum::Router;
use db::{DeploymentConfig, connect_resolved}; use clusters::{DOCUMENTS, DeploymentConfig, ResolvedDeployment};
use db::{ConnectError, connect_resolved, connect_sql};
use tokio::{net::TcpListener, sync::watch}; use tokio::{net::TcpListener, sync::watch};
#[tokio::main] #[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> { async fn main() -> Result<(), Box<dyn Error>> {
let mut args = env::args_os().skip(1);
let init_storage = match (args.next(), args.next()) {
(None, None) => false,
(Some(arg), None) if arg == "--init-storage" => true,
_ => {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"expected no arguments or --init-storage",
)
.into());
}
};
let config = match env::var_os("BEDROCK_DB_CONFIG") {
Some(path) => DeploymentConfig::load(path)?,
None => DeploymentConfig::default(),
}
.resolve()?;
if init_storage {
return initialize_storage(&config).await;
}
let address: SocketAddr = optional_env("BEDROCK_BACKEND_LISTEN")? let address: SocketAddr = optional_env("BEDROCK_BACKEND_LISTEN")?
.as_deref() .as_deref()
.unwrap_or("127.0.0.1:8080") .unwrap_or("127.0.0.1:8080")
.parse()?; .parse()?;
let config = match env::var_os("BEDROCK_DB_CONFIG") { let config = Arc::new(config);
Some(path) => DeploymentConfig::load(path)?,
None => DeploymentConfig::default(),
};
let config = Arc::new(config.resolve()?);
let admin_address = optional_env("BEDROCK_ADMIN_LISTEN")?; let admin_address = optional_env("BEDROCK_ADMIN_LISTEN")?;
let admin = match optional_env("BEDROCK_ADMIN_TOKEN")? { let admin = match optional_env("BEDROCK_ADMIN_TOKEN")? {
@@ -62,6 +80,30 @@ async fn main() -> Result<(), Box<dyn Error>> {
Ok(()) Ok(())
} }
async fn initialize_storage(resolved: &ResolvedDeployment) -> Result<(), Box<dyn Error>> {
if resolved
.binding(DOCUMENTS)
.is_some_and(|resource| resource.as_sql().is_none())
{
return Err(ConnectError::InvalidDocuments.into());
}
for (role, resource) in resolved.bound_resources() {
let Some(settings) = resource.as_sql() else {
continue;
};
let connection = connect_sql(settings).await?;
println!(
"Bedrock storage ready (config {}, role {}, {:?}, revision {}, read-only: {})",
resolved.config_version,
role,
connection.driver(),
connection.revision().await?,
connection.is_read_only(),
);
}
Ok(())
}
fn optional_env(name: &str) -> Result<Option<String>, env::VarError> { fn optional_env(name: &str) -> Result<Option<String>, env::VarError> {
match env::var(name) { match env::var(name) {
Ok(value) => Ok(Some(value)), Ok(value) => Ok(Some(value)),
+5 -5
View File
@@ -10,11 +10,11 @@ Bedrock reads a YAML deployment file from `BEDROCK_DB_CONFIG`. The loader also a
## Local SQLite ## Local SQLite
Bedrock defaults to `bedrock.sqlite3` in the working directory. To choose another path, set `BEDROCK_DB_CONFIG` to a [SQLite configuration](local/sqlite.yaml) and set the resource's `primary` to a persistent, writable path. Run `backend --init-storage` to initialize storage once. Bedrock defaults to `bedrock.sqlite3` in the working directory. To choose another path, set `BEDROCK_DB_CONFIG` to a [SQLite configuration](local/sqlite.yaml) and set the resource's `primary` to a persistent, writable path.
```mermaid ```mermaid
flowchart TD flowchart TD
A["在本机启动 Bedrock"] --> B{"是否设置 BEDROCK_DB_CONFIG"} A["在本机运行 backend --init-storage"] --> B{"是否设置 BEDROCK_DB_CONFIG"}
B -->|是| C["读取指定的 SQLite 配置,取得文件路径"] B -->|是| C["读取指定的 SQLite 配置,取得文件路径"]
B -->|否| D["使用工作目录下的 bedrock.sqlite3"] B -->|否| D["使用工作目录下的 bedrock.sqlite3"]
C --> E["打开或创建 SQLite 文件"] C --> E["打开或创建 SQLite 文件"]
@@ -26,18 +26,18 @@ flowchart TD
PostgreSQL on the existing host uses Gitea Actions variables `BEDROCK_PG_HOST`, `BEDROCK_PG_PORT`, `BEDROCK_PG_DATABASE`, `BEDROCK_PG_USER` and secret `BEDROCK_PG_PASSWORD`. The release invokes `python3 deploy/gitea/render-postgres.py /path/to/private/bedrock.yaml --deployment production --config-version RELEASE_ID`. The renderer writes a private file. The database must already exist and present a trusted certificate for the selected endpoint. PostgreSQL on the existing host uses Gitea Actions variables `BEDROCK_PG_HOST`, `BEDROCK_PG_PORT`, `BEDROCK_PG_DATABASE`, `BEDROCK_PG_USER` and secret `BEDROCK_PG_PASSWORD`. The release invokes `python3 deploy/gitea/render-postgres.py /path/to/private/bedrock.yaml --deployment production --config-version RELEASE_ID`. The renderer writes a private file. The database must already exist and present a trusted certificate for the selected endpoint.
Gitea builds a release on `ces-control` when a commit lands on `main`. The deploy step renders the private PostgreSQL configuration and runs the current one-shot Rust storage initializer on the existing `endoleap-dev_default` network. It publishes releases under `/opt/endoleap-infra/bedrock-rust/releases` and switches `/opt/endoleap-infra/bedrock-rust/current` after successful initialization. The Go service retains its own containers and routes. Gitea builds a release on `ces-control` when a commit lands on `main`. The deploy step renders the private PostgreSQL configuration and runs `backend --init-storage` through the published `bedrock` executable on the existing `endoleap-dev_default` network. It publishes releases under `/opt/endoleap-infra/bedrock-rust/releases` and switches `/opt/endoleap-infra/bedrock-rust/current` after successful initialization. The Go service retains its own containers and routes.
```mermaid ```mermaid
flowchart TD flowchart TD
M["main 收到提交"] --> W["deploy.yml 在 ces-control 上启动"] M["main 收到提交"] --> W["deploy.yml 在 ces-control 上启动"]
W --> B["build-release.sh 编译发布版"] W --> B["build-release.sh 编译 backend 发布版"]
B -->|Bedrock 二进制和 Git SHA| R B -->|Bedrock 二进制和 Git SHA| R
E["Gitea PostgreSQL Variables 和 Secret"] -->|部署参数| P E["Gitea PostgreSQL Variables 和 Secret"] -->|部署参数| P
subgraph release["release.sh"] subgraph release["release.sh"]
R["暂存待发布版本"] --> P["调用 render-postgres.py 生成私有 bedrock.yaml"] R["暂存待发布版本"] --> P["调用 render-postgres.py 生成私有 bedrock.yaml"]
P -->|配置就绪| I["启动临时容器,由 Bedrock 初始化 PostgreSQL"] P -->|配置就绪| I["临时容器运行 backend 的 --init-storage,初始化 PostgreSQL"]
I -->|成功| S["保存版本并原子切换 current"] I -->|成功| S["保存版本并原子切换 current"]
P -->|失败| F["清理暂存目录,保留现有 current"] P -->|失败| F["清理暂存目录,保留现有 current"]
I -->|失败| F I -->|失败| F
+2 -2
View File
@@ -8,6 +8,6 @@ docker run --rm \
--mount "type=bind,source=$output,target=/out" \ --mount "type=bind,source=$output,target=/out" \
-w /work -e CARGO_TARGET_DIR=/tmp/bedrock-target \ -w /work -e CARGO_TARGET_DIR=/tmp/bedrock-target \
rust:1.91.1-bookworm sh -ec ' rust:1.91.1-bookworm sh -ec '
cargo build --locked --release --bin bedrock cargo build --locked --release -p backend
install -m 755 /tmp/bedrock-target/release/bedrock /out/bedrock install -m 755 /tmp/bedrock-target/release/backend /out/bedrock
' '
+2 -2
View File
@@ -25,12 +25,12 @@ release="$revision.${stage##*.}"
python3 "$(dirname "$0")/render-postgres.py" "$stage/bedrock.yaml" \ python3 "$(dirname "$0")/render-postgres.py" "$stage/bedrock.yaml" \
--deployment production --config-version "$release" --deployment production --config-version "$release"
# The current binary is a one-shot storage initializer. It publishes no ports. # Run storage initialization as a one-shot command in the release container.
docker run --rm --network "$network" \ docker run --rm --network "$network" \
--user "$(id -u):$(id -g)" --read-only --cap-drop ALL --security-opt no-new-privileges \ --user "$(id -u):$(id -g)" --read-only --cap-drop ALL --security-opt no-new-privileges \
--mount "type=bind,source=$stage,target=/release,readonly" \ --mount "type=bind,source=$stage,target=/release,readonly" \
-e BEDROCK_DB_CONFIG=/release/bedrock.yaml \ -e BEDROCK_DB_CONFIG=/release/bedrock.yaml \
debian:bookworm-slim /release/bedrock debian:bookworm-slim /release/bedrock --init-storage
# Keep the final release private; only switch current after initialization succeeds. # Keep the final release private; only switch current after initialization succeeds.
python3 - "$stage" "$root" "$release" <<'PY' python3 - "$stage" "$root" "$release" <<'PY'
-34
View File
@@ -1,34 +0,0 @@
use std::{env, error::Error};
use clusters::{DOCUMENTS, DeploymentConfig};
use db::connect_sql;
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
let config = match env::var_os("BEDROCK_DB_CONFIG") {
Some(path) => DeploymentConfig::load(path)?,
None => DeploymentConfig::default(),
};
let resolved = config.resolve()?;
if resolved
.binding(DOCUMENTS)
.is_some_and(|resource| resource.as_sql().is_none())
{
return Err(db::ConnectError::InvalidDocuments.into());
}
for (role, resource) in resolved.bound_resources() {
let Some(settings) = resource.as_sql() else {
continue;
};
let connection = connect_sql(settings).await?;
println!(
"Bedrock storage ready (config {}, role {}, {:?}, revision {}, read-only: {})",
resolved.config_version,
role,
connection.driver(),
connection.revision().await?,
connection.is_read_only(),
);
}
Ok(())
}