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
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
use std::{net::SocketAddr, path::PathBuf, sync::Arc, time::Duration};
use anyhow::Context;
use clap::{Parser, ValueEnum};
use librqbit::{
http_api::{ApiAddTorrentResponse, HttpApi},
http_api_client,
peer_connection::PeerConnectionOptions,
session::{
AddTorrentOptions, AddTorrentResponse, ListOnlyResponse, ManagedTorrentState, Session,
SessionOptions,
},
spawn_utils::{spawn, BlockingSpawner},
torrent_state::timeit,
};
use size_format::SizeFormatterBinary as SF;
use tracing::{error, info, span, warn, Level};
#[derive(Debug, Clone, Copy, ValueEnum)]
enum LogLevel {
Trace,
Debug,
Info,
Warn,
Error,
}
#[derive(Parser)]
#[command(version, author, about)]
struct Opts {
/// The loglevel
#[arg(value_enum, short = 'v')]
log_level: Option<LogLevel>,
/// The interval to poll trackers, e.g. 30s.
/// Trackers send the refresh interval when we connect to them. Often this is
/// pretty big, e.g. 30 minutes. This can force a certain value.
#[arg(short = 'i', long = "tracker-refresh-interval", value_parser = parse_duration::parse)]
force_tracker_interval: Option<Duration>,
/// The listen address for HTTP API
#[arg(long = "http-api-listen-addr", default_value = "127.0.0.1:3030")]
http_api_listen_addr: SocketAddr,
/// Set this flag if you want to use tokio's single threaded runtime.
/// It MAY perform better, but the main purpose is easier debugging, as time
/// profilers work better with this one.
#[arg(short, long)]
single_thread_runtime: bool,
#[arg(long = "disable-dht")]
disable_dht: bool,
/// Set this to disable DHT reading and storing it's state.
/// For now this is a useful workaround if you want to launch multiple rqbit instances,
/// otherwise DHT port will conflict.
#[arg(long = "disable-dht-persistence")]
disable_dht_persistence: bool,
/// The connect timeout, e.g. 1s, 1.5s, 100ms etc.
#[arg(long = "peer-connect-timeout", value_parser = parse_duration::parse, default_value="2s")]
peer_connect_timeout: Duration,
/// The connect timeout, e.g. 1s, 1.5s, 100ms etc.
#[arg(long = "peer-read-write-timeout" , value_parser = parse_duration::parse, default_value="10s")]
peer_read_write_timeout: Duration,
/// How many threads to spawn for the executor.
#[arg(short = 't', long)]
worker_threads: Option<usize>,
#[command(subcommand)]
subcommand: SubCommand,
}
#[derive(Parser)]
struct ServerStartOptions {
/// The output folder to write to. If not exists, it will be created.
output_folder: String,
}
#[derive(Parser)]
struct ServerOpts {
#[clap(subcommand)]
subcommand: ServerSubcommand,
}
#[derive(Parser)]
enum ServerSubcommand {
Start(ServerStartOptions),
}
#[derive(Parser)]
struct DownloadOpts {
/// The filename or URL of the torrent. If URL, http/https/magnet are supported.
torrent_path: Vec<String>,
/// The output folder to write to. If not exists, it will be created.
/// If not specified, would use the server's output folder. If there's no server
/// running, this is required.
#[arg(short = 'o', long)]
output_folder: Option<String>,
/// The sub folder within output folder to write to. Useful when you have
/// a server running with output_folder configured, and don't want to specify
/// the full path every time.
#[arg(short = 's', long)]
sub_folder: Option<String>,
/// If set, only the file whose filename matching this regex will
/// be downloaded
#[arg(short = 'r', long = "filename-re")]
only_files_matching_regex: Option<String>,
/// Only list the torrent metadata contents, don't do anything else.
#[arg(short, long)]
list: bool,
/// Set if you are ok to write on top of existing files
#[arg(long)]
overwrite: bool,
/// Exit the program once the torrents complete download.
#[arg(short = 'e', long)]
exit_on_finish: bool,
}
// server start
// download [--connect-to-existing] --output-folder(required) [file1] [file2]
#[derive(Parser)]
enum SubCommand {
Server(ServerOpts),
Download(DownloadOpts),
}
fn init_logging(opts: &Opts) {
if std::env::var_os("RUST_LOG").is_none() {
match opts.log_level.as_ref() {
Some(level) => {
let level_str = match level {
LogLevel::Trace => "trace",
LogLevel::Debug => "debug",
LogLevel::Info => "info",
LogLevel::Warn => "warn",
LogLevel::Error => "error",
};
std::env::set_var("RUST_LOG", level_str);
}
None => {
std::env::set_var("RUST_LOG", "info");
}
};
}
use tracing_subscriber::{fmt, prelude::*, EnvFilter};
tracing_subscriber::registry()
.with(fmt::layer())
.with(EnvFilter::from_default_env())
.init();
}
fn _start_deadlock_detector_thread() {
use parking_lot::deadlock;
use std::thread;
// Create a background thread which checks for deadlocks every 10s
thread::spawn(move || loop {
thread::sleep(Duration::from_secs(10));
let deadlocks = deadlock::check_deadlock();
if deadlocks.is_empty() {
continue;
}
println!("{} deadlocks detected", deadlocks.len());
for (i, threads) in deadlocks.iter().enumerate() {
println!("Deadlock #{}", i);
for t in threads {
println!("Thread Id {:#?}", t.thread_id());
println!("{:#?}", t.backtrace());
}
}
std::process::exit(42);
});
}
fn main() -> anyhow::Result<()> {
let opts = Opts::parse();
init_logging(&opts);
// start_deadlock_detector_thread();
let (mut rt_builder, spawner) = match opts.single_thread_runtime {
true => (
tokio::runtime::Builder::new_current_thread(),
BlockingSpawner::new(false),
),
false => (
{
let mut b = tokio::runtime::Builder::new_multi_thread();
if let Some(e) = opts.worker_threads {
b.worker_threads(e);
}
b
},
BlockingSpawner::new(true),
),
};
let rt = rt_builder
.enable_time()
.enable_io()
// the default is 512, it can get out of hand, as this program is CPU-bound on
// hash checking.
// note: we aren't using spawn_blocking() anymore, so this doesn't apply,
// however I'm still messing around, so in case we do, let's block the number of
// spawned threads.
.max_blocking_threads(8)
.build()?;
rt.block_on(async_main(opts, spawner))
}
async fn async_main(opts: Opts, spawner: BlockingSpawner) -> anyhow::Result<()> {
let sopts = SessionOptions {
disable_dht: opts.disable_dht,
disable_dht_persistence: opts.disable_dht_persistence,
dht_config: None,
peer_id: None,
peer_opts: Some(PeerConnectionOptions {
connect_timeout: Some(opts.peer_connect_timeout),
read_write_timeout: Some(opts.peer_read_write_timeout),
..Default::default()
}),
};
let stats_printer = |session: Arc<Session>| async move {
loop {
session.with_torrents(|torrents| {
for (idx, torrent) in torrents.iter().enumerate() {
match &torrent.state {
ManagedTorrentState::Initializing => {
info!("[{}] initializing", idx);
},
ManagedTorrentState::Running(handle) => {
let stats = timeit("stats_snapshot", || handle.torrent_state().stats_snapshot());
let speed = handle.speed_estimator();
let total = stats.total_bytes;
let progress = stats.total_bytes - stats.remaining_bytes;
let downloaded_pct = if stats.remaining_bytes == 0 {
100f64
} else {
(progress as f64 / total as f64) * 100f64
};
info!(
"[{}]: {:.2}% ({:.2}), down speed {:.2} MiB/s, fetched {}, remaining {:.2} of {:.2}, uploaded {:.2}, peers: {{live: {}, connecting: {}, queued: {}, seen: {}, dead: {}}}",
idx,
downloaded_pct,
SF::new(progress),
speed.download_mbps(),
SF::new(stats.fetched_bytes),
SF::new(stats.remaining_bytes),
SF::new(total),
SF::new(stats.uploaded_bytes),
stats.peer_stats.live,
stats.peer_stats.connecting,
stats.peer_stats.queued,
stats.peer_stats.seen,
stats.peer_stats.dead,
);
},
}
}
});
tokio::time::sleep(Duration::from_secs(1)).await;
}
};
match &opts.subcommand {
SubCommand::Server(server_opts) => match &server_opts.subcommand {
ServerSubcommand::Start(start_opts) => {
let session = Arc::new(
Session::new_with_opts(
PathBuf::from(&start_opts.output_folder),
spawner,
sopts,
)
.await
.context("error initializing rqbit session")?,
);
spawn(
span!(Level::TRACE, "stats_printer"),
stats_printer(session.clone()),
);
let http_api = HttpApi::new(session);
let http_api_listen_addr = opts.http_api_listen_addr;
http_api
.make_http_api_and_run(http_api_listen_addr)
.await
.context("error starting HTTP API")
}
},
SubCommand::Download(download_opts) => {
if download_opts.torrent_path.is_empty() {
anyhow::bail!("you must provide at least one URL to download")
}
let http_api_url = format!("http://{}", opts.http_api_listen_addr);
let client = http_api_client::HttpApiClient::new(&http_api_url)?;
let torrent_opts = AddTorrentOptions {
only_files_regex: download_opts.only_files_matching_regex.clone(),
overwrite: download_opts.overwrite,
list_only: download_opts.list,
force_tracker_interval: opts.force_tracker_interval,
output_folder: download_opts.output_folder.clone(),
sub_folder: download_opts.sub_folder.clone(),
..Default::default()
};
let connect_to_existing = match client.validate_rqbit_server().await {
Ok(_) => {
info!("Connected to HTTP API at {}, will call it instead of downloading within this process", client.base_url());
true
}
Err(err) => {
warn!("Error checking HTTP API at {}: {:}", client.base_url(), err);
false
}
};
if connect_to_existing {
for torrent_url in &download_opts.torrent_path {
match client
.add_torrent(torrent_url, Some(torrent_opts.clone()))
.await
{
Ok(ApiAddTorrentResponse { id, details }) => {
if let Some(id) = id {
info!("{} added to the server with index {}. Query {}/torrents/{}/(stats/haves) for details", details.info_hash, id, http_api_url, id)
}
for file in details.files {
info!(
"file {:?}, size {}{}",
file.name,
SF::new(file.length),
if file.included { "" } else { ", will skip" }
)
}
}
Err(err) => warn!("error adding {}: {:?}", torrent_url, err),
}
}
Ok(())
} else {
let session = Arc::new(
Session::new_with_opts(
download_opts
.output_folder
.as_ref()
.map(PathBuf::from)
.context(
"output_folder is required if can't connect to an existing server",
)?,
spawner,
sopts,
)
.await
.context("error initializing rqbit session")?,
);
spawn(
span!(Level::TRACE, "stats_printer"),
stats_printer(session.clone()),
);
let http_api = HttpApi::new(session.clone());
let http_api_listen_addr = opts.http_api_listen_addr;
spawn(
span!(Level::ERROR, "http_api"),
http_api.clone().make_http_api_and_run(http_api_listen_addr),
);
let mut added = false;
let mut handles = Vec::new();
for path in &download_opts.torrent_path {
let handle = match session
.add_torrent(path.as_str(), Some(torrent_opts.clone()))
.await
{
Ok(v) => match v {
AddTorrentResponse::AlreadyManaged(handle) => {
info!(
"torrent {:?} is already managed, downloaded to {:?}",
handle.info_hash, handle.output_folder
);
continue;
}
AddTorrentResponse::ListOnly(ListOnlyResponse {
info_hash: _,
info,
only_files,
}) => {
for (idx, (filename, len)) in
info.iter_filenames_and_lengths()?.enumerate()
{
let included = match &only_files {
Some(files) => files.contains(&idx),
None => true,
};
info!(
"File {}, size {}{}",
filename.to_string()?,
SF::new(len),
if included { "" } else { ", will skip" }
)
}
continue;
}
AddTorrentResponse::Added(handle) => {
added = true;
handle
}
},
Err(err) => {
error!("error adding {:?}: {:?}", &path, err);
continue;
}
};
http_api.add_torrent_handle(handle.clone());
handles.push(handle);
}
if download_opts.list {
Ok(())
} else if added {
if download_opts.exit_on_finish {
let results = futures::future::join_all(
handles.iter().map(|h| h.wait_until_completed()),
);
results.await;
info!("All downloads completed, exiting");
Ok(())
} else {
// Sleep forever.
loop {
tokio::time::sleep(Duration::from_secs(60)).await;
}
}
} else {
anyhow::bail!("no torrents were added")
}
}
}
}
}