-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.rs
301 lines (258 loc) · 7.86 KB
/
main.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
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
#[macro_use]
extern crate log;
#[macro_use]
extern crate async_trait;
use crate::elastic::ElasticLink;
use anyhow::Result;
use futures::StreamExt;
use indicatif::{ProgressBar, ProgressStyle};
use shared::db;
use shared::db::Database;
use shrust::{Shell, ShellIO};
use std::io::Write;
use std::path::PathBuf;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::Duration;
use structopt::StructOpt;
use wither::bson::doc;
use wither::Model;
mod check_links;
mod elastic;
mod scans;
mod stats;
macro_rules! enclose {
( ($( $x:ident ),*) $y:expr ) => {
{
$(let $x = $x.clone();)*
$y
}
};
}
#[derive(StructOpt, Debug, Clone)]
pub struct Opt {
/// The Path to the OpenDirectoryDownloader executable. This executable's scan dir is inferred automatically.
#[structopt(
long,
default_value = "OpenDirectoryDownloader/OpenDirectoryDownloader"
)]
odd: PathBuf,
/// Additional scan directories
#[structopt(long)]
scan_dir: Vec<PathBuf>,
/// Elasticsearch address
#[structopt(long, default_value = "http://127.0.0.1:9200")]
elastic_url: String,
/// Elasticsearch password
#[structopt(long, env = "ELASTIC_PASS", default_value = "")]
elastic_pass: String,
/// Directory for public files (e.g. stats.json)
#[structopt(long, default_value = ".")]
public_dir: PathBuf,
// Disables the scheduler, allowing for exports etc.
#[structopt(long)]
disable_scheduler: bool,
}
#[async_std::main]
async fn main() -> Result<()> {
fern::Dispatch::new()
.format(|out, message, record| {
out.finish(format_args!(
"{} [{}] [{}] {}",
chrono::Local::now().format("[%H:%M:%S]"),
record.level(),
record.target(),
message
))
})
.level(log::LevelFilter::Info)
.level_for("isahc", log::LevelFilter::Error)
.chain(fern::log_file("odcrawler-discovery.log")?)
.apply()?;
let mut opt = Opt::from_args();
let mut odd_scan_dir = opt.odd.parent().unwrap().to_path_buf();
odd_scan_dir.push("Scans");
std::fs::create_dir_all(&odd_scan_dir).unwrap();
opt.scan_dir.push(odd_scan_dir);
dbg!(&opt);
let db = db::Database::new().await.unwrap();
if !opt.disable_scheduler {
let scheduler_db = db.clone();
let scheduler_opt = opt.clone();
let _scheduler_handle = std::thread::spawn(|| {
async_std::task::block_on(scheduler_loop(scheduler_opt, scheduler_db))
});
}
let mut shell = Shell::new(());
shell.new_command("add", "Adds an OD to the database", 1, |io, _, s| {
writeln!(io, "STUB: add {} to DB", s[0])?;
warn!("STUB: add {} to DB", s[0]);
Ok(())
});
shell.new_command_noargs(
"dump",
"Creates a new Dump",
enclose! { (opt, db) move |io, _| {
if let Err(e) = async_std::task::block_on(stats::create_dump(&opt, &db)) {
writeln!(io, "Error while creating dump: {}", e)?;
error!("Error while creating dump: {}", e);
};
Ok(())
}},
);
shell.new_command_noargs(
"export",
"Exports all links to Elasticsearch",
enclose! { (db, opt) move |io, _| {
if let Err(e) = async_std::task::block_on(export_all(&opt, &db)) {
writeln!(io, "Error while exporting links: {}", e)?;
error!("Error while exporting links: {}", e);
};
Ok(())
}},
);
shell.run_loop(&mut ShellIO::default());
Ok(())
}
pub async fn export_all(opt: &Opt, db: &Database) -> Result<()> {
info!("Adding or removing all links to/from Elasticsearch");
let alive_ods: Vec<String> = db
.get_opendirectories(false)
.await?
.filter_map(|r| async { r.ok().map(|od| od.url) })
.collect()
.await;
let total = db::Link::collection(&db.db)
.estimated_document_count(None)
.await? as u64;
let exported = AtomicU64::new(0);
let pb = ProgressBar::new(total).with_style(
ProgressStyle::default_bar().template("{percent}%, ETA {eta} {wide_bar} {pos}/~{len}"),
);
pb.enable_steady_tick(100);
db::Link::find(&db.db, doc! {}, None)
.await?
.filter_map(|l| async { l.ok() })
.map(|l| (alive_ods.contains(&l.opendirectory), ElasticLink::from(l)))
.chunks(5_000)
.for_each_concurrent(4, |chunk| async {
let len = chunk.len();
let chunk = chunk;
let mut body = elastic::BulkBody::default();
for (is_alive, link) in chunk {
body.items.push(if is_alive {
elastic::BulkAction::Index(link)
} else {
elastic::BulkAction::Delete(link.id)
});
}
if let Err(e) = elastic::bulk_request(opt, body) {
error!("Error exporting links to Elasticsearch: {}", e);
};
exported.fetch_add(len as u64, Ordering::Relaxed);
let exported_inner = exported.load(Ordering::Relaxed);
if exported_inner > total {
pb.set_length(total);
}
pb.set_position(exported_inner as u64);
})
.await;
info!("Exported {} documents", exported.into_inner());
Ok(())
}
#[async_trait]
trait Schedule {
fn name(&self) -> &str;
/// How often this should run:
/// 1 = run every time
/// 5 = run every 5 times
fn frequency(&self) -> u16;
async fn run(&self, opt: &Opt, db: &mut Database) -> Result<()>;
}
struct ProcessResults;
#[async_trait]
impl Schedule for ProcessResults {
fn name(&self) -> &str {
"process results"
}
fn frequency(&self) -> u16 {
2
}
async fn run(&self, opt: &Opt, db: &mut Database) -> Result<()> {
scans::process_scans(opt, db).await
}
}
struct ScanOpendirectory;
#[async_trait]
impl Schedule for ScanOpendirectory {
fn name(&self) -> &str {
"scan opendirectory"
}
fn frequency(&self) -> u16 {
4
}
async fn run(&self, _: &Opt, _: &mut Database) -> Result<()> {
scans::scan_opendirectories()
}
}
struct CheckLinks;
#[async_trait]
impl Schedule for CheckLinks {
fn name(&self) -> &str {
"check links"
}
fn frequency(&self) -> u16 {
100
}
async fn run(&self, opt: &Opt, db: &mut Database) -> Result<()> {
check_links::check_opendirectories(opt, db).await
}
}
struct UpdateStats;
#[async_trait]
impl Schedule for UpdateStats {
fn name(&self) -> &str {
"update stats"
}
fn frequency(&self) -> u16 {
3
}
async fn run(&self, opt: &Opt, db: &mut Database) -> Result<()> {
stats::update_stats(opt, db).await
}
}
struct CreateDump;
#[async_trait]
impl Schedule for CreateDump {
fn name(&self) -> &str {
"create dump"
}
fn frequency(&self) -> u16 {
250
}
async fn run(&self, opt: &Opt, db: &mut Database) -> Result<()> {
stats::create_dump(opt, db).await
}
}
async fn scheduler_loop(opt: Opt, mut db: Database) {
info!("Started scheduler thread");
let schedule_tasks: [Box<dyn Schedule>; 5] = [
Box::new(ProcessResults),
Box::new(ScanOpendirectory),
Box::new(CheckLinks),
Box::new(UpdateStats),
Box::new(CreateDump),
];
let mut counter: u16 = 1;
loop {
std::thread::sleep(Duration::from_secs(3));
for task in &schedule_tasks {
if counter % task.frequency() == 0 {
if let Err(e) = task.run(&opt, &mut db).await {
error!("Failed to run task '{}' due to error: \n{}", task.name(), e);
break;
};
}
}
counter = counter.overflowing_add(1).0;
}
}