Skip to content

Prototype: Public database dumps #1800

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 35 commits into from
Sep 30, 2019
Merged
Show file tree
Hide file tree
Changes from 27 commits
Commits
Show all changes
35 commits
Select commit Hold shift + click to select a range
8487e80
Add dump_db task.
smarnach Aug 27, 2019
32ec944
Add documentation to dump-db.toml.
smarnach Aug 17, 2019
4bfd40c
Refactor enqueue helper in the enqueue-job binary.
smarnach Aug 17, 2019
1d50084
Reduce global state in dump_db task.
smarnach Aug 17, 2019
0ed2929
Address review comments by @carols10cents.
smarnach Aug 21, 2019
c2dce7c
Make database URL and upload target of DB dumps configurable.
smarnach Aug 24, 2019
a648dbd
Make cleanup of old database files more robust.
smarnach Aug 26, 2019
29a86e9
Adapt dump_db to new uploader interface.
smarnach Aug 27, 2019
ec06f10
Correct error handling for the psql call.
smarnach Aug 26, 2019
d4b9f8c
Use Handlebars template to generate psql script.
smarnach Aug 29, 2019
ee888f8
Add code to generate import script for dumps.
smarnach Aug 29, 2019
bcbccd6
Include import and export scripts in the database dump.
smarnach Aug 29, 2019
3eff6dc
Set default value for gh_access_token in import script.
smarnach Sep 2, 2019
b085a78
Simplify topological sort implementation.
smarnach Sep 3, 2019
b4ad1f1
Move psql script generation code to submodule.
smarnach Sep 3, 2019
3b477c9
Refactor dump_db code to use Drop for cleanup.
smarnach Sep 3, 2019
4448ca8
Refactor schema check unit test.
smarnach Sep 3, 2019
ede4fe0
Allow specifying column defaults in the DB dump config.
smarnach Sep 5, 2019
1c4737b
Add basic unit tests for topological sorting.
smarnach Sep 5, 2019
c373f4b
Add prototype for dump_db integration test.
smarnach Sep 8, 2019
44a995a
Use cloned() instead of copied().
smarnach Sep 8, 2019
f5f536a
Suppress migrations output in dump_db test.
smarnach Sep 8, 2019
cacbc4f
Merge remote-tracking branch 'origin' into dump-db-new
smarnach Sep 8, 2019
200d99f
Remove crates.licence column from dump_db configuration.
smarnach Sep 8, 2019
db89e77
Merge remote-tracking branch 'origin' into dump-db-new
smarnach Sep 12, 2019
e760a53
Move data in dump tarbal into subdirectory.
smarnach Sep 12, 2019
3beeb38
Add README and metadata to database dump.
smarnach Sep 12, 2019
d8b45d9
Remove redundant dependency in dump-db.toml.
smarnach Sep 14, 2019
cc8f22e
Inlcude schema dump in database dump.
smarnach Sep 14, 2019
620bb51
Remove format version from dump metadata.
smarnach Sep 16, 2019
ba3709b
Document the database dumps in the frontend.
smarnach Sep 17, 2019
4e479cf
Merge remote-tracking branch 'origin' into dump-db-new
smarnach Sep 18, 2019
c142880
Add dependency for badges on crates to db dump configuration.
smarnach Sep 18, 2019
a57fed2
Small edits to the data access documentation
carols10cents Sep 28, 2019
01a4e98
Take new clippy suggestions that came with 1.38
carols10cents Sep 28, 2019
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 57 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -83,12 +83,14 @@ tokio = "0.1"
hyper = "0.12"
ctrlc = { version = "3.0", features = ["termination"] }
indexmap = "1.0.2"
handlebars = "2.0.1"

[dev-dependencies]
conduit-test = "0.8"
hyper-tls = "0.3"
lazy_static = "1.0"
tokio-core = "0.1"
diesel_migrations = { version = "1.3.0", features = ["postgres"] }

[build-dependencies]
dotenv = "0.11"
Expand Down
3 changes: 1 addition & 2 deletions migrations/2017-10-08-193512_category_trees/up.sql
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
-- Your SQL goes here
CREATE EXTENSION ltree;
CREATE EXTENSION IF NOT EXISTS ltree;

