-
Notifications
You must be signed in to change notification settings - Fork 640
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
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 32ec944
Add documentation to dump-db.toml.
smarnach 4bfd40c
Refactor enqueue helper in the enqueue-job binary.
smarnach 1d50084
Reduce global state in dump_db task.
smarnach 0ed2929
Address review comments by @carols10cents.
smarnach c2dce7c
Make database URL and upload target of DB dumps configurable.
smarnach a648dbd
Make cleanup of old database files more robust.
smarnach 29a86e9
Adapt dump_db to new uploader interface.
smarnach ec06f10
Correct error handling for the psql call.
smarnach d4b9f8c
Use Handlebars template to generate psql script.
smarnach ee888f8
Add code to generate import script for dumps.
smarnach bcbccd6
Include import and export scripts in the database dump.
smarnach 3eff6dc
Set default value for gh_access_token in import script.
smarnach b085a78
Simplify topological sort implementation.
smarnach b4ad1f1
Move psql script generation code to submodule.
smarnach 3b477c9
Refactor dump_db code to use Drop for cleanup.
smarnach 4448ca8
Refactor schema check unit test.
smarnach ede4fe0
Allow specifying column defaults in the DB dump config.
smarnach 1c4737b
Add basic unit tests for topological sorting.
smarnach c373f4b
Add prototype for dump_db integration test.
smarnach 44a995a
Use cloned() instead of copied().
smarnach f5f536a
Suppress migrations output in dump_db test.
smarnach cacbc4f
Merge remote-tracking branch 'origin' into dump-db-new
smarnach 200d99f
Remove crates.licence column from dump_db configuration.
smarnach db89e77
Merge remote-tracking branch 'origin' into dump-db-new
smarnach e760a53
Move data in dump tarbal into subdirectory.
smarnach 3beeb38
Add README and metadata to database dump.
smarnach d8b45d9
Remove redundant dependency in dump-db.toml.
smarnach cc8f22e
Inlcude schema dump in database dump.
smarnach 620bb51
Remove format version from dump metadata.
smarnach ba3709b
Document the database dumps in the frontend.
smarnach 4e479cf
Merge remote-tracking branch 'origin' into dump-db-new
smarnach c142880
Add dependency for badges on crates to db dump configuration.
smarnach a57fed2
Small edits to the data access documentation
carols10cents 01a4e98
Take new clippy suggestions that came with 1.38
carols10cents File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 {} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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", | ||
}; | ||
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; |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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.