-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathgcs-rsync.rs
175 lines (156 loc) · 5.17 KB
/
gcs-rsync.rs
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
use std::{path::Path, str::FromStr};
use futures::{StreamExt, TryStreamExt};
use gcs_rsync::{
oauth2::token::TokenGenerator,
storage::{
credentials::{authorizeduser, metadata},
Error, StorageResult,
},
sync::{RSync, RSyncError, RSyncResult, Source},
};
use structopt::StructOpt;
#[derive(Debug, StructOpt)]
#[structopt(
name = "gcs-rsync",
about = "synchronize fs or gcs source to destination"
)]
struct Opt {
/// Use Google metadata api for authentication
#[structopt(short, long)]
use_metadata_token_api: bool,
/// Activate mirror mode (sync by default). /!\ This mode will deletes all extra entries.
#[structopt(short, long)]
mirror: bool,
/// Restore mtime on filesystem (disabled by default)
#[structopt(short, long)]
restore_fs_mtime: bool,
/// Include glob pattern, can be repeated
#[structopt(short = "i", long = "include")]
includes: Vec<String>,
/// Exclude glob pattern, can be repeated
#[structopt(short = "x", long = "exclude")]
excludes: Vec<String>,
/// Source path: can be either gs (gs://bucket/path/to/object) or fs source
/// To synchronize only a prefix: gs://bucket/path/to/your/prefix
/// To synchronize a full folder: gs://bucket/path/to/your/folder/ with the trailing slash in the end
#[structopt()]
source: String,
/// Destination path: can be either gs (gs://bucket/path/to/object) or fs source
/// To synchronize a full folder: gs://bucket/path/to/your/folder/ with the trailing slash in the end
#[structopt()]
dest: String,
}
#[derive(Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BucketPrefix {
pub bucket: String,
pub prefix: String,
}
impl FromStr for BucketPrefix {
type Err = Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
s.strip_prefix("gs://")
.and_then(|part| part.split_once('/'))
.ok_or(Error::GcsInvalidUrl {
url: s.to_owned(),
message: "gs url should be gs://bucket/object/path/name".to_owned(),
})
.and_then(|(bucket, prefix)| BucketPrefix::new(bucket, prefix))
}
}
impl BucketPrefix {
pub fn new(bucket: &str, prefix: &str) -> StorageResult<Self> {
if bucket.is_empty() {
return Err(Error::GcsInvalidObjectName);
}
Ok(Self {
bucket: bucket.to_owned(),
prefix: prefix.to_owned(),
})
}
}
async fn get_source(
path: &str,
is_dest: bool,
use_metadata_token_api: bool,
) -> RSyncResult<Source> {
match BucketPrefix::from_str(path).ok() {
Some(o) => {
let token_generator: Option<Box<dyn TokenGenerator>> = if use_metadata_token_api {
Some(Box::new(
metadata::default().map_err(RSyncError::StorageError)?,
))
} else {
let token_generator = authorizeduser::default().await;
match token_generator {
Err(_) => {
println!("no default auth found, running gcs-rsync without auth");
None
}
Ok(o) => Some(Box::new(o)),
}
};
let bucket = o.bucket.as_str();
let prefix = o.prefix.as_str();
match token_generator {
None => Ok(Source::gcs_no_auth(bucket, prefix)),
Some(token_generator) => Source::gcs(token_generator, bucket, prefix).await,
}
}
None => {
let path = Path::new(path);
if path.exists() || is_dest {
Ok(Source::fs(path))
} else {
Err(RSyncError::EmptyRelativePathError)
}
}
}
}
#[tokio::main]
async fn main() -> RSyncResult<()> {
let num_cpus = num_cpus::get();
let opt = Opt::from_args();
let source = get_source(&opt.source, false, opt.use_metadata_token_api).await?;
let dest = get_source(&opt.dest, true, opt.use_metadata_token_api).await?;
let rsync = RSync::new(source, dest)
.with_restore_fs_mtime(opt.restore_fs_mtime)
.with_includes(
opt.includes
.iter()
.map(String::as_ref)
.collect::<Vec<_>>()
.as_slice(),
)?
.with_excludes(
opt.excludes
.iter()
.map(String::as_ref)
.collect::<Vec<_>>()
.as_slice(),
)?;
if opt.mirror {
println!("mirroring {} > {}", &opt.source, &opt.dest);
rsync
.mirror()
.await
.try_buffer_unordered(num_cpus)
.for_each(|x| {
println!("{:?}", x);
futures::future::ready(())
})
.await;
} else {
println!("syncing {} > {}", &opt.source, &opt.dest);
rsync
.sync()
.await
.try_buffer_unordered(num_cpus)
.for_each(|x| {
println!("{:?}", x);
futures::future::ready(())
})
.await;
};
Ok(())
}