-- Create the new column which will represent our category tree.
-- Fill it with values from `slug` column and then set to non-null
Expand Down
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
CREATE EXTENSION pg_trgm;
CREATE EXTENSION IF NOT EXISTS pg_trgm;
CREATE INDEX index_crates_name_tgrm ON crates USING gin (canon_crate_name(name) gin_trgm_ops);
36 changes: 24 additions & 12 deletions src/bin/enqueue-job.rs
Original file line number Diff line number Diff line change
@@ -1,17 +1,29 @@
use cargo_registry::util::{CargoError, CargoResult};
use cargo_registry::{db, tasks};
use std::env::args;
use swirl::Job;
use cargo_registry::util::{human, CargoError, CargoResult};
use cargo_registry::{db, env, tasks};
use diesel::PgConnection;

fn main() -> CargoResult<()> {
let conn = db::connect_now()?;
let mut args = std::env::args().skip(1);
match &*args.next().unwrap_or_default() {
"update_downloads" => tasks::update_downloads().enqueue(&conn),
"dump_db" => {
let database_url = args.next().unwrap_or_else(|| env("DATABASE_URL"));
let target_name = args
.next()
.unwrap_or_else(|| String::from("db-dump.tar.gz"));
tasks::dump_db(database_url, target_name).enqueue(&conn)
}
other => Err(human(&format!("Unrecognized job type `{}`", other))),
}
}

match &*args().nth(1).unwrap_or_default() {
"update_downloads" => tasks::update_downloads()
.enqueue(&conn)
.map_err(|e| CargoError::from_std_error(e))?,
other => panic!("Unrecognized job type `{}`", other),
};

Ok(())
/// Helper to map the `PerformError` returned by `swirl::Job::enqueue()` to a
/// `CargoError`. Can be removed once `map_err()` isn't needed any more.
trait Enqueue: swirl::Job {
fn enqueue(self, conn: &PgConnection) -> CargoResult<()> {
<Self as swirl::Job>::enqueue(self, conn).map_err(|e| CargoError::from_std_error(e))
}
}

impl<J: swirl::Job> Enqueue for J {}
2 changes: 2 additions & 0 deletions src/tasks.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
pub mod dump_db;
mod update_downloads;

pub use dump_db::dump_db;
pub use update_downloads::update_downloads;
153 changes: 153 additions & 0 deletions src/tasks/dump_db.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
use std::{
fs::File,
path::{Path, PathBuf},
};

use crate::{background_jobs::Environment, uploaders::Uploader, util::errors::std_error_no_send};

use swirl::PerformError;

/// Create CSV dumps of the public information in the database, wrap them in a
/// tarball and upload to S3.
#[swirl::background_job]
pub fn dump_db(
env: &Environment,
database_url: String,
target_name: String,
) -> Result<(), PerformError> {
let directory = DumpDirectory::create()?;
directory.dump_db(&database_url)?;
let tarball = DumpTarball::create(&directory.export_dir)?;
tarball.upload(&target_name, &env.uploader)?;
println!("Database dump uploaded to {}.", &target_name);
Ok(())
}

/// Manage the export directory.
///
/// Create the directory, populate it with the psql scripts and CSV dumps, and
/// make sure it gets deleted again even in the case of an error.
#[derive(Debug)]
pub struct DumpDirectory {
pub timestamp: chrono::DateTime<chrono::Utc>,
pub export_dir: PathBuf,
}

