-
Notifications
You must be signed in to change notification settings - Fork 16
/
main.rs
281 lines (247 loc) · 8.38 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
extern crate actix;
extern crate actix_web;
extern crate env_logger;
extern crate failure;
extern crate futures;
#[macro_use]
extern crate log;
#[macro_use]
extern crate maplit;
extern crate serde;
extern crate serde_derive;
extern crate serde_json;
extern crate structopt;
#[macro_use]
extern crate prometheus;
mod graph;
mod metadata;
mod metrics;
mod policy;
mod scraper;
use actix::prelude::*;
use actix_web::{http::Method, middleware::Logger, server, App};
use actix_web::{HttpRequest, HttpResponse};
use failure::{Error, Fallible};
use futures::future;
use futures::prelude::*;
use prometheus::{Histogram, IntCounter, IntCounterVec, IntGaugeVec};
use std::collections::HashMap;
use std::net::{IpAddr, Ipv4Addr};
use std::sync::Arc;
use structopt::StructOpt;
lazy_static::lazy_static! {
static ref V1_GRAPH_INCOMING_REQS: IntCounter = register_int_counter!(opts!(
"dumnati_pe_v1_graph_incoming_requests_total",
"Total number of incoming HTTP client request to /v1/graph"
))
.unwrap();
static ref UNIQUE_IDS: IntCounter = register_int_counter!(opts!(
"dumnati_pe_v1_graph_unique_uuids_total",
"Total number of unique node UUIDs (per-instance Bloom filter)."
))
.unwrap();
static ref ROLLOUT_WARINESS: Histogram = register_histogram!(
"dumnati_pe_v1_graph_rollout_wariness",
"Per-request rollout wariness.",
prometheus::linear_buckets(0.0, 0.1, 11).unwrap()
)
.unwrap();
static ref GRAPH_FINAL_EDGES: IntGaugeVec = register_int_gauge_vec!(
"dumnati_gb_scraper_graph_final_edges",
"Number of edges in the cached graph, after processing",
&["stream"]
).unwrap();
static ref GRAPH_FINAL_RELEASES: IntGaugeVec = register_int_gauge_vec!(
"dumnati_gb_scraper_graph_final_releases",
"Number of releases in the cached graph, after processing",
&["stream"]
).unwrap();
static ref LAST_REFRESH: IntGaugeVec = register_int_gauge_vec!(
"dumnati_gb_scraper_graph_last_refresh_timestamp",
"UTC timestamp of last graph refresh",
&["stream"]
).unwrap();
static ref UPSTREAM_SCRAPES: IntCounterVec = register_int_counter_vec!(
"dumnati_gb_scraper_upstream_scrapes_total",
"Total number of upstream scrapes",
&["stream"]
).unwrap();
}
fn main() -> Fallible<()> {
env_logger::Builder::from_default_env().try_init()?;
let opts = CliOptions::from_args();
trace!("started with CLI options: {:#?}", opts);
let sys = actix::System::new("dumnati");
// TODO(lucab): figure out all configuration params.
let streams_cfg = maplit::btreeset!["testing", "stable"];
let mut scrapers = HashMap::with_capacity(streams_cfg.len());
for stream in streams_cfg {
let addr = scraper::Scraper::new(stream)?.start();
scrapers.insert(stream.to_string(), addr);
}
let node_population = Arc::new(cbloom::Filter::new(10 * 1024 * 1024, 1_000_000));
let service_state = AppState {
scrapers,
population: Arc::clone(&node_population),
};
let gb_service = service_state.clone();
let gb_status = service_state.clone();
let pe_service = service_state.clone();
let pe_status = service_state.clone();
// Graph-builder service.
server::new(move || {
App::with_state(gb_service.clone())
.middleware(Logger::default())
.route("/v1/graph", Method::GET, gb_serve_graph)
})
.bind((IpAddr::from(Ipv4Addr::UNSPECIFIED), 8080))?
.start();
// Graph-builder status service.
server::new(move || {
App::with_state(gb_status.clone())
.middleware(Logger::default())
.route("/metrics", Method::GET, metrics::serve_metrics)
})
.bind((IpAddr::from(Ipv4Addr::UNSPECIFIED), 9080))?
.start();
// Policy-engine service.
server::new(move || {
App::with_state(pe_service.clone())
.middleware(Logger::default())
.route("/v1/graph", Method::GET, pe_serve_graph)
})
.bind((IpAddr::from(Ipv4Addr::UNSPECIFIED), 8081))?
.start();
// Policy-engine status service.
server::new(move || {
App::with_state(pe_status.clone())
.middleware(Logger::default())
.route("/metrics", Method::GET, metrics::serve_metrics)
})
.bind((IpAddr::from(Ipv4Addr::UNSPECIFIED), 9081))?
.start();
sys.run();
Ok(())
}
#[derive(Clone, Debug)]
pub(crate) struct AppState {
scrapers: HashMap<String, Addr<scraper::Scraper>>,
population: Arc<cbloom::Filter>,
}
pub(crate) fn gb_serve_graph(
req: HttpRequest<AppState>,
) -> Box<dyn Future<Item = HttpResponse, Error = Error>> {
let basearch = req
.query()
.get("basearch")
.map(String::from)
.unwrap_or_default();
let stream = req
.query()
.get("stream")
.map(String::from)
.unwrap_or_default();
let addr = match req.state().scrapers.get(&stream) {
None => return Box::new(future::ok(HttpResponse::NotFound().finish())),
Some(addr) => addr,
};
let cached_graph = addr.send(scraper::GetCachedGraph { stream }).flatten();
let resp = cached_graph
.and_then(|graph| policy::pick_basearch(graph, basearch))
.map(|graph| policy::filter_deadends(graph))
.and_then(|graph| {
serde_json::to_string_pretty(&graph).map_err(|e| failure::format_err!("{}", e))
})
.map(|json| {
HttpResponse::Ok()
.content_type("application/json")
.body(json)
});
Box::new(resp)
}
pub(crate) fn pe_serve_graph(
req: HttpRequest<AppState>,
) -> Box<dyn Future<Item = HttpResponse, Error = Error>> {
pe_record_metrics(&req);
let basearch = req
.query()
.get("basearch")
.map(String::from)
.unwrap_or_default();
let stream = req
.query()
.get("stream")
.map(String::from)
.unwrap_or_default();
let addr = match req.state().scrapers.get(&stream) {
None => return Box::new(future::ok(HttpResponse::NotFound().finish())),
Some(addr) => addr,
};
let wariness = compute_wariness(&req.query());
ROLLOUT_WARINESS.observe(wariness);
let cached_graph = addr.send(scraper::GetCachedGraph { stream }).flatten();
let resp = cached_graph
.and_then(|graph| policy::pick_basearch(graph, basearch))
.map(move |graph| policy::throttle_rollouts(graph, wariness))
.map(|graph| policy::filter_deadends(graph))
.and_then(|graph| {
serde_json::to_string_pretty(&graph).map_err(|e| failure::format_err!("{}", e))
})
.map(|json| {
HttpResponse::Ok()
.content_type("application/json")
.body(json)
});
Box::new(resp)
}
fn compute_wariness(params: &HashMap<String, String>) -> f64 {
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
if let Ok(input) = params
.get("rollout_wariness")
.map(String::from)
.unwrap_or_default()
.parse::<f64>()
{
let wariness = input.max(0.0).min(1.0);
return wariness;
}
let uuid = params
.get("node_uuid")
.map(String::from)
.unwrap_or_default();
let wariness = {
// Left limit not included in range.
const COMPUTED_MIN: f64 = 0.0 + 0.000001;
const COMPUTED_MAX: f64 = 1.0;
let mut hasher = DefaultHasher::new();
uuid.hash(&mut hasher);
let digest = hasher.finish();
// Scale down.
let scaled = (digest as f64) / (std::u64::MAX as f64);
// Clamp within limits.
scaled.max(COMPUTED_MIN).min(COMPUTED_MAX)
};
wariness
}
pub(crate) fn pe_record_metrics(req: &HttpRequest<AppState>) {
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
V1_GRAPH_INCOMING_REQS.inc();
let population = &req.state().population;
if let Some(uuid) = req.query().get("node_uuid") {
let mut hasher = DefaultHasher::default();
uuid.hash(&mut hasher);
let client_uuid = hasher.finish();
if !population.maybe_contains(client_uuid) {
population.insert(client_uuid);
UNIQUE_IDS.inc();
}
}
}
#[derive(Debug, StructOpt)]
pub(crate) struct CliOptions {
/// Path to configuration file.
#[structopt(short = "c")]
pub config_path: Option<String>,
}