-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathmanager.rs
More file actions
1842 lines (1733 loc) · 63.2 KB
/
manager.rs
File metadata and controls
1842 lines (1733 loc) · 63.2 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
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
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use clap::{Parser, Subcommand};
use config::PoolSize;
use git_testament::{git_testament, render_testament};
use graph::bail;
use graph::blockchain::BlockHash;
use graph::cheap_clone::CheapClone;
use graph::components::network_provider::ChainName;
use graph::endpoint::EndpointMetrics;
use graph::env::ENV_VARS;
use graph::log::logger_with_levels;
use graph::prelude::{BLOCK_NUMBER_MAX, BlockNumber, MetricsRegistry};
use graph::{data::graphql::load_manager::LoadManager, prelude::chrono, prometheus::Registry};
use graph::{
prelude::{
Logger, NodeId,
anyhow::{self, Context as AnyhowContextTrait, anyhow},
info, tokio,
},
url::Url,
};
use graph_chain_ethereum::EthereumAdapter;
use graph_graphql::prelude::GraphQlRunner;
use graph_node::config::{self, Config as Cfg};
use graph_node::manager::color::Terminal;
use graph_node::manager::commands;
use graph_node::network_setup::Networks;
use graph_node::{
MetricsContext, manager::deployment::DeploymentSearch, store_builder::StoreBuilder,
};
use graph_store_postgres::{
BlockStore, ChainStore, ConnectionPool, NotificationSender, PRIMARY_SHARD, PoolCoordinator,
Shard, Store, SubgraphStore, SubscriptionManager,
};
use itertools::Itertools;
use lazy_static::lazy_static;
use std::env;
use std::str::FromStr;
use std::{collections::HashMap, num::ParseIntError, sync::Arc, time::Duration};
const VERSION_LABEL_KEY: &str = "version";
git_testament!(TESTAMENT);
lazy_static! {
static ref RENDERED_TESTAMENT: String = render_testament!(TESTAMENT);
}
#[derive(Parser, Clone, Debug)]
#[clap(
name = "graphman",
about = "Management tool for a graph-node infrastructure",
author = "Graph Protocol, Inc.",
version = RENDERED_TESTAMENT.as_str()
)]
pub struct Opt {
#[clap(
long,
default_value = "off",
env = "GRAPHMAN_LOG",
help = "level for log output in slog format"
)]
pub log_level: String,
#[clap(
long,
default_value = "auto",
help = "whether to colorize the output. Set to 'auto' to colorize only on\nterminals (the default), 'always' to always colorize, or 'never'\nto not colorize at all"
)]
pub color: String,
#[clap(
long,
short,
env = "GRAPH_NODE_CONFIG",
help = "the name of the configuration file\n"
)]
pub config: String,
#[clap(
long,
default_value = "default",
value_name = "NODE_ID",
env = "GRAPH_NODE_ID",
help = "a unique identifier for this node. Should have the same value\nbetween consecutive node restarts\n"
)]
pub node_id: String,
#[clap(
long,
value_name = "{HOST:PORT|URL}",
default_value = "https://api.thegraph.com/ipfs/",
env = "IPFS",
help = "HTTP addresses of IPFS nodes\n"
)]
pub ipfs: Vec<String>,
#[clap(
long,
value_name = "{HOST:PORT|URL}",
default_value = "https://arweave.net",
env = "GRAPH_NODE_ARWEAVE_URL",
help = "HTTP base URL for arweave gateway"
)]
pub arweave: String,
#[clap(
long,
default_value = "3",
help = "the size for connection pools. Set to 0 to use pool size from\nconfiguration file corresponding to NODE_ID\n"
)]
pub pool_size: u32,
#[clap(long, value_name = "URL", help = "Base URL for forking subgraphs")]
pub fork_base: Option<String>,
#[clap(long, help = "version label, used for prometheus metrics")]
pub version_label: Option<String>,
#[clap(
long,
value_name = "{HOST:PORT|URL}",
env = "GRAPH_AMP_FLIGHT_SERVICE_ADDRESS",
help = "The address of the Amp Flight gRPC service"
)]
pub amp_flight_service_address: Option<String>,
#[clap(subcommand)]
pub cmd: Command,
}
#[derive(Clone, Debug, Subcommand)]
pub enum Command {
/// Calculate the transaction speed
TxnSpeed {
#[clap(long, short, default_value = "60")]
delay: u64,
},
/// Print details about a deployment
///
/// The deployment can be specified as either a subgraph name, an IPFS
/// hash `Qm..`, or the database namespace `sgdNNN`. Since the same IPFS
/// hash can be deployed in multiple shards, it is possible to specify
/// the shard by adding `:shard` to the IPFS hash.
Info {
/// The deployment (see above)
deployment: Option<DeploymentSearch>,
/// List all the deployments in the graph-node
#[clap(long, short)]
all: bool,
/// List only current version
#[clap(long, short)]
current: bool,
/// List only pending versions
#[clap(long, short)]
pending: bool,
/// Include status information
#[clap(long, short)]
status: bool,
/// List only used (current and pending) versions
#[clap(long, short)]
used: bool,
/// List names only for the active deployment
#[clap(long, short)]
brief: bool,
/// Do not print subgraph names
#[clap(long, short = 'N')]
no_name: bool,
},
/// Manage unused deployments
///
/// Record which deployments are unused with `record`, then remove them
/// with `remove`
#[clap(subcommand)]
Unused(UnusedCommand),
/// Remove a named subgraph
Remove {
/// The name of the subgraph to remove
name: String,
},
/// Create a subgraph name
Create {
/// The name of the subgraph to create
name: String,
},
/// Assign or reassign a deployment
Reassign {
/// The deployment (see `help info`)
deployment: DeploymentSearch,
/// The name of the node that should index the deployment
node: String,
},
/// Unassign a deployment
Unassign {
/// The deployment (see `help info`)
deployment: DeploymentSearch,
},
/// Pause a deployment
Pause {
/// The deployment (see `help info`)
deployment: DeploymentSearch,
},
/// Resume a deployment
Resume {
/// The deployment (see `help info`)
deployment: DeploymentSearch,
},
/// Pause and resume one or multiple deployments
Restart {
/// The deployment(s) (see `help info`)
deployments: Vec<DeploymentSearch>,
/// Sleep for this many seconds after pausing subgraphs
#[clap(
long,
short,
default_value = "20",
value_parser = parse_duration_in_secs
)]
sleep: Duration,
},
/// Rewind a subgraph to a specific block
Rewind {
/// Force rewinding even if the block hash is not found in the local
/// database
#[clap(long, short)]
force: bool,
/// Rewind to the start block of the subgraph
#[clap(long)]
start_block: bool,
/// Sleep for this many seconds after pausing subgraphs
#[clap(
long,
short,
default_value = "20",
value_parser = parse_duration_in_secs
)]
sleep: Duration,
/// The block hash of the target block
#[clap(
required_unless_present = "start_block",
conflicts_with = "start_block",
long,
short = 'H'
)]
block_hash: Option<String>,
/// The block number of the target block
#[clap(
required_unless_present = "start_block",
conflicts_with = "start_block",
long,
short = 'n'
)]
block_number: Option<i32>,
/// The deployments to rewind (see `help info`)
#[clap(required = true)]
deployments: Vec<DeploymentSearch>,
},
/// Deploy and run an arbitrary subgraph up to a certain block
///
/// The run can surpass it by a few blocks, it's not exact (use for dev
/// and testing purposes) -- WARNING: WILL RUN MIGRATIONS ON THE DB, DO
/// NOT USE IN PRODUCTION
///
/// Also worth noting that the deployed subgraph will be removed at the
/// end.
Run {
/// Network name (must fit one of the chain)
network_name: String,
/// Subgraph in the form `<IPFS Hash>` or `<name>:<IPFS Hash>`
subgraph: String,
/// Highest block number to process before stopping (inclusive)
stop_block: i32,
/// Prometheus push gateway endpoint.
prometheus_host: Option<String>,
},
/// Check and interrogate the configuration
///
/// Print information about a configuration file without
/// actually connecting to databases or network clients
#[clap(subcommand)]
Config(ConfigCommand),
/// Listen for store events and print them
#[clap(subcommand)]
Listen(ListenCommand),
/// Manage deployment copies and grafts
#[clap(subcommand)]
Copy(CopyCommand),
/// Run a GraphQL query
Query {
/// Save the JSON query result in this file
#[clap(long, short)]
output: Option<String>,
/// Save the query trace in this file
#[clap(long, short)]
trace: Option<String>,
/// The subgraph to query
///
/// Either a deployment id `Qm..` or a subgraph name
target: String,
/// The GraphQL query
query: String,
/// The variables in the form `key=value`
vars: Vec<String>,
},
/// Get information about chains and manipulate them
#[clap(subcommand)]
Chain(ChainCommand),
/// Manipulate internal subgraph statistics
#[clap(subcommand)]
Stats(StatsCommand),
/// Manage database indexes
#[clap(subcommand)]
Index(IndexCommand),
/// Prune subgraphs by removing old entity versions
///
/// Keep only entity versions that are needed to respond to queries at
/// block heights that are within `history` blocks of the subgraph head;
/// all other entity versions are removed.
#[clap(subcommand)]
Prune(PruneCommand),
/// General database management
#[clap(subcommand)]
Database(DatabaseCommand),
/// Deploy a subgraph
Deploy {
name: DeploymentSearch,
deployment: DeploymentSearch,
/// The url of the graph-node
#[clap(long, short, default_value = "http://localhost:8020")]
url: String,
},
/// Dump a subgraph deployment into a directory
///
/// EXPERIMENTAL - NOT FOR PRODUCTION USE
///
/// This will create a dump of the subgraph deployment in the specified
/// directory. The dump includes the subgraph manifest, the mapping, and
/// the data in the database as parquet files. The dump can be used to
/// restore the subgraph deployment later with the `restore` command.
Dump {
/// The deployment (see `help info`)
deployment: DeploymentSearch,
/// The name of the directory to dump to
directory: String,
},
/// Restore a subgraph deployment from a dump directory
///
/// EXPERIMENTAL - NOT FOR PRODUCTION USE
///
/// Restore a subgraph deployment from a dump created with the `dump`
/// command.
Restore {
/// Path to the dump directory
directory: String,
/// The database shard to restore into. When not given, use the
/// deployment rules to determine the shard, or default to the
/// primary shard if no rules match. This option is required when
/// using `--add`
#[clap(long)]
shard: Option<String>,
/// Subgraph name for deployment rule matching and node assignment.
/// If omitted, uses an existing name from the database; errors if none found.
#[clap(long)]
name: Option<String>,
/// Drop and recreate if the deployment already exists in the target shard
#[clap(long, conflicts_with_all = ["add", "force"])]
replace: bool,
/// Create a copy in a shard that doesn't have this deployment (requires --shard)
#[clap(long, conflicts_with_all = ["replace", "force"])]
add: bool,
/// Restore no matter what: replace if exists in target shard, add if not
#[clap(long, conflicts_with_all = ["replace", "add"])]
force: bool,
},
}
impl Command {
/// Return `true` if the command should not override connection pool
/// sizes, in general only when we will not actually connect to any
/// databases
fn use_configured_pool_size(&self) -> bool {
matches!(self, Command::Config(_))
}
}
#[derive(Clone, Debug, Subcommand)]
pub enum UnusedCommand {
/// List unused deployments
List {
/// Only list unused deployments that still exist
#[clap(short, long, conflicts_with = "deployment")]
existing: bool,
/// Deployment
#[clap(short, long)]
deployment: Option<DeploymentSearch>,
},
/// Update and record currently unused deployments
Record,
/// Remove deployments that were marked as unused with `record`.
///
/// Deployments are removed in descending order of number of entities,
/// i.e., smaller deployments are removed before larger ones
Remove {
/// How many unused deployments to remove (default: all)
#[clap(short, long)]
count: Option<usize>,
/// Remove a specific deployment
#[clap(short, long, conflicts_with = "count")]
deployment: Option<String>,
/// Remove unused deployments that were recorded at least this many minutes ago
#[clap(short, long)]
older: Option<u32>,
},
}
#[derive(Clone, Debug, Subcommand)]
pub enum ConfigCommand {
/// Check and validate the configuration file
Check {
/// Print the configuration as JSON
#[clap(long)]
print: bool,
},
/// Print how a specific subgraph would be placed
Place {
/// The name of the subgraph
name: String,
/// The network the subgraph indexes
network: String,
},
/// Information about the size of database pools
Pools {
/// The names of the nodes that are going to run
nodes: Vec<String>,
/// Print connections by shard rather than by node
#[clap(short, long)]
shard: bool,
},
/// Show eligible providers
///
/// Prints the providers that can be used for a deployment on a given
/// network with the given features. Set the name of the node for which
/// to simulate placement with the toplevel `--node-id` option
Provider {
#[clap(short, long, default_value = "")]
features: String,
network: String,
},
/// Run all available provider checks against all providers.
CheckProviders {
/// Maximum duration of all provider checks for a provider.
///
/// Defaults to 60 seconds.
timeout_seconds: Option<u64>,
},
/// Show subgraph-specific settings
///
/// GRAPH_EXPERIMENTAL_SUBGRAPH_SETTINGS can add a file that contains
/// subgraph-specific settings. This command determines which settings
/// would apply when a subgraph <name> is deployed and prints the result
Setting {
/// The subgraph name for which to print settings
name: String,
},
}
#[derive(Clone, Debug, Subcommand)]
pub enum ListenCommand {
/// Listen only to assignment events
Assignments,
}
#[derive(Clone, Debug, Subcommand)]
pub enum CopyCommand {
/// Create a copy of an existing subgraph
///
/// The copy will be treated as its own deployment. The deployment with
/// IPFS hash `src` will be copied to a new deployment in the database
/// shard `shard` and will be assigned to `node` for indexing. The new
/// subgraph will start as a copy of all blocks of `src` that are
/// `offset` behind the current subgraph head of `src`. The offset
/// should be chosen such that only final blocks are copied
Create {
/// How far behind `src` subgraph head to copy
#[clap(long, short, default_value = "200")]
offset: u32,
/// Activate this copy once it has synced
#[clap(long, short, conflicts_with = "replace")]
activate: bool,
/// Replace the source with this copy once it has synced
#[clap(long, short, conflicts_with = "activate")]
replace: bool,
/// The source deployment (see `help info`)
src: DeploymentSearch,
/// The name of the database shard into which to copy
shard: String,
/// The name of the node that should index the copy
node: String,
},
/// Activate the copy of a deployment.
///
/// This will route queries to that specific copy (with some delay); the
/// previously active copy will become inactive. Only copies that have
/// progressed at least as far as the original should be activated.
Activate {
/// The IPFS hash of the deployment to activate
deployment: String,
/// The name of the database shard that holds the copy
shard: String,
},
/// List all currently running copy and graft operations
List,
/// Print the progress of a copy operation
Status {
/// The destination deployment of the copy operation (see `help info`)
dst: DeploymentSearch,
},
}
#[derive(Clone, Debug, Subcommand)]
pub enum ChainCommand {
/// List all chains that are in the database
List,
/// Show information about a chain
Info {
#[clap(
long,
short,
default_value = "50",
env = "ETHEREUM_REORG_THRESHOLD",
help = "the reorg threshold to check\n"
)]
reorg_threshold: i32,
#[clap(long, help = "display block hashes\n")]
hashes: bool,
name: String,
},
/// Remove a chain and all its data
///
/// There must be no deployments using that chain. If there are, the
/// subgraphs and/or deployments using the chain must first be removed
Remove { name: String },
/// Compares cached blocks with fresh ones and clears the block cache when they differ.
CheckBlocks {
#[clap(subcommand)] // Note that we mark a field as a subcommand
method: CheckBlockMethod,
/// Chain name (must be an existing chain, see 'chain list')
#[clap(value_parser = clap::builder::NonEmptyStringValueParser::new())]
chain_name: String,
},
/// Truncates the whole block cache for the given chain.
Truncate {
/// Chain name (must be an existing chain, see 'chain list')
#[clap(value_parser = clap::builder::NonEmptyStringValueParser::new())]
chain_name: String,
/// Skips confirmation prompt
#[clap(long, short)]
force: bool,
},
/// Update the genesis block hash for a chain
UpdateGenesis {
#[clap(long, short)]
force: bool,
#[clap(value_parser = clap::builder::NonEmptyStringValueParser::new())]
block_hash: String,
#[clap(value_parser = clap::builder::NonEmptyStringValueParser::new())]
chain_name: String,
},
/// Change the block cache shard for a chain
ChangeShard {
/// Chain name (must be an existing chain, see 'chain list')
#[clap(value_parser = clap::builder::NonEmptyStringValueParser::new())]
chain_name: String,
/// Shard name
#[clap(value_parser = clap::builder::NonEmptyStringValueParser::new())]
shard: String,
},
/// Execute operations on call cache.
CallCache {
#[clap(subcommand)]
method: CallCacheCommand,
/// Chain name (must be an existing chain, see 'chain list')
#[clap(value_parser = clap::builder::NonEmptyStringValueParser::new())]
chain_name: String,
},
/// Ingest a block into the block cache.
///
/// This will overwrite any blocks we may already have in the block
/// cache, and can therefore be used to get rid of duplicate blocks in
/// the block cache as well as making sure that a certain block is in
/// the cache
Ingest {
/// The name of the chain
name: String,
/// The block number to ingest
number: BlockNumber,
},
/// Rebuild a chain's storage schema and reset head metadata.
///
/// If the storage schema is missing, rebuilds it silently.
/// If the storage already exists, prompts for confirmation before
/// dropping and rebuilding it (use --force to skip the prompt).
RebuildStorage {
/// Chain name (must be an existing chain, see 'chain list')
#[clap(value_parser = clap::builder::NonEmptyStringValueParser::new())]
chain_name: String,
/// Skip confirmation prompt when storage already exists
#[clap(long, short)]
force: bool,
},
}
#[derive(Clone, Debug, Subcommand)]
pub enum CallCacheCommand {
/// Remove the call cache of the specified chain.
///
/// Either remove entries in the range `--from` and `--to`,
/// remove the cache for contracts that have not been accessed for the specified duration --ttl_days,
/// or remove the entire cache with `--remove-entire-cache`. Removing the entire
/// cache can reduce indexing performance significantly and should
/// generally be avoided.
Remove {
/// Remove the entire cache
#[clap(long, conflicts_with_all = &["from", "to"])]
remove_entire_cache: bool,
/// Remove the cache for contracts that have not been accessed in the last <TTL_DAYS> days
#[clap(long, conflicts_with_all = &["from", "to", "remove-entire-cache"], value_parser = clap::value_parser!(u32).range(1..))]
ttl_days: Option<u32>,
/// Maximum number of contracts to evict. When set, the effective TTL
/// is increased so that at most this many contracts are deleted.
#[clap(long, requires = "ttl_days")]
max_contracts: Option<usize>,
/// Starting block number
#[clap(long, short, conflicts_with = "remove-entire-cache", requires = "to")]
from: Option<i32>,
/// Ending block number
#[clap(long, short, conflicts_with = "remove-entire-cache", requires = "from")]
to: Option<i32>,
},
}
#[derive(Clone, Debug, Subcommand)]
pub enum StatsCommand {
/// Toggle whether a table is account-like
///
/// Setting a table to 'account-like' enables a query optimization that
/// is very effective for tables with a high ratio of entity versions
/// to distinct entities. It can take up to 5 minutes for this to take
/// effect.
AccountLike {
#[clap(long, short, help = "do not set but clear the account-like flag\n")]
clear: bool,
/// The deployment (see `help info`).
deployment: DeploymentSearch,
/// The name of the database table
table: String,
},
/// Show statistics for the tables of a deployment
///
/// Show how many distinct entities and how many versions the tables of
/// each subgraph have. The data is based on the statistics that
/// Postgres keeps, and only refreshed when a table is analyzed.
Show {
/// The deployment (see `help info`).
deployment: DeploymentSearch,
},
/// Perform a SQL ANALYZE in a Entity table
Analyze {
/// The deployment (see `help info`).
deployment: DeploymentSearch,
/// The name of the Entity to ANALYZE, in camel case. Analyze all
/// tables if omitted
entity: Option<String>,
},
/// Show statistics targets for the statistics collector
///
/// For all tables in the given deployment, show the target for each
/// column. A value of `-1` means that the global default is used
Target {
/// The deployment (see `help info`).
deployment: DeploymentSearch,
},
/// Set the statistics targets for the statistics collector
///
/// Set (or reset) the target for a deployment. The statistics target
/// determines how much of a table Postgres will sample when it analyzes
/// a table. This can be particularly beneficial when Postgres chooses
/// suboptimal query plans for some queries. Increasing the target will
/// make analyzing tables take longer and will require more space in
/// Postgres' internal statistics storage.
///
/// If no `columns` are provided, change the statistics target for the
/// `id` and `block_range` columns which will usually be enough to
/// improve query performance, but it might be necessary to increase the
/// target for other columns, too.
SetTarget {
/// The value of the statistics target
#[clap(short, long, default_value = "200", conflicts_with = "reset")]
target: u32,
/// Reset the target so the default is used
#[clap(long, conflicts_with = "target")]
reset: bool,
/// Do not analyze changed tables
#[clap(long)]
no_analyze: bool,
/// The deployment (see `help info`).
deployment: DeploymentSearch,
/// The table for which to set the target, all if omitted
entity: Option<String>,
/// The columns to which to apply the target. Defaults to `id, block_range`
columns: Vec<String>,
},
}
#[derive(Clone, Debug, Subcommand)]
pub enum PruneCommand {
/// Prune a deployment in the foreground
///
/// Unless `--once` is given, this setting is permanent and the subgraph
/// will periodically be pruned to remove history as the subgraph head
/// moves forward.
Run {
/// The deployment to prune (see `help info`)
deployment: DeploymentSearch,
/// Prune by rebuilding tables when removing more than this fraction
/// of history. Defaults to GRAPH_STORE_HISTORY_REBUILD_THRESHOLD
#[clap(long, short)]
rebuild_threshold: Option<f64>,
/// Prune by deleting when removing more than this fraction of
/// history but less than rebuild_threshold. Defaults to
/// GRAPH_STORE_HISTORY_DELETE_THRESHOLD
#[clap(long, short)]
delete_threshold: Option<f64>,
/// How much history to keep in blocks. Defaults to
/// GRAPH_MIN_HISTORY_BLOCKS
#[clap(long, short = 'y')]
history: Option<usize>,
/// Prune only this once
#[clap(long, short)]
once: bool,
},
/// Prune a deployment in the background
///
/// Set the amount of history the subgraph should retain. The actual
/// data removal happens in the background and can be monitored with
/// `prune status`. It can take several minutes of the first pruning to
/// start, during which time `prune status` will not return any
/// information
Set {
/// The deployment to prune (see `help info`)
deployment: DeploymentSearch,
/// Prune by rebuilding tables when removing more than this fraction
/// of history. Defaults to GRAPH_STORE_HISTORY_REBUILD_THRESHOLD
#[clap(long, short)]
rebuild_threshold: Option<f64>,
/// Prune by deleting when removing more than this fraction of
/// history but less than rebuild_threshold. Defaults to
/// GRAPH_STORE_HISTORY_DELETE_THRESHOLD
#[clap(long, short)]
delete_threshold: Option<f64>,
/// How much history to keep in blocks. Defaults to
/// GRAPH_MIN_HISTORY_BLOCKS
#[clap(long, short = 'y')]
history: Option<usize>,
},
/// Show the status of a pruning operation
Status {
/// The number of the pruning run
#[clap(long, short)]
run: Option<usize>,
/// The deployment to check (see `help info`)
deployment: DeploymentSearch,
},
}
#[derive(Clone, Debug, Subcommand)]
pub enum IndexCommand {
/// Creates a new database index.
///
/// The new index will be created concurrenly for the provided entity and its fields. whose
/// names must be declared the in camel case, following GraphQL conventions.
///
/// The index will have its validity checked after the operation and will be dropped if it is
/// invalid.
///
/// This command may be time-consuming.
Create {
/// The deployment (see `help info`).
#[clap(value_parser = clap::builder::NonEmptyStringValueParser::new())]
deployment: DeploymentSearch,
/// The Entity name.
///
/// Can be expressed either in upper camel case (as its GraphQL definition) or in snake case
/// (as its SQL table name).
#[clap(value_parser = clap::builder::NonEmptyStringValueParser::new())]
entity: String,
/// The Field names.
///
/// Each field can be expressed either in camel case (as its GraphQL definition) or in snake
/// case (as its SQL colmun name).
#[clap(required = true)]
fields: Vec<String>,
/// The index method. Defaults to `btree` in general, and to `gist` when the index includes the `block_range` column
#[clap(
short, long, default_value = "btree",
value_parser = clap::builder::PossibleValuesParser::new(&["btree", "hash", "gist", "spgist", "gin", "brin"])
)]
method: Option<String>,
#[clap(long)]
/// Specifies a starting block number for creating a partial index.
after: Option<i32>,
},
/// Lists existing indexes for a given Entity
List {
/// Do not list attribute indexes
#[clap(short = 'A', long)]
no_attribute_indexes: bool,
/// Do not list any of the indexes that are generated by default,
/// including attribute indexes
#[clap(short = 'D', long)]
no_default_indexes: bool,
/// Print SQL statements instead of a more human readable overview
#[clap(long)]
sql: bool,
/// When `--sql` is used, make statements run concurrently
#[clap(long, requires = "sql")]
concurrent: bool,
/// When `--sql` is used, add `if not exists` clause
#[clap(long, requires = "sql")]
if_not_exists: bool,
/// The deployment (see `help info`).
deployment: DeploymentSearch,
/// The Entity name.
///
/// Can be expressed either in upper camel case (as its GraphQL definition) or in snake case
/// (as its SQL table name).
#[clap(value_parser = clap::builder::NonEmptyStringValueParser::new())]
entity: String,
},
/// Drops an index for a given deployment, concurrently
Drop {
/// The deployment (see `help info`).
deployment: DeploymentSearch,
/// The name of the index to be dropped
#[clap(value_parser = clap::builder::NonEmptyStringValueParser::new())]
index_name: String,
},
}
#[derive(Clone, Debug, Subcommand)]
pub enum DatabaseCommand {
/// Apply any pending migrations to the database schema in all shards
Migrate,
/// Refresh the mapping of tables into different shards
///
/// This command rebuilds the mappings of tables from one shard into all
/// other shards. It makes it possible to fix these mappings when a
/// database migration was interrupted before it could rebuild the
/// mappings
///
/// Each shard imports certain tables from all other shards. To recreate
/// the mappings in a given shard, use `--dest SHARD`, to recreate the
/// mappings in other shards that depend on a shard, use `--source
/// SHARD`. Without `--dest` and `--source` options, recreate all
/// possible mappings. Recreating mappings needlessly is harmless, but
/// might take quite a bit of time with a lot of shards.
Remap {
/// Only refresh mappings from SOURCE
#[clap(long, short)]
source: Option<String>,
/// Only refresh mappings inside DEST
#[clap(long, short)]
dest: Option<String>,
/// Continue remapping even when one operation fails
#[clap(long, short)]
force: bool,
},
}
#[derive(Clone, Debug, Subcommand)]
pub enum CheckBlockMethod {
/// The hash of the target block
ByHash {
/// The block hash to verify
hash: String,
},
/// The number of the target block
ByNumber {
/// The block number to verify
number: i32,
/// Delete duplicated blocks (by number) if found
#[clap(long, short, action)]
delete_duplicates: bool,
},
/// A block number range, inclusive on both ends.
ByRange {
/// The first block number to verify
#[clap(long, short)]
from: Option<i32>,
/// The last block number to verify
#[clap(long, short)]
to: Option<i32>,
/// Delete duplicated blocks (by number) if found
#[clap(long, short, action)]
delete_duplicates: bool,
},
}
impl From<Opt> for config::Opt {
fn from(opt: Opt) -> Self {
config::Opt {
config: Some(opt.config),
store_connection_pool_size: 5,
node_id: opt.node_id,
..Default::default()
}
}
}
/// Utilities to interact mostly with the store and build the parts of the
/// store we need for specific commands
struct Context {
logger: Logger,
node_id: NodeId,
config: Cfg,
ipfs_url: Vec<String>,
arweave_url: String,
fork_base: Option<Url>,
registry: Arc<MetricsRegistry>,
pub prometheus_registry: Arc<Registry>,
}
impl Context {
fn new(
logger: Logger,
node_id: NodeId,
config: Cfg,
ipfs_url: Vec<String>,
arweave_url: String,
fork_base: Option<Url>,
version_label: Option<String>,
) -> Self {
let prometheus_registry = Arc::new(
Registry::new_custom(
None,
version_label.map(|label| {
let mut m = HashMap::<String, String>::new();
m.insert(VERSION_LABEL_KEY.into(), label);
m
}),
)
.expect("unable to build prometheus registry"),
);
let registry = Arc::new(MetricsRegistry::new(
logger.clone(),
prometheus_registry.clone(),
));
Self {
logger,
node_id,
config,
ipfs_url,
fork_base,
registry,
prometheus_registry,
arweave_url,
}
}
fn metrics_registry(&self) -> Arc<MetricsRegistry> {
self.registry.clone()
}
fn config(&self) -> Cfg {
self.config.clone()
}
fn node_id(&self) -> NodeId {
self.node_id.clone()
}
fn notification_sender(&self) -> Arc<NotificationSender> {
Arc::new(NotificationSender::new(self.registry.clone()))
}
fn primary_pool(self) -> ConnectionPool {