forked from graphprotocol/graph-node
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconfig.rs
More file actions
412 lines (371 loc) · 12 KB
/
Copy pathconfig.rs
File metadata and controls
412 lines (371 loc) · 12 KB
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
use graph::prelude::{
anyhow::{anyhow, Result},
info, serde_json, Logger, NodeId,
};
use graph_chain_ethereum::CLEANUP_BLOCKS;
use graph_store_postgres::{DeploymentPlacer, Shard as ShardName, PRIMARY_SHARD};
use regex::Regex;
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::fs::read_to_string;
use url::Url;
const ANY_NAME: &str = ".*";
pub struct Opt {
pub postgres_url: Option<String>,
pub config: Option<String>,
pub store_connection_pool_size: u32,
pub postgres_secondary_hosts: Vec<String>,
pub postgres_host_weights: Vec<usize>,
pub disable_block_ingestor: bool,
pub node_id: String,
}
impl Default for Opt {
fn default() -> Self {
Opt {
postgres_url: None,
config: None,
store_connection_pool_size: 10,
postgres_secondary_hosts: vec![],
postgres_host_weights: vec![],
disable_block_ingestor: true,
node_id: "default".to_string(),
}
}
}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct Config {
#[serde(rename = "store")]
pub stores: BTreeMap<String, Shard>,
pub deployment: Deployment,
ingestor: Ingestor,
}
fn validate_name(s: &str) -> Result<()> {
if s.is_empty() {
return Err(anyhow!("names must not be empty"));
}
if s.len() > 30 {
return Err(anyhow!(
"names can be at most 30 characters, but `{}` has {} characters",
s,
s.len()
));
}
if !s
.chars()
.all(|c| (c.is_ascii_alphanumeric() && c.is_lowercase()) || c == '-')
{
return Err(anyhow!(
"name `{}` is invalid: names can only contain lowercase alphanumeric characters or '-'",
s
));
}
Ok(())
}
impl Config {
/// Check that the config is valid. Some defaults (like `pool_size`) will
/// be filled in from `opt` at the same time.
fn validate(&mut self, opt: &Opt) -> Result<()> {
if !self.stores.contains_key(PRIMARY_SHARD.as_str()) {
return Err(anyhow!("missing a primary store"));
}
if self.stores.len() > 1 && *CLEANUP_BLOCKS {
// See 8b6ad0c64e244023ac20ced7897fe666
return Err(anyhow!(
"GRAPH_ETHEREUM_CLEANUP_BLOCKS can not be used with a sharded store"
));
}
for (key, shard) in self.stores.iter_mut() {
ShardName::new(key.clone()).map_err(|e| anyhow!(e))?;
shard.validate(opt)?;
}
self.deployment.validate()?;
// Check that deployment rules only reference existing stores
for (i, rule) in self.deployment.rules.iter().enumerate() {
if !self.stores.contains_key(&rule.shard) {
return Err(anyhow!(
"unknown shard {} in deployment rule {}",
rule.shard,
i
));
}
}
Ok(())
}
/// Load a configuration file if `opt.config` is set. If not, generate
/// a config from the command line arguments in `opt`
pub fn load(logger: &Logger, opt: &Opt) -> Result<Config> {
if let Some(config) = &opt.config {
info!(logger, "Reading configuration file `{}`", config);
let config = read_to_string(config)?;
let mut config: Config = toml::from_str(&config)?;
config.validate(opt)?;
Ok(config)
} else {
info!(
logger,
"Generating configuration from command line arguments"
);
Self::from_opt(opt)
}
}
fn from_opt(opt: &Opt) -> Result<Config> {
let ingestor = Ingestor::from_opt(opt);
let deployment = Deployment::from_opt(opt);
let mut stores = BTreeMap::new();
stores.insert(PRIMARY_SHARD.to_string(), Shard::from_opt(opt)?);
Ok(Config {
stores,
deployment,
ingestor,
})
}
/// Genrate a JSON representation of the config.
pub fn to_json(&self) -> Result<String> {
// It would be nice to produce a TOML representation, but that runs
// into this error: https://github.com/alexcrichton/toml-rs/issues/142
// and fixing it as described in the issue didn't fix it. Since serializing
// this data isn't crucial and only needed for debugging, we'll
// just stick with JSON
Ok(serde_json::to_string_pretty(&self)?)
}
pub fn primary_store(&self) -> &Shard {
self.stores
.get(PRIMARY_SHARD.as_str())
.expect("a validated config has a primary store")
}
}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct Shard {
pub connection: String,
#[serde(default = "one")]
pub weight: usize,
#[serde(default)]
pub pool_size: u32,
#[serde(default)]
pub replicas: BTreeMap<String, Replica>,
}
fn check_pool_size(pool_size: u32, connection: &str) -> Result<()> {
if pool_size < 2 {
Err(anyhow!(
"connection pool size must be at least 2, but is {} for {}",
pool_size,
connection
))
} else {
Ok(())
}
}
impl Shard {
fn validate(&mut self, opt: &Opt) -> Result<()> {
self.connection = shellexpand::env(&self.connection)?.into_owned();
if self.pool_size == 0 {
self.pool_size = opt.store_connection_pool_size;
}
check_pool_size(self.pool_size, &self.connection)?;
for (name, replica) in self.replicas.iter_mut() {
validate_name(name)?;
replica.validate(opt)?;
}
Ok(())
}
fn from_opt(opt: &Opt) -> Result<Self> {
let postgres_url = opt
.postgres_url
.as_ref()
.expect("validation checked that postgres_url is set");
check_pool_size(opt.store_connection_pool_size, &postgres_url)?;
let mut replicas = BTreeMap::new();
for (i, host) in opt.postgres_secondary_hosts.iter().enumerate() {
let replica = Replica {
connection: replace_host(&postgres_url, &host),
weight: opt.postgres_host_weights.get(i + 1).cloned().unwrap_or(1),
pool_size: opt.store_connection_pool_size,
};
replicas.insert(format!("replica{}", i + 1), replica);
}
Ok(Self {
connection: postgres_url.clone(),
weight: opt.postgres_host_weights.get(0).cloned().unwrap_or(1),
pool_size: opt.store_connection_pool_size,
replicas,
})
}
}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct Replica {
pub connection: String,
#[serde(default = "one")]
pub weight: usize,
#[serde(default = "zero")]
pub pool_size: u32,
}
impl Replica {
fn validate(&mut self, opt: &Opt) -> Result<()> {
self.connection = shellexpand::env(&self.connection)?.into_owned();
if self.pool_size == 0 {
self.pool_size = opt.store_connection_pool_size;
}
check_pool_size(self.pool_size, &self.connection)?;
Ok(())
}
}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct Deployment {
#[serde(rename = "rule")]
rules: Vec<Rule>,
}
impl Deployment {
fn validate(&self) -> Result<()> {
if self.rules.is_empty() {
return Err(anyhow!(
"there must be at least one deployment rule".to_string()
));
}
let mut default_rule = false;
for rule in &self.rules {
rule.validate()?;
if default_rule {
return Err(anyhow!("rules after a default rule are useless"));
}
default_rule = rule.is_default();
}
if !default_rule {
return Err(anyhow!(
"the rules do not contain a default rule that matches everything"
));
}
Ok(())
}
fn from_opt(_: &Opt) -> Self {
Self { rules: vec![] }
}
}
impl DeploymentPlacer for Deployment {
fn place(&self, name: &str, network: &str) -> Result<Option<(ShardName, Vec<NodeId>)>, String> {
// Errors here are really programming errors. We should have validated
// everything already so that the various conversions can't fail. We
// still return errors so that they bubble up to the deployment request
// rather than crashing the node and burying the crash in the logs
let placement = match self.rules.iter().find(|rule| rule.matches(name, network)) {
Some(rule) => {
let shard = ShardName::new(rule.shard.clone()).map_err(|e| e.to_string())?;
let indexers: Vec<_> = rule
.indexers
.iter()
.map(|idx| {
NodeId::new(idx.clone())
.map_err(|()| format!("{} is not a valid node name", idx))
})
.collect::<Result<Vec<_>, _>>()?;
Some((shard, indexers))
}
None => None,
};
Ok(placement)
}
}
#[derive(Clone, Debug, Deserialize, Serialize)]
struct Rule {
#[serde(rename = "match", default)]
pred: Predicate,
#[serde(default = "primary_store")]
shard: String,
indexers: Vec<String>,
}
impl Rule {
fn is_default(&self) -> bool {
self.pred.matches_anything()
}
fn matches(&self, name: &str, network: &str) -> bool {
self.pred.matches(name, network)
}
fn validate(&self) -> Result<()> {
if self.indexers.is_empty() {
return Err(anyhow!("useless rule without indexers"));
}
for indexer in &self.indexers {
NodeId::new(indexer).map_err(|()| anyhow!("invalid node id {}", &indexer))?;
}
ShardName::new(self.shard.clone())
.map_err(|e| anyhow!("illegal name for store shard `{}`: {}", &self.shard, e))?;
Ok(())
}
}
#[derive(Clone, Debug, Deserialize, Serialize)]
struct Predicate {
#[serde(with = "serde_regex", default = "any_name")]
name: Regex,
network: Option<String>,
}
impl Predicate {
fn matches_anything(&self) -> bool {
self.name.as_str() == ANY_NAME && self.network.is_none()
}
pub fn matches(&self, name: &str, network: &str) -> bool {
if let Some(n) = &self.network {
if n != network {
return false;
}
}
match self.name.find(name) {
None => false,
Some(m) => m.as_str() == name,
}
}
}
impl Default for Predicate {
fn default() -> Self {
Predicate {
name: any_name(),
network: None,
}
}
}
#[derive(Clone, Debug, Deserialize, Serialize)]
struct Ingestor {
node: String,
}
impl Ingestor {
fn from_opt(opt: &Opt) -> Self {
// If we are not the block ingestor, set the node name
// to something that is definitely not our node_id
if opt.disable_block_ingestor {
Ingestor {
node: format!("{} is not ingesting", opt.node_id),
}
} else {
Ingestor {
node: opt.node_id.clone(),
}
}
}
}
/// Replace the host portion of `url` and return a new URL with `host`
/// as the host portion
///
/// Panics if `url` is not a valid URL (which won't happen in our case since
/// we would have paniced before getting here as `url` is the connection for
/// the primary Postgres instance)
fn replace_host(url: &str, host: &str) -> String {
let mut url = match Url::parse(url) {
Ok(url) => url,
Err(_) => panic!("Invalid Postgres URL {}", url),
};
if let Err(e) = url.set_host(Some(host)) {
panic!("Invalid Postgres url {}: {}", url, e.to_string());
}
url.into_string()
}
// Various default functions for deserialization
fn any_name() -> Regex {
Regex::new(ANY_NAME).unwrap()
}
fn primary_store() -> String {
PRIMARY_SHARD.to_string()
}
fn one() -> usize {
1
}
fn zero() -> u32 {
0
}