-
Notifications
You must be signed in to change notification settings - Fork 164
Expand file tree
/
Copy pathservice.go
More file actions
1460 lines (1231 loc) · 51.8 KB
/
service.go
File metadata and controls
1460 lines (1231 loc) · 51.8 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
package service
import (
"fmt"
"os"
"path/filepath"
"regexp"
"strings"
"time"
"github.com/mitchellh/go-homedir"
"github.com/rivo/tview"
"github.com/urfave/cli"
"gopkg.in/yaml.v2"
"github.com/dustin/go-humanize"
cliconfig "github.com/rocket-pool/smartnode/rocketpool-cli/service/config"
"github.com/rocket-pool/smartnode/shared"
"github.com/rocket-pool/smartnode/shared/services/config"
"github.com/rocket-pool/smartnode/shared/services/rocketpool"
cfgtypes "github.com/rocket-pool/smartnode/shared/types/config"
cliutils "github.com/rocket-pool/smartnode/shared/utils/cli"
"github.com/rocket-pool/smartnode/shared/utils/cli/prompt"
"github.com/shirou/gopsutil/v3/disk"
)
// Settings
const (
ExporterContainerSuffix string = "_exporter"
ValidatorContainerSuffix string = "_validator"
BeaconContainerSuffix string = "_eth2"
ExecutionContainerSuffix string = "_eth1"
NodeContainerSuffix string = "_node"
ApiContainerSuffix string = "_api"
WatchtowerContainerSuffix string = "_watchtower"
PruneProvisionerContainerSuffix string = "_prune_provisioner"
clientDataVolumeName string = "/ethclient"
dataFolderVolumeName string = "/.rocketpool/data"
PruneFreeSpaceRequired uint64 = 50 * 1024 * 1024 * 1024
NethermindPruneFreeSpaceRequired uint64 = 250 * 1024 * 1024 * 1024
// Capture the entire image name, including the custom registry if present.
// Just ignore the version tag.
dockerImageRegex string = "(?P<image>.+):.*"
colorReset string = "\033[0m"
colorBold string = "\033[1m"
colorRed string = "\033[31m"
colorYellow string = "\033[33m"
colorGreen string = "\033[32m"
colorLightBlue string = "\033[36m"
clearLine string = "\033[2K"
)
// Install the Rocket Pool service
func installService(c *cli.Context) error {
dataPath := ""
// Prompt for confirmation
if !(c.Bool("yes") || prompt.Confirm(fmt.Sprintf(
"The Rocket Pool %s service will be installed.\n\n%sIf you're upgrading, your existing configuration will be backed up and preserved.\nAll of your previous settings will be migrated automatically.%s\nAre you sure you want to continue?",
shared.RocketPoolVersion(), colorGreen, colorReset,
))) {
fmt.Println("Cancelled.")
return nil
}
// Get RP client
rp := rocketpool.NewClientFromCtx(c)
defer rp.Close()
// Attempt to load the config to see if any settings need to be passed along to the install script
cfg, isNew, err := rp.LoadConfig()
if err != nil {
return fmt.Errorf("error loading old configuration: %w", err)
}
if !isNew {
dataPath = cfg.Smartnode.DataPath.Value.(string)
dataPath, err = homedir.Expand(dataPath)
if err != nil {
return fmt.Errorf("error getting data path from old configuration: %w", err)
}
}
// Install service
err = rp.InstallService(c.Bool("verbose"), c.Bool("no-deps"), c.String("path"), dataPath)
if err != nil {
return err
}
// Print success message & return
fmt.Println("")
fmt.Println("The Rocket Pool service was successfully installed!")
printPatchNotes(c)
// Reload the config after installation
_, isNew, err = rp.LoadConfig()
if err != nil {
return fmt.Errorf("error loading new configuration: %w", err)
}
// Report next steps
fmt.Printf("%s\n=== Next Steps ===\n", colorLightBlue)
fmt.Printf("Run 'rocketpool service config' to review the settings changes for this update, or to continue setting up your node.%s\n", colorReset)
// Print the docker permissions notice
if isNew {
fmt.Printf("\n%sNOTE:\nSince this is your first time installing Rocket Pool, please start a new shell session by logging out and back in or restarting the machine.\n", colorYellow)
fmt.Printf("This is necessary for your user account to have permissions to use Docker.%s", colorReset)
}
return nil
}
// Print the latest patch notes for this release
// TODO: get this from an external source and don't hardcode it into the CLI
func printPatchNotes(c *cli.Context) {
fmt.Print(shared.Logo())
fmt.Println()
fmt.Println()
fmt.Printf("%s=== Smart Node v%s ===%s\n", colorGreen, shared.RocketPoolVersion(), colorReset)
fmt.Println()
fmt.Printf("Changes you should be aware of before starting:\n")
fmt.Println()
fmt.Println()
}
// Install the Rocket Pool update tracker for the metrics dashboard
func installUpdateTracker(c *cli.Context) error {
// Prompt for confirmation
if !(c.Bool("yes") || prompt.Confirm(
"This will add the ability to display any available Operating System updates or new Rocket Pool versions on the metrics dashboard. "+
"Are you sure you want to install the update tracker?")) {
fmt.Println("Cancelled.")
return nil
}
// Get RP client
rp := rocketpool.NewClientFromCtx(c)
defer rp.Close()
// Install service
err := rp.InstallUpdateTracker(c.Bool("verbose"))
if err != nil {
return err
}
// Print success message & return
fmt.Println("")
fmt.Println("The Rocket Pool update tracker service was successfully installed!")
fmt.Println("")
fmt.Printf("%sNOTE:\nPlease restart the Smart Node stack to enable update tracking on the metrics dashboard.%s\n", colorYellow, colorReset)
fmt.Println("")
return nil
}
// View the Rocket Pool service status
func serviceStatus(c *cli.Context) error {
// Get RP client
rp := rocketpool.NewClientFromCtx(c)
defer rp.Close()
// Get the config
cfg, isNew, err := rp.LoadConfig()
if err != nil {
return fmt.Errorf("Error loading configuration: %w", err)
}
// Print what network we're on
err = cliutils.PrintNetwork(cfg.GetNetwork(), isNew)
if err != nil {
return err
}
// Print service status
return rp.PrintServiceStatus(getComposeFiles(c))
}
// Configure the service
func configureService(c *cli.Context) error {
// Make sure the config directory exists first
configPath := c.GlobalString("config-path")
path, err := homedir.Expand(configPath)
if err != nil {
return fmt.Errorf("error expanding config path [%s]: %w", configPath, err)
}
_, err = os.Stat(path)
if os.IsNotExist(err) {
fmt.Printf("%sYour configured Rocket Pool directory of [%s] does not exist.\nPlease follow the instructions at https://docs.rocketpool.net/node-staking/docker to install the Smart Node.%s\n", colorYellow, path, colorReset)
return nil
}
// Get RP client
rp := rocketpool.NewClientFromCtx(c)
defer rp.Close()
// Load the config, checking to see if it's new (hasn't been installed before)
var oldCfg *config.RocketPoolConfig
cfg, isNew, err := rp.LoadConfig()
if err != nil {
return fmt.Errorf("error loading user settings: %w", err)
}
// Check if this is a new install
isUpdate, err := rp.IsFirstRun()
if err != nil {
return fmt.Errorf("error checking for first-run status: %w", err)
}
// For upgrades, move the config to the old one and create a new upgraded copy
if isUpdate {
oldCfg = cfg
cfg = cfg.CreateCopy()
err = cfg.UpdateDefaults()
if err != nil {
return fmt.Errorf("error upgrading configuration with the latest parameters: %w", err)
}
}
cfg.ConfirmUpdateSuggestedSettings()
// Save the config and exit in headless mode
if c.NumFlags() > 0 {
err := configureHeadless(c, cfg)
if err != nil {
return fmt.Errorf("error updating config from provided arguments: %w", err)
}
return rp.SaveConfig(cfg)
}
// Check for native mode
isNative := c.GlobalIsSet("daemon-path")
app := tview.NewApplication()
md := cliconfig.NewMainDisplay(app, oldCfg, cfg, isNew, isUpdate, isNative)
err = app.Run()
if err != nil {
return err
}
// Deal with saving the config and printing the changes
if md.ShouldSave {
// Save the config
err = rp.SaveConfig(md.Config)
if err != nil {
return fmt.Errorf("error saving config: %w", err)
}
fmt.Println("Your changes have been saved!")
// Exit immediately if we're in native mode
if isNative {
fmt.Println("Please restart your daemon service for them to take effect.")
return nil
}
// Handle network changes
prefix := fmt.Sprint(md.PreviousConfig.Smartnode.ProjectName.Value)
if md.ChangeNetworks {
// Remove the checkpoint sync provider
md.Config.ConsensusCommon.CheckpointSyncProvider.Value = ""
err = rp.SaveConfig(md.Config)
if err != nil {
return fmt.Errorf("error saving config: %w", err)
}
fmt.Printf("%sWARNING: You have requested to change networks.\n\nAll of your existing chain data, your node wallet, and your validator keys will be removed. If you had a Checkpoint Sync URL provided for your Consensus client, it will be removed and you will need to specify a different one that supports the new network.\n\nPlease confirm you have backed up everything you want to keep, because it will be deleted if you answer `y` to the prompt below.\n\n%s", colorYellow, colorReset)
if !prompt.Confirm("Would you like the Smart Node to automatically switch networks for you? This will destroy and rebuild your `data` folder and all of Rocket Pool's Docker containers.") {
fmt.Println("To change networks manually, please follow the steps laid out in the Node Operator's guide (https://docs.rocketpool.net/node-staking/config-docker#choosing-a-network).")
return nil
}
err = changeNetworks(c, rp, fmt.Sprintf("%s%s", prefix, ApiContainerSuffix))
if err != nil {
fmt.Printf("%s%s%s\nThe Smart Node could not automatically change networks for you, so you will have to run the steps manually. Please follow the steps laid out in the Node Operator's guide (https://docs.rocketpool.net/node-staking/mainnet.html).\n", colorRed, err.Error(), colorReset)
}
return nil
}
// Query for service start if this is a new installation
if isNew {
if !prompt.Confirm("Would you like to start the Smart Node services automatically now?") {
fmt.Println("Please run `rocketpool service start` when you are ready to launch.")
return nil
}
return startService(c, true)
}
// Query for service start if this is old and there are containers to change
if len(md.ContainersToRestart) > 0 {
fmt.Println("The following containers must be restarted for the changes to take effect:")
for _, container := range md.ContainersToRestart {
fmt.Printf("\t%s_%s\n", prefix, container)
}
if !prompt.Confirm("Would you like to restart them automatically now?") {
fmt.Println("Please run `rocketpool service start` when you are ready to apply the changes.")
return nil
}
// Let's reduce potential downtime by pulling the new containers before restarting
fmt.Println("Pulling potential new container images...")
err = rp.PullComposeImages(getComposeFiles(c))
if err != nil {
fmt.Fprintf(os.Stderr, "Warning: couldn't pull new images for updated containers: %s\n", err.Error())
}
fmt.Println()
for _, container := range md.ContainersToRestart {
fullName := fmt.Sprintf("%s_%s", prefix, container)
fmt.Printf("Stopping %s... ", fullName)
rp.StopContainer(fullName)
fmt.Print("done!\n")
}
fmt.Println()
fmt.Println("Applying changes and restarting containers...")
return startService(c, true)
}
} else {
fmt.Println("Your changes have not been saved. Your Smart Node configuration is the same as it was before.")
return nil
}
return err
}
// Updates a configuration from the provided CLI arguments headlessly
func configureHeadless(c *cli.Context, cfg *config.RocketPoolConfig) error {
// Root params
for _, param := range cfg.GetParameters() {
err := updateConfigParamFromCliArg(c, "", param, cfg)
if err != nil {
return err
}
}
// Subconfigs
for sectionName, subconfig := range cfg.GetSubconfigs() {
for _, param := range subconfig.GetParameters() {
err := updateConfigParamFromCliArg(c, sectionName, param, cfg)
if err != nil {
return err
}
}
}
return nil
}
// Updates a config parameter from a CLI flag
func updateConfigParamFromCliArg(c *cli.Context, sectionName string, param *cfgtypes.Parameter, cfg *config.RocketPoolConfig) error {
var paramName string
if sectionName == "" {
paramName = param.ID
} else {
paramName = fmt.Sprintf("%s-%s", sectionName, param.ID)
}
if c.IsSet(paramName) {
switch param.Type {
case cfgtypes.ParameterType_Bool:
param.Value = c.Bool(paramName)
case cfgtypes.ParameterType_Int:
param.Value = c.Int(paramName)
case cfgtypes.ParameterType_Float:
param.Value = c.Float64(paramName)
case cfgtypes.ParameterType_String:
setting := c.String(paramName)
if param.MaxLength > 0 && len(setting) > param.MaxLength {
return fmt.Errorf("error setting value for %s: [%s] is too long (max length %d)", paramName, setting, param.MaxLength)
}
param.Value = c.String(paramName)
case cfgtypes.ParameterType_Uint:
param.Value = c.Uint(paramName)
case cfgtypes.ParameterType_Uint16:
param.Value = uint16(c.Uint(paramName))
case cfgtypes.ParameterType_Choice:
selection := c.String(paramName)
found := false
for _, option := range param.Options {
if fmt.Sprint(option.Value) == selection {
param.Value = option.Value
found = true
break
}
}
if !found {
return fmt.Errorf("error setting value for %s: [%s] is not one of the valid options", paramName, selection)
}
}
}
return nil
}
// Handle a network change by terminating the service, deleting everything, and starting over
func changeNetworks(c *cli.Context, rp *rocketpool.Client, apiContainerName string) error {
// Stop all of the containers
fmt.Println("Stopping containers... ")
err := rp.PauseService(getComposeFiles(c))
if err != nil {
return fmt.Errorf("error stopping service: %w", err)
}
fmt.Println("done")
// Restart the API container
fmt.Println("Starting API container... ")
output, err := rp.StartContainer(apiContainerName)
if err != nil {
return fmt.Errorf("error starting API container: %w", err)
}
if output != apiContainerName {
return fmt.Errorf("starting API container had unexpected output: %s", output)
}
fmt.Println("done")
// Get the path of the user's data folder
fmt.Println("Retrieving data folder path... ")
volumePath, err := rp.GetClientVolumeSource(apiContainerName, dataFolderVolumeName)
if err != nil {
return fmt.Errorf("error getting data folder path: %w", err)
}
fmt.Printf("done, data folder = %s\n", volumePath)
// Delete the data folder
fmt.Println("Removing data folder... ")
_, err = rp.TerminateDataFolder()
if err != nil {
return err
}
fmt.Println("done")
// Terminate the current setup
fmt.Println("Removing old installation... ")
err = rp.StopService(getComposeFiles(c))
if err != nil {
return fmt.Errorf("error terminating old installation: %w", err)
}
fmt.Println("done")
// Create new validator folder
fmt.Println("Recreating data folder... ")
err = os.MkdirAll(filepath.Join(volumePath, "validators"), 0775)
if err != nil {
return fmt.Errorf("error recreating data folder: %w", err)
}
// Start the service
fmt.Println("Starting Rocket Pool... ")
err = rp.StartService(getComposeFiles(c))
if err != nil {
return fmt.Errorf("error starting service: %w", err)
}
fmt.Println("done")
return nil
}
// Start the Rocket Pool service
func startService(c *cli.Context, ignoreConfigSuggestion bool) error {
// Get RP client
rp := rocketpool.NewClientFromCtx(c)
defer rp.Close()
// Update the Prometheus template with the assigned ports
cfg, isNew, err := rp.LoadConfig()
if err != nil {
return fmt.Errorf("Error loading user settings: %w", err)
}
// Force all Docker or all Hybrid
if cfg.ExecutionClientMode.Value.(cfgtypes.Mode) == cfgtypes.Mode_Local && cfg.ConsensusClientMode.Value.(cfgtypes.Mode) == cfgtypes.Mode_External {
fmt.Printf("%sYou are using a locally-managed Execution client and an externally-managed Consensus client.\nThis configuration is not compatible with The Merge; please select either locally-managed or externally-managed for both the EC and CC.%s\n", colorRed, colorReset)
} else if cfg.ExecutionClientMode.Value.(cfgtypes.Mode) == cfgtypes.Mode_External && cfg.ConsensusClientMode.Value.(cfgtypes.Mode) == cfgtypes.Mode_Local {
fmt.Printf("%sYou are using an externally-managed Execution client and a locally-managed Consensus client.\nThis configuration is not compatible with The Merge; please select either locally-managed or externally-managed for both the EC and CC.%s\n", colorRed, colorReset)
}
if isNew {
return fmt.Errorf("No configuration detected. Please run `rocketpool service config` to set up your Smart Node before running it.")
}
// Check if this is a new install
isUpdate, err := rp.IsFirstRun()
if err != nil {
return fmt.Errorf("error checking for first-run status: %w", err)
}
if isUpdate && !ignoreConfigSuggestion {
if c.Bool("yes") || prompt.Confirm("Smart Node upgrade detected - starting will overwrite certain settings with the latest defaults (such as container versions).\nYou may want to run `service config` first to see what's changed.\n\nWould you like to continue starting the service?") {
err = cfg.UpdateDefaults()
if err != nil {
return fmt.Errorf("error upgrading configuration with the latest parameters: %w", err)
}
rp.SaveConfig(cfg)
fmt.Printf("%sUpdated settings successfully.%s\n", colorGreen, colorReset)
} else {
fmt.Println("Cancelled.")
return nil
}
}
// Update the Prometheus template with the assigned ports
metricsEnabled := cfg.EnableMetrics.Value.(bool)
if metricsEnabled {
err := rp.UpdatePrometheusConfiguration(cfg)
if err != nil {
return err
}
}
// Update the Alertmanager configuration files even if metrics is disabled; as smartnode sends some alerts directly
alertingEnabled := cfg.Alertmanager.EnableAlerting.Value.(bool)
if alertingEnabled {
err = cfg.Alertmanager.UpdateConfigurationFiles(rp.ConfigPath())
if err != nil {
return err
}
}
// Validate the config
errors := cfg.Validate()
if len(errors) > 0 {
fmt.Printf("%sYour configuration encountered errors. You must correct the following in order to start Rocket Pool:\n\n", colorRed)
for _, err := range errors {
fmt.Printf("%s\n\n", err)
}
fmt.Println(colorReset)
return nil
}
if !c.Bool("ignore-slash-timer") {
// Do the client swap check
err := checkForValidatorChange(rp, cfg)
if err != nil {
fmt.Printf("%sWARNING: couldn't verify that the validator container can be safely restarted:\n\t%s\n", colorYellow, err.Error())
fmt.Println("If you are changing to a different ETH2 client, it may resubmit an attestation you have already submitted.")
fmt.Println("This will slash your validator!")
fmt.Println("To prevent slashing, you must wait 15 minutes from the time you stopped the clients before starting them again.")
fmt.Println()
fmt.Println("**If you did NOT change clients, you can safely ignore this warning.**")
fmt.Println()
if !prompt.Confirm(fmt.Sprintf("Press y when you understand the above warning, have waited, and are ready to start Rocket Pool:%s", colorReset)) {
fmt.Println("Cancelled.")
return nil
}
}
} else {
fmt.Printf("%sIgnoring anti-slashing safety delay.%s\n", colorYellow, colorReset)
}
// Write a note on doppelganger protection
doppelgangerEnabled, err := cfg.IsDoppelgangerEnabled()
if err != nil {
fmt.Printf("%sCouldn't check if you have Doppelganger Protection enabled: %s\nIf you do, your validator will miss up to 3 attestations when it starts.\nThis is *intentional* and does not indicate a problem with your node.%s\n\n", colorYellow, err.Error(), colorReset)
} else if doppelgangerEnabled {
fmt.Printf("%sNOTE: You currently have Doppelganger Protection enabled.\nYour validator will miss up to 3 attestations when it starts.\nThis is *intentional* and does not indicate a problem with your node.%s\n\n", colorYellow, colorReset)
}
// Start service
err = rp.StartService(getComposeFiles(c))
if err != nil {
return err
}
// Remove the upgrade flag if it's there
return rp.RemoveUpgradeFlagFile()
}
func checkForValidatorChange(rp *rocketpool.Client, cfg *config.RocketPoolConfig) error {
// Get the container prefix
prefix, err := rp.GetContainerPrefix()
if err != nil {
return fmt.Errorf("Error getting validator container prefix: %w", err)
}
// Get the current validator client
currentValidatorImageString, err := rp.GetDockerImage(prefix + ValidatorContainerSuffix)
if err != nil {
return fmt.Errorf("Error getting current validator image: %w", err)
}
currentValidatorName, err := getDockerImageName(currentValidatorImageString)
if err != nil {
return fmt.Errorf("Error getting current validator image name: %w", err)
}
// Get the new validator client according to the settings file
selectedConsensusClientConfig, err := cfg.GetSelectedConsensusClientConfig()
if err != nil {
return fmt.Errorf("Error getting selected consensus client config: %w", err)
}
pendingValidatorName, err := getDockerImageName(selectedConsensusClientConfig.GetValidatorImage())
if err != nil {
return fmt.Errorf("Error getting pending validator image name: %w", err)
}
// Compare the clients and warn if necessary
if currentValidatorName == pendingValidatorName {
fmt.Printf("Validator client [%s] was previously used - no slashing prevention delay necessary.\n", currentValidatorName)
} else if currentValidatorName == "" {
fmt.Println("This is the first time starting Rocket Pool - no slashing prevention delay necessary.")
} else {
consensusClient, _ := cfg.GetSelectedConsensusClient()
// Warn about Lodestar
if consensusClient == cfgtypes.ConsensusClient_Lodestar {
fmt.Printf("%sNOTE:\nIf this is your first time running Lodestar and you have existing minipools, you must run `rocketpool wallet rebuild` after the Smart Node starts to generate the validator keys for it.\nIf you have run it before or you don't have any minipools, you can ignore this message.%s\n\n", colorYellow, colorReset)
}
// Get the time that the container responsible for validator duties exited
validatorDutyContainerName, err := getContainerNameForValidatorDuties(currentValidatorName, rp)
if err != nil {
return fmt.Errorf("Error getting validator container name: %w", err)
}
validatorFinishTime, err := rp.GetDockerContainerShutdownTime(validatorDutyContainerName)
if err != nil {
return fmt.Errorf("Error getting validator shutdown time: %w", err)
}
// If it hasn't exited yet, shut it down
zeroTime := time.Time{}
status, err := rp.GetDockerStatus(validatorDutyContainerName)
if err != nil {
return fmt.Errorf("Error getting container [%s] status: %w", validatorDutyContainerName, err)
}
if validatorFinishTime == zeroTime || status == "running" {
fmt.Printf("%sValidator is currently running, stopping it...%s\n", colorYellow, colorReset)
response, err := rp.StopContainer(validatorDutyContainerName)
validatorFinishTime = time.Now()
if err != nil {
return fmt.Errorf("Error stopping container [%s]: %w", validatorDutyContainerName, err)
}
if response != validatorDutyContainerName {
return fmt.Errorf("Unexpected response when stopping container [%s]: %s", validatorDutyContainerName, response)
}
}
// Print the warning and start the time lockout
safeStartTime := validatorFinishTime.Add(15 * time.Minute)
remainingTime := time.Until(safeStartTime)
if remainingTime <= 0 {
fmt.Printf("The validator has been offline for %s, which is long enough to prevent slashing.\n", time.Since(validatorFinishTime))
fmt.Println("The new client can be safely started.")
} else {
fmt.Printf("%s=== WARNING ===\n", colorRed)
fmt.Printf("You have changed your validator client from %s to %s. Only %s has elapsed since you stopped %s.\n", currentValidatorName, pendingValidatorName, time.Since(validatorFinishTime), currentValidatorName)
fmt.Printf("If you were actively validating while using %s, starting %s without waiting will cause your validators to be slashed due to duplicate attestations!", currentValidatorName, pendingValidatorName)
fmt.Println("To prevent slashing, Rocket Pool will delay activating the new client for 15 minutes.")
fmt.Println("See the documentation for a more detailed explanation: https://docs.rocketpool.net/node-staking/maintenance/node-migration.html#slashing-and-the-slashing-database")
fmt.Printf("If you have read the documentation, understand the risks, and want to bypass this cooldown, run `rocketpool service start --ignore-slash-timer`.%s\n\n", colorReset)
// Wait for 15 minutes
for remainingTime > 0 {
fmt.Printf("Remaining time: %s", remainingTime)
time.Sleep(1 * time.Second)
remainingTime = time.Until(safeStartTime)
fmt.Printf("%s\r", clearLine)
}
fmt.Println(colorReset)
fmt.Println("You may now safely start the validator without fear of being slashed.")
}
}
return nil
}
// Get the name of the container responsible for validator duties based on the client name
func getContainerNameForValidatorDuties(CurrentValidatorClientName string, rp *rocketpool.Client) (string, error) {
prefix, err := rp.GetContainerPrefix()
if err != nil {
return "", err
}
return prefix + ValidatorContainerSuffix, nil
}
// Get the time that the container responsible for validator duties exited
func getValidatorFinishTime(CurrentValidatorClientName string, rp *rocketpool.Client) (time.Time, error) {
prefix, err := rp.GetContainerPrefix()
if err != nil {
return time.Time{}, err
}
var validatorFinishTime time.Time
if CurrentValidatorClientName == "nimbus" {
validatorFinishTime, err = rp.GetDockerContainerShutdownTime(prefix + BeaconContainerSuffix)
} else {
validatorFinishTime, err = rp.GetDockerContainerShutdownTime(prefix + ValidatorContainerSuffix)
}
return validatorFinishTime, err
}
// Extract the image name from a Docker image string
func getDockerImageName(imageString string) (string, error) {
// Return the empty string if the validator didn't exist (probably because this is the first time starting it up)
if imageString == "" {
return "", nil
}
reg := regexp.MustCompile(dockerImageRegex)
matches := reg.FindStringSubmatch(imageString)
if matches == nil {
return "", fmt.Errorf("Couldn't parse the Docker image string [%s]", imageString)
}
imageIndex := reg.SubexpIndex("image")
if imageIndex == -1 {
return "", fmt.Errorf("Image name not found in Docker image [%s]", imageString)
}
imageName := matches[imageIndex]
return imageName, nil
}
// Prepares the execution client for pruning
func pruneExecutionClient(c *cli.Context) error {
// Get RP client
rp := rocketpool.NewClientFromCtx(c)
defer rp.Close()
// Get the config
cfg, isNew, err := rp.LoadConfig()
if err != nil {
return err
}
if isNew {
return fmt.Errorf("Settings file not found. Please run `rocketpool service config` to set up your Smart Node.")
}
// Sanity checks
if cfg.ExecutionClientMode.Value.(cfgtypes.Mode) == cfgtypes.Mode_External {
fmt.Println("You are using an externally managed Execution client.\nThe Smart Node cannot prune it for you.")
return nil
}
if cfg.IsNativeMode {
fmt.Println("You are using Native Mode.\nThe Smart Node cannot prune your Execution client for you, you'll have to do it manually.")
}
selectedEc := cfg.ExecutionClient.Value.(cfgtypes.ExecutionClient)
// Don't prune if the EC is in archive mode
if cfg.ExecutionCommon.PruningMode.Value == cfgtypes.PruningMode_Archive {
fmt.Println("Your Execution Client is being used as an archive node.\nArchive nodes should not be pruned. Aborting.")
return nil
}
// Print the appropriate warnings before pruning
if selectedEc == cfgtypes.ExecutionClient_Geth {
fmt.Printf("%sGeth has a new feature that renders pruning obsolete. However, as this is a new feature you may have to resync with `rocketpool service resync-eth1` before this takes effect.%s\n", colorYellow, colorReset)
fmt.Println("This will shut down your main execution client and prune its database, freeing up disk space.")
if cfg.UseFallbackClients.Value == false {
fmt.Printf("%sYou do not have a fallback execution client configured.\nYour node will no longer be able to perform any validation duties (attesting or proposing blocks) until pruning is done.\nPlease configure a fallback client with `rocketpool service config` before running this.%s\n", colorRed, colorReset)
} else {
fmt.Println("You have fallback clients enabled. Rocket Pool (and your consensus client) will use that while the main client is pruning.")
}
fmt.Println("Once pruning is complete, your execution client will restart automatically.")
} else {
fmt.Println("This will request your main execution client to prune its database, freeing up disk space. This is a resource intensive operation and may lead to an increase in missed attestations until it finishes.")
}
fmt.Println()
// Get the container prefix
prefix, err := rp.GetContainerPrefix()
if err != nil {
return fmt.Errorf("Error getting container prefix: %w", err)
}
// Prompt for confirmation
if !(c.Bool("yes") || prompt.Confirm("Are you sure you want to prune your main execution client?")) {
fmt.Println("Cancelled.")
return nil
}
// Get the execution container name
executionContainerName := prefix + ExecutionContainerSuffix
// Check for enough free space
volumePath, err := rp.GetClientVolumeSource(executionContainerName, clientDataVolumeName)
if err != nil {
return fmt.Errorf("Error getting execution volume source path: %w", err)
}
partitions, err := disk.Partitions(true)
if err != nil {
return fmt.Errorf("Error getting partition list: %w", err)
}
longestPath := 0
bestPartition := disk.PartitionStat{}
for _, partition := range partitions {
if strings.HasPrefix(volumePath, partition.Mountpoint) && len(partition.Mountpoint) > longestPath {
bestPartition = partition
longestPath = len(partition.Mountpoint)
}
}
diskUsage, err := disk.Usage(bestPartition.Mountpoint)
if err != nil {
return fmt.Errorf("Error getting free disk space available: %w", err)
}
freeSpaceHuman := humanize.IBytes(diskUsage.Free)
pruneFreeSpaceRequired := PruneFreeSpaceRequired
if cfg.GetNetwork() == cfgtypes.Network_Mainnet && selectedEc == cfgtypes.ExecutionClient_Nethermind {
pruneFreeSpaceRequired = NethermindPruneFreeSpaceRequired
}
if diskUsage.Free < pruneFreeSpaceRequired {
return fmt.Errorf("%sYour disk must have %s GiB free to prune, but it only has %s free. Please free some space before pruning.%s", colorRed, humanize.IBytes(pruneFreeSpaceRequired), freeSpaceHuman, colorReset)
}
fmt.Printf("Your disk has %s free, which is enough to prune.\n", freeSpaceHuman)
if selectedEc == cfgtypes.ExecutionClient_Nethermind {
// Restarting NM is not needed anymore
err = rp.RunNethermindPruneStarter(executionContainerName)
if err != nil {
return fmt.Errorf("Error starting Nethermind prune starter: %w", err)
}
return nil
}
fmt.Printf("Stopping %s...\n", executionContainerName)
result, err := rp.StopContainer(executionContainerName)
if err != nil {
return fmt.Errorf("Error stopping main execution container: %w", err)
}
if result != executionContainerName {
return fmt.Errorf("Unexpected output while stopping main execution container: %s", result)
}
// Get the ETH1 volume name
volume, err := rp.GetClientVolumeName(executionContainerName, clientDataVolumeName)
if err != nil {
return fmt.Errorf("Error getting execution client volume name: %w", err)
}
// Run the prune provisioner
fmt.Printf("Provisioning pruning on volume %s...\n", volume)
err = rp.RunPruneProvisioner(prefix+PruneProvisionerContainerSuffix, volume)
if err != nil {
return fmt.Errorf("Error running prune provisioner: %w", err)
}
// Restart ETH1
fmt.Printf("Restarting %s...\n", executionContainerName)
result, err = rp.StartContainer(executionContainerName)
if err != nil {
return fmt.Errorf("Error starting main execution client: %w", err)
}
if result != executionContainerName {
return fmt.Errorf("Unexpected output while starting main execution client: %s", result)
}
fmt.Println()
fmt.Println("Done! Your main execution client is now pruning. You can follow its progress with `rocketpool service logs eth1`.")
fmt.Println("Once it's done, it will restart automatically and resume normal operation.")
fmt.Println(colorYellow + "NOTE: While pruning, you **cannot** interrupt the client (e.g. by restarting) or you risk corrupting the database!\nYou must let it run to completion!" + colorReset)
return nil
}
// Stops Smart Node stack containers, prunes docker, and restarts the Smart Node stack.
func resetDocker(c *cli.Context) error {
fmt.Println("Once cleanup is complete, Rocket Pool will restart automatically.")
fmt.Println()
// Stop...
// NOTE: pauseService prompts for confirmation, so we don't need to do it here
confirmed, err := pauseService(c)
if err != nil {
return err
}
if !confirmed {
// if the user cancelled the pause, then we cancel the rest of the operation here:
return nil
}
// Prune images...
err = pruneDocker(c)
if err != nil {
return fmt.Errorf("error pruning Docker: %s", err)
}
// Restart...
// NOTE: startService does some other sanity checks and messages that we leverage here:
fmt.Println("Restarting Rocket Pool...")
err = startService(c, true)
if err != nil {
return fmt.Errorf("error starting Rocket Pool: %s", err)
}
return nil
}
func pruneDocker(c *cli.Context) error {
// Get RP client
rp := rocketpool.NewClientFromCtx(c)
defer rp.Close()
// NOTE: we deliberately avoid using `docker system prune -a` and delete all
// images manually so that we can preserve the current smartnode-stack
// images, _unless_ the user specified --all option
deleteAllImages := c.Bool("all")
if !deleteAllImages {
ourImages, err := rp.GetComposeImages(getComposeFiles(c))
if err != nil {
return fmt.Errorf("error getting compose images: %w", err)
}
ourImagesMap := make(map[string]struct{})
for _, image := range ourImages {
ourImagesMap[image] = struct{}{}
}
allImages, err := rp.GetAllDockerImages()
if err != nil {
return fmt.Errorf("error getting all docker images: %w", err)
}
fmt.Println("Deleting images not used by the Rocket Pool Smart Node...")
for _, image := range allImages {
if _, ok := ourImagesMap[image.TagString()]; !ok {
fmt.Printf("Deleting %s...\n", image.String())
_, err = rp.DeleteDockerImage(image.ID)
if err != nil {
// safe to ignore and print to user, since it may just be an image referenced by a running container that is managed outside of the smartnode's compose stack
fmt.Printf("Error deleting image %s: %s\n", image.String(), err.Error())
}
continue
}
fmt.Printf("Skipping image used by Smart Node stack: %s\n", image.String())
}
}
// now we can run docker system prune (potentially without --all) to remove
// all stopped containers and networks:
fmt.Println("Pruning Docker system...")
err := rp.DockerSystemPrune(deleteAllImages)
if err != nil {
return fmt.Errorf("error pruning Docker system: %w", err)
}
return nil
}
// Pause the Rocket Pool service. Returns whether the action proceeded (was confirmed by user and no error occurred before starting it)
func pauseService(c *cli.Context) (bool, error) {
// Get RP client
rp := rocketpool.NewClientFromCtx(c)
defer rp.Close()
// Get the config
cfg, _, err := rp.LoadConfig()
if err != nil {
return false, err
}
// Write a note on doppelganger protection
doppelgangerEnabled, err := cfg.IsDoppelgangerEnabled()
if err != nil {
fmt.Printf("%sCouldn't check if you have Doppelganger Protection enabled: %s\nIf you do, stopping your validator will cause it to miss up to 3 attestations when it next starts.\nThis is *intentional* and does not indicate a problem with your node.%s\n\n", colorYellow, err.Error(), colorReset)
} else if doppelgangerEnabled {
fmt.Printf("%sNOTE: You currently have Doppelganger Protection enabled.\nIf you stop your validator, it will miss up to 3 attestations when it next starts.\nThis is *intentional* and does not indicate a problem with your node.%s\n\n", colorYellow, colorReset)
}
// Prompt for confirmation
if !(c.Bool("yes") || prompt.Confirm("Are you sure you want to pause the Rocket Pool service? Any staking minipools will be penalized!")) {
fmt.Println("Cancelled.")
return false, nil
}
// Pause service
err = rp.PauseService(getComposeFiles(c))
return true, err