impl DumpDirectory {
pub fn create() -> Result<Self, PerformError> {
let timestamp = chrono::Utc::now();
let timestamp_str = timestamp.format("%Y-%m-%d-%H%M%S").to_string();
let export_dir = std::env::temp_dir().join("dump-db").join(timestamp_str);
std::fs::create_dir_all(&export_dir)?;
Ok(Self {
timestamp,
export_dir,
})
}

pub fn dump_db(&self, database_url: &str) -> Result<(), PerformError> {
self.add_readme()?;
self.add_metadata()?;
let export_script = self.export_dir.join("export.sql");
let import_script = self.export_dir.join("import.sql");
gen_scripts::gen_scripts(&export_script, &import_script)?;
std::fs::create_dir(self.export_dir.join("data"))?;
run_psql(&export_script, database_url)
}

fn add_readme(&self) -> Result<(), PerformError> {
use std::io::Write;

let mut readme = File::create(self.export_dir.join("README.md"))?;
readme.write_all(include_bytes!("dump_db/readme_for_tarball.md"))?;
Ok(())
}

fn add_metadata(&self) -> Result<(), PerformError> {
#[derive(Serialize)]
struct Metadata<'a> {
timestamp: &'a chrono::DateTime<chrono::Utc>,
crates_io_commit: String,
format_version: &'static str,
}
let metadata = Metadata {
timestamp: &self.timestamp,
crates_io_commit: dotenv::var("HEROKU_SLUG_COMMIT")
.unwrap_or_else(|_| "unknown".to_owned()),
format_version: "0.1",
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm assuming you're envisioning this version number to increase its minor version with any backwards compatible schema change and increase its major version with any breaking schema change? So to give some information about compatibility with previous database dumps without needing to look up changes between git SHAs?

I'm a little concerned about the usefulness of this version number because I can very easily see us forgetting to update this with schema changes :-/ If it's not incremented meaningfully, then it's not going to be particularly useful, and people using the database dumps will need to look up what changed in the git history anyway.

Given that we recommend using the import script that does a destructive import anyway, rather than providing diffs between dumps say, is this going to provide enough value for people using the dumps to justify our maintenance of it?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You are right, this would need a bit more specification to be useful.

I did not have in mind to increase this on every schema change, but rather everytime we change something more fundamentally to the format of the tarball, like adding a fundamentally new file.

The main goal was to allow us to make backwards-incompatible changes, and indicate these in the version number. However, this doesn't really work. If we change the dump in a way that breaks compatibility, people will notice without checking a version number, since there tool will break. And if they can't go back to the old version, this version number does not really help.

So the only way to break compatibility is to provide dumps in the new format at a different URL alongside the dumps in the old format. And that does not require a version number, so I'll remove it again.

};
let file = File::create(self.export_dir.join("metadata.json"))?;
serde_json::to_writer_pretty(file, &metadata)?;
Ok(())
}
}

impl Drop for DumpDirectory {
fn drop(&mut self) {
std::fs::remove_dir_all(&self.export_dir).unwrap();
}
}

pub fn run_psql(script: &Path, database_url: &str) -> Result<(), PerformError> {
let psql_script = File::open(&script)?;
let psql = std::process::Command::new("psql")
.arg(database_url)
.current_dir(script.parent().unwrap())
.stdin(psql_script)
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::piped())
.spawn()?;
let output = psql.wait_with_output()?;
let stderr = String::from_utf8_lossy(&output.stderr);
if stderr.contains("ERROR") {
Err(format!("Error while executing psql: {}", stderr))?;
}
if !output.status.success() {
Err("psql did not finish successfully.")?;
}
Ok(())
}

/// Manage the tarball of the database dump.
///
/// Create the tarball, upload it to S3, and make sure it gets deleted.
struct DumpTarball {
tarball_path: PathBuf,
}

impl DumpTarball {
fn create(export_dir: &Path) -> Result<Self, PerformError> {
let tarball_path = export_dir.with_extension("tar.gz");
let tarfile = File::create(&tarball_path)?;
let result = Self { tarball_path };
let encoder = flate2::write::GzEncoder::new(tarfile, flate2::Compression::default());
let mut archive = tar::Builder::new(encoder);
archive.append_dir_all(export_dir.file_name().unwrap(), &export_dir)?;
Ok(result)
}

fn upload(&self, target_name: &str, uploader: &Uploader) -> Result<(), PerformError> {
let client = reqwest::Client::new();
let tarfile = File::open(&self.tarball_path)?;
let content_length = tarfile.metadata()?.len();
// TODO Figure out the correct content type.
uploader
.upload(
&client,
target_name,
tarfile,
content_length,
"application/gzip",
)
.map_err(std_error_no_send)?;
Ok(())
}
}

impl Drop for DumpTarball {
fn drop(&mut self) {
std::fs::remove_file(&self.tarball_path).unwrap();
}
}

mod gen_scripts;
Loading