forked from solana-labs/solana
-
Notifications
You must be signed in to change notification settings - Fork 300
/
Copy pathmain.rs
2228 lines (2076 loc) · 90.3 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
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
#![allow(clippy::arithmetic_side_effects)]
#[cfg(not(any(target_env = "msvc", target_os = "freebsd")))]
use jemallocator::Jemalloc;
use {
agave_validator::{
admin_rpc_service,
admin_rpc_service::{load_staked_nodes_overrides, StakedNodesOverrides},
bootstrap,
cli::{self, app, warn_for_deprecated_arguments, DefaultArgs},
dashboard::Dashboard,
ledger_lockfile, lock_ledger, new_spinner_progress_bar, println_name_value,
redirect_stderr_to_file,
},
clap::{crate_name, value_t, value_t_or_exit, values_t, values_t_or_exit, ArgMatches},
console::style,
crossbeam_channel::unbounded,
log::*,
rand::{seq::SliceRandom, thread_rng},
solana_accounts_db::{
accounts_db::{AccountShrinkThreshold, AccountsDb, AccountsDbConfig, CreateAncientStorage},
accounts_file::StorageAccess,
accounts_index::{
AccountIndex, AccountSecondaryIndexes, AccountSecondaryIndexesIncludeExclude,
AccountsIndexConfig, IndexLimitMb, ScanFilter,
},
utils::{
create_all_accounts_run_and_snapshot_dirs, create_and_canonicalize_directories,
create_and_canonicalize_directory,
},
},
solana_clap_utils::input_parsers::{keypair_of, keypairs_of, pubkey_of, value_of, values_of},
solana_core::{
banking_trace::DISABLED_BAKING_TRACE_DIR,
consensus::tower_storage,
system_monitor_service::SystemMonitorService,
tpu::DEFAULT_TPU_COALESCE,
validator::{
is_snapshot_config_valid, BlockProductionMethod, BlockVerificationMethod,
TransactionStructure, Validator, ValidatorConfig, ValidatorError,
ValidatorStartProgress, ValidatorTpuConfig,
},
},
solana_gossip::{
cluster_info::{Node, NodeConfig},
contact_info::ContactInfo,
},
solana_ledger::{
blockstore_cleanup_service::{DEFAULT_MAX_LEDGER_SHREDS, DEFAULT_MIN_MAX_LEDGER_SHREDS},
blockstore_options::{
AccessType, BlockstoreCompressionType, BlockstoreOptions, BlockstoreRecoveryMode,
LedgerColumnOptions,
},
use_snapshot_archives_at_startup::{self, UseSnapshotArchivesAtStartup},
},
solana_perf::recycler::enable_recycler_warming,
solana_poh::poh_service,
solana_rpc::{
rpc::{JsonRpcConfig, RpcBigtableConfig},
rpc_pubsub_service::PubSubConfig,
},
solana_rpc_client::rpc_client::RpcClient,
solana_rpc_client_api::config::RpcLeaderScheduleConfig,
solana_runtime::{
runtime_config::RuntimeConfig,
snapshot_bank_utils::DISABLED_SNAPSHOT_ARCHIVE_INTERVAL,
snapshot_config::{SnapshotConfig, SnapshotUsage},
snapshot_utils::{self, ArchiveFormat, SnapshotVersion},
},
solana_sdk::{
clock::{Slot, DEFAULT_SLOTS_PER_EPOCH, DEFAULT_S_PER_SLOT},
commitment_config::CommitmentConfig,
hash::Hash,
pubkey::Pubkey,
signature::{read_keypair, Keypair, Signer},
},
solana_send_transaction_service::send_transaction_service,
solana_streamer::{quic::QuicServerParams, socket::SocketAddrSpace},
solana_tpu_client::tpu_client::DEFAULT_TPU_ENABLE_UDP,
std::{
collections::{HashSet, VecDeque},
env,
fs::{self, File},
net::{IpAddr, Ipv4Addr, SocketAddr},
num::NonZeroUsize,
path::{Path, PathBuf},
process::exit,
str::FromStr,
sync::{Arc, RwLock},
time::{Duration, SystemTime},
},
};
#[cfg(not(any(target_env = "msvc", target_os = "freebsd")))]
#[global_allocator]
static GLOBAL: Jemalloc = Jemalloc;
#[derive(Debug, PartialEq, Eq)]
enum Operation {
Initialize,
Run,
}
const MILLIS_PER_SECOND: u64 = 1000;
fn monitor_validator(ledger_path: &Path) {
let dashboard = Dashboard::new(ledger_path, None, None).unwrap_or_else(|err| {
println!(
"Error: Unable to connect to validator at {}: {:?}",
ledger_path.display(),
err,
);
exit(1);
});
dashboard.run(Duration::from_secs(2));
}
fn wait_for_restart_window(
ledger_path: &Path,
identity: Option<Pubkey>,
min_idle_time_in_minutes: usize,
max_delinquency_percentage: u8,
skip_new_snapshot_check: bool,
skip_health_check: bool,
) -> Result<(), Box<dyn std::error::Error>> {
let sleep_interval = Duration::from_secs(5);
let min_idle_slots = (min_idle_time_in_minutes as f64 * 60. / DEFAULT_S_PER_SLOT) as Slot;
let admin_client = admin_rpc_service::connect(ledger_path);
let rpc_addr = admin_rpc_service::runtime()
.block_on(async move { admin_client.await?.rpc_addr().await })
.map_err(|err| format!("Unable to get validator RPC address: {err}"))?;
let Some(rpc_client) = rpc_addr.map(RpcClient::new_socket) else {
return Err("RPC not available".into());
};
let my_identity = rpc_client.get_identity()?;
let identity = identity.unwrap_or(my_identity);
let monitoring_another_validator = identity != my_identity;
println_name_value("Identity:", &identity.to_string());
println_name_value(
"Minimum Idle Time:",
&format!("{min_idle_slots} slots (~{min_idle_time_in_minutes} minutes)"),
);
println!("Maximum permitted delinquency: {max_delinquency_percentage}%");
let mut current_epoch = None;
let mut leader_schedule = VecDeque::new();
let mut restart_snapshot = None;
let mut upcoming_idle_windows = vec![]; // Vec<(starting slot, idle window length in slots)>
let progress_bar = new_spinner_progress_bar();
let monitor_start_time = SystemTime::now();
let mut seen_incremential_snapshot = false;
loop {
let snapshot_slot_info = rpc_client.get_highest_snapshot_slot().ok();
let snapshot_slot_info_has_incremential = snapshot_slot_info
.as_ref()
.map(|snapshot_slot_info| snapshot_slot_info.incremental.is_some())
.unwrap_or_default();
seen_incremential_snapshot |= snapshot_slot_info_has_incremential;
let epoch_info = rpc_client.get_epoch_info_with_commitment(CommitmentConfig::processed())?;
let healthy = skip_health_check || rpc_client.get_health().ok().is_some();
let delinquent_stake_percentage = {
let vote_accounts = rpc_client.get_vote_accounts()?;
let current_stake: u64 = vote_accounts
.current
.iter()
.map(|va| va.activated_stake)
.sum();
let delinquent_stake: u64 = vote_accounts
.delinquent
.iter()
.map(|va| va.activated_stake)
.sum();
let total_stake = current_stake + delinquent_stake;
delinquent_stake as f64 / total_stake as f64
};
if match current_epoch {
None => true,
Some(current_epoch) => current_epoch != epoch_info.epoch,
} {
progress_bar.set_message(format!(
"Fetching leader schedule for epoch {}...",
epoch_info.epoch
));
let first_slot_in_epoch = epoch_info.absolute_slot - epoch_info.slot_index;
leader_schedule = rpc_client
.get_leader_schedule_with_config(
Some(first_slot_in_epoch),
RpcLeaderScheduleConfig {
identity: Some(identity.to_string()),
..RpcLeaderScheduleConfig::default()
},
)?
.ok_or_else(|| {
format!("Unable to get leader schedule from slot {first_slot_in_epoch}")
})?
.get(&identity.to_string())
.cloned()
.unwrap_or_default()
.into_iter()
.map(|slot_index| first_slot_in_epoch.saturating_add(slot_index as u64))
.filter(|slot| *slot > epoch_info.absolute_slot)
.collect::<VecDeque<_>>();
upcoming_idle_windows.clear();
{
let mut leader_schedule = leader_schedule.clone();
let mut max_idle_window = 0;
let mut idle_window_start_slot = epoch_info.absolute_slot;
while let Some(next_leader_slot) = leader_schedule.pop_front() {
let idle_window = next_leader_slot - idle_window_start_slot;
max_idle_window = max_idle_window.max(idle_window);
if idle_window > min_idle_slots {
upcoming_idle_windows.push((idle_window_start_slot, idle_window));
}
idle_window_start_slot = next_leader_slot;
}
if !leader_schedule.is_empty() && upcoming_idle_windows.is_empty() {
return Err(format!(
"Validator has no idle window of at least {} slots. Largest idle window \
for epoch {} is {} slots",
min_idle_slots, epoch_info.epoch, max_idle_window
)
.into());
}
}
current_epoch = Some(epoch_info.epoch);
}
let status = {
if !healthy {
style("Node is unhealthy").red().to_string()
} else {
// Wait until a hole in the leader schedule before restarting the node
let in_leader_schedule_hole = if epoch_info.slot_index + min_idle_slots
> epoch_info.slots_in_epoch
{
Err("Current epoch is almost complete".to_string())
} else {
while leader_schedule
.front()
.map(|slot| *slot < epoch_info.absolute_slot)
.unwrap_or(false)
{
leader_schedule.pop_front();
}
while upcoming_idle_windows
.first()
.map(|(slot, _)| *slot < epoch_info.absolute_slot)
.unwrap_or(false)
{
upcoming_idle_windows.pop();
}
match leader_schedule.front() {
None => {
Ok(()) // Validator has no leader slots
}
Some(next_leader_slot) => {
let idle_slots =
next_leader_slot.saturating_sub(epoch_info.absolute_slot);
if idle_slots >= min_idle_slots {
Ok(())
} else {
Err(match upcoming_idle_windows.first() {
Some((starting_slot, length_in_slots)) => {
format!(
"Next idle window in {} slots, for {} slots",
starting_slot.saturating_sub(epoch_info.absolute_slot),
length_in_slots
)
}
None => format!(
"Validator will be leader soon. Next leader slot is \
{next_leader_slot}"
),
})
}
}
}
};
match in_leader_schedule_hole {
Ok(_) => {
if skip_new_snapshot_check {
break; // Restart!
}
let snapshot_slot = snapshot_slot_info.map(|snapshot_slot_info| {
snapshot_slot_info
.incremental
.unwrap_or(snapshot_slot_info.full)
});
if restart_snapshot.is_none() {
restart_snapshot = snapshot_slot;
}
if restart_snapshot == snapshot_slot && !monitoring_another_validator {
"Waiting for a new snapshot".to_string()
} else if delinquent_stake_percentage
>= (max_delinquency_percentage as f64 / 100.)
{
style("Delinquency too high").red().to_string()
} else if seen_incremential_snapshot && !snapshot_slot_info_has_incremential
{
// Restarts using just a full snapshot will put the node significantly
// further behind than if an incremental snapshot is also used, as full
// snapshots are larger and take much longer to create.
//
// Therefore if the node just created a new full snapshot, wait a
// little longer until it creates the first incremental snapshot for
// the full snapshot.
"Waiting for incremental snapshot".to_string()
} else {
break; // Restart!
}
}
Err(why) => style(why).yellow().to_string(),
}
}
};
progress_bar.set_message(format!(
"{} | Processed Slot: {} {} | {:.2}% delinquent stake | {}",
{
let elapsed =
chrono::Duration::from_std(monitor_start_time.elapsed().unwrap()).unwrap();
format!(
"{:02}:{:02}:{:02}",
elapsed.num_hours(),
elapsed.num_minutes() % 60,
elapsed.num_seconds() % 60
)
},
epoch_info.absolute_slot,
if monitoring_another_validator {
"".to_string()
} else {
format!(
"| Full Snapshot Slot: {} | Incremental Snapshot Slot: {}",
snapshot_slot_info
.as_ref()
.map(|snapshot_slot_info| snapshot_slot_info.full.to_string())
.unwrap_or_else(|| '-'.to_string()),
snapshot_slot_info
.as_ref()
.and_then(|snapshot_slot_info| snapshot_slot_info
.incremental
.map(|incremental| incremental.to_string()))
.unwrap_or_else(|| '-'.to_string()),
)
},
delinquent_stake_percentage * 100.,
status
));
std::thread::sleep(sleep_interval);
}
drop(progress_bar);
println!("{}", style("Ready to restart").green());
Ok(())
}
fn set_repair_whitelist(
ledger_path: &Path,
whitelist: Vec<Pubkey>,
) -> Result<(), Box<dyn std::error::Error>> {
let admin_client = admin_rpc_service::connect(ledger_path);
admin_rpc_service::runtime()
.block_on(async move { admin_client.await?.set_repair_whitelist(whitelist).await })
.map_err(|err| {
std::io::Error::new(
std::io::ErrorKind::Other,
format!("setRepairWhitelist request failed: {err}"),
)
})?;
Ok(())
}
// This function is duplicated in ledger-tool/src/main.rs...
fn hardforks_of(matches: &ArgMatches<'_>, name: &str) -> Option<Vec<Slot>> {
if matches.is_present(name) {
Some(values_t_or_exit!(matches, name, Slot))
} else {
None
}
}
fn validators_set(
identity_pubkey: &Pubkey,
matches: &ArgMatches<'_>,
matches_name: &str,
arg_name: &str,
) -> Option<HashSet<Pubkey>> {
if matches.is_present(matches_name) {
let validators_set: HashSet<_> = values_t_or_exit!(matches, matches_name, Pubkey)
.into_iter()
.collect();
if validators_set.contains(identity_pubkey) {
eprintln!("The validator's identity pubkey cannot be a {arg_name}: {identity_pubkey}");
exit(1);
}
Some(validators_set)
} else {
None
}
}
fn get_cluster_shred_version(entrypoints: &[SocketAddr]) -> Option<u16> {
let entrypoints = {
let mut index: Vec<_> = (0..entrypoints.len()).collect();
index.shuffle(&mut rand::thread_rng());
index.into_iter().map(|i| &entrypoints[i])
};
for entrypoint in entrypoints {
match solana_net_utils::get_cluster_shred_version(entrypoint) {
Err(err) => eprintln!("get_cluster_shred_version failed: {entrypoint}, {err}"),
Ok(0) => eprintln!("entrypoint {entrypoint} returned shred-version zero"),
Ok(shred_version) => {
info!(
"obtained shred-version {} from {}",
shred_version, entrypoint
);
return Some(shred_version);
}
}
}
None
}
fn configure_banking_trace_dir_byte_limit(
validator_config: &mut ValidatorConfig,
matches: &ArgMatches,
) {
validator_config.banking_trace_dir_byte_limit = if matches.is_present("disable_banking_trace") {
// disable with an explicit flag; This effectively becomes `opt-out` by resetting to
// DISABLED_BAKING_TRACE_DIR, while allowing us to specify a default sensible limit in clap
// configuration for cli help.
DISABLED_BAKING_TRACE_DIR
} else {
// a default value in clap configuration (BANKING_TRACE_DIR_DEFAULT_BYTE_LIMIT) or
// explicit user-supplied override value
value_t_or_exit!(matches, "banking_trace_dir_byte_limit", u64)
};
}
pub fn main() {
let default_args = DefaultArgs::new();
let solana_version = solana_version::version!();
let cli_app = app(solana_version, &default_args);
let matches = cli_app.get_matches();
warn_for_deprecated_arguments(&matches);
let socket_addr_space = SocketAddrSpace::new(matches.is_present("allow_private_addr"));
let ledger_path = PathBuf::from(matches.value_of("ledger_path").unwrap());
let operation = match matches.subcommand() {
("", _) | ("run", _) => Operation::Run,
("authorized-voter", Some(authorized_voter_subcommand_matches)) => {
match authorized_voter_subcommand_matches.subcommand() {
("add", Some(subcommand_matches)) => {
if let Ok(authorized_voter_keypair) =
value_t!(subcommand_matches, "authorized_voter_keypair", String)
{
let authorized_voter_keypair = fs::canonicalize(&authorized_voter_keypair)
.unwrap_or_else(|err| {
println!(
"Unable to access path: {authorized_voter_keypair}: {err:?}"
);
exit(1);
});
println!(
"Adding authorized voter path: {}",
authorized_voter_keypair.display()
);
let admin_client = admin_rpc_service::connect(&ledger_path);
admin_rpc_service::runtime()
.block_on(async move {
admin_client
.await?
.add_authorized_voter(
authorized_voter_keypair.display().to_string(),
)
.await
})
.unwrap_or_else(|err| {
println!("addAuthorizedVoter request failed: {err}");
exit(1);
});
} else {
let mut stdin = std::io::stdin();
let authorized_voter_keypair =
read_keypair(&mut stdin).unwrap_or_else(|err| {
println!("Unable to read JSON keypair from stdin: {err:?}");
exit(1);
});
println!(
"Adding authorized voter: {}",
authorized_voter_keypair.pubkey()
);
let admin_client = admin_rpc_service::connect(&ledger_path);
admin_rpc_service::runtime()
.block_on(async move {
admin_client
.await?
.add_authorized_voter_from_bytes(Vec::from(
authorized_voter_keypair.to_bytes(),
))
.await
})
.unwrap_or_else(|err| {
println!("addAuthorizedVoterFromBytes request failed: {err}");
exit(1);
});
}
return;
}
("remove-all", _) => {
let admin_client = admin_rpc_service::connect(&ledger_path);
admin_rpc_service::runtime()
.block_on(async move {
admin_client.await?.remove_all_authorized_voters().await
})
.unwrap_or_else(|err| {
println!("removeAllAuthorizedVoters request failed: {err}");
exit(1);
});
println!("All authorized voters removed");
return;
}
_ => unreachable!(),
}
}
("plugin", Some(plugin_subcommand_matches)) => {
match plugin_subcommand_matches.subcommand() {
("list", _) => {
let admin_client = admin_rpc_service::connect(&ledger_path);
let plugins = admin_rpc_service::runtime()
.block_on(async move { admin_client.await?.list_plugins().await })
.unwrap_or_else(|err| {
println!("Failed to list plugins: {err}");
exit(1);
});
if !plugins.is_empty() {
println!("Currently the following plugins are loaded:");
for (plugin, i) in plugins.into_iter().zip(1..) {
println!(" {i}) {plugin}");
}
} else {
println!("There are currently no plugins loaded");
}
return;
}
("unload", Some(subcommand_matches)) => {
if let Ok(name) = value_t!(subcommand_matches, "name", String) {
let admin_client = admin_rpc_service::connect(&ledger_path);
admin_rpc_service::runtime()
.block_on(async {
admin_client.await?.unload_plugin(name.clone()).await
})
.unwrap_or_else(|err| {
println!("Failed to unload plugin {name}: {err:?}");
exit(1);
});
println!("Successfully unloaded plugin: {name}");
}
return;
}
("load", Some(subcommand_matches)) => {
if let Ok(config) = value_t!(subcommand_matches, "config", String) {
let admin_client = admin_rpc_service::connect(&ledger_path);
let name = admin_rpc_service::runtime()
.block_on(async {
admin_client.await?.load_plugin(config.clone()).await
})
.unwrap_or_else(|err| {
println!("Failed to load plugin {config}: {err:?}");
exit(1);
});
println!("Successfully loaded plugin: {name}");
}
return;
}
("reload", Some(subcommand_matches)) => {
if let Ok(name) = value_t!(subcommand_matches, "name", String) {
if let Ok(config) = value_t!(subcommand_matches, "config", String) {
let admin_client = admin_rpc_service::connect(&ledger_path);
admin_rpc_service::runtime()
.block_on(async {
admin_client
.await?
.reload_plugin(name.clone(), config.clone())
.await
})
.unwrap_or_else(|err| {
println!("Failed to reload plugin {name}: {err:?}");
exit(1);
});
println!("Successfully reloaded plugin: {name}");
}
}
return;
}
_ => unreachable!(),
}
}
("contact-info", Some(subcommand_matches)) => {
let output_mode = subcommand_matches.value_of("output");
let admin_client = admin_rpc_service::connect(&ledger_path);
let contact_info = admin_rpc_service::runtime()
.block_on(async move { admin_client.await?.contact_info().await })
.unwrap_or_else(|err| {
eprintln!("Contact info query failed: {err}");
exit(1);
});
if let Some(mode) = output_mode {
match mode {
"json" => println!("{}", serde_json::to_string_pretty(&contact_info).unwrap()),
"json-compact" => print!("{}", serde_json::to_string(&contact_info).unwrap()),
_ => unreachable!(),
}
} else {
print!("{contact_info}");
}
return;
}
("init", _) => Operation::Initialize,
("exit", Some(subcommand_matches)) => {
let min_idle_time = value_t_or_exit!(subcommand_matches, "min_idle_time", usize);
let force = subcommand_matches.is_present("force");
let monitor = subcommand_matches.is_present("monitor");
let skip_new_snapshot_check = subcommand_matches.is_present("skip_new_snapshot_check");
let skip_health_check = subcommand_matches.is_present("skip_health_check");
let max_delinquent_stake =
value_t_or_exit!(subcommand_matches, "max_delinquent_stake", u8);
if !force {
wait_for_restart_window(
&ledger_path,
None,
min_idle_time,
max_delinquent_stake,
skip_new_snapshot_check,
skip_health_check,
)
.unwrap_or_else(|err| {
println!("{err}");
exit(1);
});
}
let admin_client = admin_rpc_service::connect(&ledger_path);
admin_rpc_service::runtime()
.block_on(async move { admin_client.await?.exit().await })
.unwrap_or_else(|err| {
println!("exit request failed: {err}");
exit(1);
});
println!("Exit request sent");
if monitor {
monitor_validator(&ledger_path);
}
return;
}
("monitor", _) => {
monitor_validator(&ledger_path);
return;
}
("staked-nodes-overrides", Some(subcommand_matches)) => {
if !subcommand_matches.is_present("path") {
println!(
"staked-nodes-overrides requires argument of location of the configuration"
);
exit(1);
}
let path = subcommand_matches.value_of("path").unwrap();
let admin_client = admin_rpc_service::connect(&ledger_path);
admin_rpc_service::runtime()
.block_on(async move {
admin_client
.await?
.set_staked_nodes_overrides(path.to_string())
.await
})
.unwrap_or_else(|err| {
println!("setStakedNodesOverrides request failed: {err}");
exit(1);
});
return;
}
("set-identity", Some(subcommand_matches)) => {
let require_tower = subcommand_matches.is_present("require_tower");
if let Ok(identity_keypair) = value_t!(subcommand_matches, "identity", String) {
let identity_keypair = fs::canonicalize(&identity_keypair).unwrap_or_else(|err| {
println!("Unable to access path: {identity_keypair}: {err:?}");
exit(1);
});
println!(
"New validator identity path: {}",
identity_keypair.display()
);
let admin_client = admin_rpc_service::connect(&ledger_path);
admin_rpc_service::runtime()
.block_on(async move {
admin_client
.await?
.set_identity(identity_keypair.display().to_string(), require_tower)
.await
})
.unwrap_or_else(|err| {
println!("setIdentity request failed: {err}");
exit(1);
});
} else {
let mut stdin = std::io::stdin();
let identity_keypair = read_keypair(&mut stdin).unwrap_or_else(|err| {
println!("Unable to read JSON keypair from stdin: {err:?}");
exit(1);
});
println!("New validator identity: {}", identity_keypair.pubkey());
let admin_client = admin_rpc_service::connect(&ledger_path);
admin_rpc_service::runtime()
.block_on(async move {
admin_client
.await?
.set_identity_from_bytes(
Vec::from(identity_keypair.to_bytes()),
require_tower,
)
.await
})
.unwrap_or_else(|err| {
println!("setIdentityFromBytes request failed: {err}");
exit(1);
});
};
return;
}
("set-log-filter", Some(subcommand_matches)) => {
let filter = value_t_or_exit!(subcommand_matches, "filter", String);
let admin_client = admin_rpc_service::connect(&ledger_path);
admin_rpc_service::runtime()
.block_on(async move { admin_client.await?.set_log_filter(filter).await })
.unwrap_or_else(|err| {
println!("set log filter failed: {err}");
exit(1);
});
return;
}
("wait-for-restart-window", Some(subcommand_matches)) => {
let min_idle_time = value_t_or_exit!(subcommand_matches, "min_idle_time", usize);
let identity = pubkey_of(subcommand_matches, "identity");
let max_delinquent_stake =
value_t_or_exit!(subcommand_matches, "max_delinquent_stake", u8);
let skip_new_snapshot_check = subcommand_matches.is_present("skip_new_snapshot_check");
let skip_health_check = subcommand_matches.is_present("skip_health_check");
wait_for_restart_window(
&ledger_path,
identity,
min_idle_time,
max_delinquent_stake,
skip_new_snapshot_check,
skip_health_check,
)
.unwrap_or_else(|err| {
println!("{err}");
exit(1);
});
return;
}
("repair-shred-from-peer", Some(subcommand_matches)) => {
let pubkey = value_t!(subcommand_matches, "pubkey", Pubkey).ok();
let slot = value_t_or_exit!(subcommand_matches, "slot", u64);
let shred_index = value_t_or_exit!(subcommand_matches, "shred", u64);
let admin_client = admin_rpc_service::connect(&ledger_path);
admin_rpc_service::runtime()
.block_on(async move {
admin_client
.await?
.repair_shred_from_peer(pubkey, slot, shred_index)
.await
})
.unwrap_or_else(|err| {
println!("repair shred from peer failed: {err}");
exit(1);
});
return;
}
("repair-whitelist", Some(repair_whitelist_subcommand_matches)) => {
match repair_whitelist_subcommand_matches.subcommand() {
("get", Some(subcommand_matches)) => {
let output_mode = subcommand_matches.value_of("output");
let admin_client = admin_rpc_service::connect(&ledger_path);
let repair_whitelist = admin_rpc_service::runtime()
.block_on(async move { admin_client.await?.repair_whitelist().await })
.unwrap_or_else(|err| {
eprintln!("Repair whitelist query failed: {err}");
exit(1);
});
if let Some(mode) = output_mode {
match mode {
"json" => println!(
"{}",
serde_json::to_string_pretty(&repair_whitelist).unwrap()
),
"json-compact" => {
print!("{}", serde_json::to_string(&repair_whitelist).unwrap())
}
_ => unreachable!(),
}
} else {
print!("{repair_whitelist}");
}
return;
}
("set", Some(subcommand_matches)) => {
let whitelist = if subcommand_matches.is_present("whitelist") {
let validators_set: HashSet<_> =
values_t_or_exit!(subcommand_matches, "whitelist", Pubkey)
.into_iter()
.collect();
validators_set.into_iter().collect::<Vec<_>>()
} else {
return;
};
set_repair_whitelist(&ledger_path, whitelist).unwrap_or_else(|err| {
eprintln!("{err}");
exit(1);
});
return;
}
("remove-all", _) => {
set_repair_whitelist(&ledger_path, Vec::default()).unwrap_or_else(|err| {
eprintln!("{err}");
exit(1);
});
return;
}
_ => unreachable!(),
}
}
("set-public-address", Some(subcommand_matches)) => {
let parse_arg_addr = |arg_name: &str, arg_long: &str| -> Option<SocketAddr> {
subcommand_matches.value_of(arg_name).map(|host_port| {
solana_net_utils::parse_host_port(host_port).unwrap_or_else(|err| {
eprintln!(
"Failed to parse --{arg_long} address. It must be in the HOST:PORT \
format. {err}"
);
exit(1);
})
})
};
let tpu_addr = parse_arg_addr("tpu_addr", "tpu");
let tpu_forwards_addr = parse_arg_addr("tpu_forwards_addr", "tpu-forwards");
macro_rules! set_public_address {
($public_addr:expr, $set_public_address:ident, $request:literal) => {
if let Some(public_addr) = $public_addr {
let admin_client = admin_rpc_service::connect(&ledger_path);
admin_rpc_service::runtime()
.block_on(async move {
admin_client.await?.$set_public_address(public_addr).await
})
.unwrap_or_else(|err| {
eprintln!("{} request failed: {err}", $request);
exit(1);
});
}
};
}
set_public_address!(tpu_addr, set_public_tpu_address, "setPublicTpuAddress");
set_public_address!(
tpu_forwards_addr,
set_public_tpu_forwards_address,
"setPublicTpuForwardsAddress"
);
return;
}
_ => unreachable!(),
};
let cli::thread_args::NumThreadConfig {
accounts_db_clean_threads,
accounts_db_foreground_threads,
accounts_db_hash_threads,
accounts_index_flush_threads,
ip_echo_server_threads,
rayon_global_threads,
replay_forks_threads,
replay_transactions_threads,
rocksdb_compaction_threads,
rocksdb_flush_threads,
tvu_receive_threads,
tvu_sigverify_threads,
} = cli::thread_args::parse_num_threads_args(&matches);
let identity_keypair = keypair_of(&matches, "identity").unwrap_or_else(|| {
clap::Error::with_description(
"The --identity <KEYPAIR> argument is required",
clap::ErrorKind::ArgumentNotFound,
)
.exit();
});
let logfile = {
let logfile = matches
.value_of("logfile")
.map(|s| s.into())
.unwrap_or_else(|| format!("agave-validator-{}.log", identity_keypair.pubkey()));
if logfile == "-" {
None
} else {
println!("log file: {logfile}");
Some(logfile)
}
};
let use_progress_bar = logfile.is_none();
let _logger_thread = redirect_stderr_to_file(logfile);
info!("{} {}", crate_name!(), solana_version);
info!("Starting validator with: {:#?}", std::env::args_os());
let cuda = matches.is_present("cuda");
if cuda {
solana_perf::perf_libs::init_cuda();
enable_recycler_warming();
}
solana_core::validator::report_target_features();
let authorized_voter_keypairs = keypairs_of(&matches, "authorized_voter_keypairs")
.map(|keypairs| keypairs.into_iter().map(Arc::new).collect())
.unwrap_or_else(|| {
vec![Arc::new(
keypair_of(&matches, "identity").expect("identity"),
)]
});
let authorized_voter_keypairs = Arc::new(RwLock::new(authorized_voter_keypairs));
let staked_nodes_overrides_path = matches
.value_of("staked_nodes_overrides")
.map(str::to_string);
let staked_nodes_overrides = Arc::new(RwLock::new(
match &staked_nodes_overrides_path {
None => StakedNodesOverrides::default(),
Some(p) => load_staked_nodes_overrides(p).unwrap_or_else(|err| {
error!("Failed to load stake-nodes-overrides from {}: {}", p, err);
clap::Error::with_description(
"Failed to load configuration of stake-nodes-overrides argument",
clap::ErrorKind::InvalidValue,
)
.exit()
}),
}
.staked_map_id,
));
let init_complete_file = matches.value_of("init_complete_file");
let rpc_bootstrap_config = bootstrap::RpcBootstrapConfig {
no_genesis_fetch: matches.is_present("no_genesis_fetch"),
no_snapshot_fetch: matches.is_present("no_snapshot_fetch"),
check_vote_account: matches
.value_of("check_vote_account")
.map(|url| url.to_string()),
only_known_rpc: matches.is_present("only_known_rpc"),
max_genesis_archive_unpacked_size: value_t_or_exit!(
matches,
"max_genesis_archive_unpacked_size",
u64
),
incremental_snapshot_fetch: !matches.is_present("no_incremental_snapshots"),
};
let private_rpc = matches.is_present("private_rpc");
let do_port_check = !matches.is_present("no_port_check");
let tpu_coalesce = value_t!(matches, "tpu_coalesce_ms", u64)
.map(Duration::from_millis)
.unwrap_or(DEFAULT_TPU_COALESCE);