-
Notifications
You must be signed in to change notification settings - Fork 169
Expand file tree
/
Copy pathservice.go
More file actions
1634 lines (1397 loc) · 57 KB
/
service.go
File metadata and controls
1634 lines (1397 loc) · 57 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/v3"
"gopkg.in/yaml.v2"
"github.com/dustin/go-humanize"
"github.com/shirou/gopsutil/v3/disk"
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/color"
"github.com/rocket-pool/smartnode/shared/utils/cli/prompt"
)
// Settings
const (
ExporterContainerSuffix string = "_exporter"
ValidatorContainerSuffix string = "_validator"
BeaconContainerSuffix string = "_eth2"
ExecutionContainerSuffix string = "_eth1"
NodeContainerSuffix string = "_node"
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>.+):.*"
clearLine string = "\033[2K"
)
// Install the Rocket Pool service
func installService(yes, verbose, noDeps bool, path string) error {
dataPath := ""
// Prompt for confirmation
if prompt.Declined(yes,
"%s",
fmt.Sprintf("The Rocket Pool %s service will be installed.\n\n", shared.RocketPoolVersion())+
color.Green("If you're upgrading, your existing configuration will be backed up and preserved.\nAll of your previous settings will be migrated automatically.\n")+
"Are you sure you want to continue?",
) {
fmt.Println("Cancelled.")
return nil
}
// Get RP client
rp := rocketpool.NewClient()
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(verbose, noDeps, path, dataPath)
if err != nil {
return err
}
// Print success message & return
fmt.Println("")
fmt.Println("The Rocket Pool service was successfully installed!")
printPatchNotes()
// Reload the config after installation
_, isNew, err = rp.LoadConfig()
if err != nil {
return fmt.Errorf("error loading new configuration: %w", err)
}
// Report next steps
color.LightBluePrintln("=== Next Steps ===")
color.LightBluePrintln("Run 'rocketpool service config' to review the settings changes for this update, or to continue setting up your node.")
// Print the docker permissions notice
if isNew {
fmt.Println()
color.YellowPrintln("NOTE:")
color.YellowPrintln("Since this is your first time installing Rocket Pool, please start a new shell session by logging out and back in or restarting the machine.")
color.YellowPrintln("This is necessary for your user account to have permissions to use Docker.")
}
return nil
}
// Print the latest patch notes for this release
func printPatchNotes() {
fmt.Print(shared.Logo())
fmt.Println()
fmt.Println()
color.GreenPrintf("=== Smart Node v%s ===\n", shared.RocketPoolVersion())
fmt.Println()
fmt.Println("Changes you should be aware of before starting:")
fmt.Println()
}
// Install the OS update tracker for the metrics dashboard
func installUpdateTracker(yes, verbose bool) error {
// Prompt for confirmation
if prompt.Declined(yes,
"This will add the ability to display any available Operating System updates on the metrics dashboard. "+
"Are you sure you want to install the update tracker?") {
fmt.Println("Cancelled.")
return nil
}
// Get RP client
rp := rocketpool.NewClient()
defer rp.Close()
// Install service
err := rp.InstallUpdateTracker(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("")
color.YellowPrintln("NOTE:")
color.YellowPrintln("Please restart the Smart Node stack to enable update tracking on the metrics dashboard.")
fmt.Println("")
return nil
}
// View the Rocket Pool service status
func serviceStatus(composeFiles []string) error {
// Get RP client
rp := rocketpool.NewClient()
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(composeFiles)
}
func configureServicePrecheck() (isNew bool, cfg, oldCfg *config.RocketPoolConfig, err error) {
// Get RP client
rp := rocketpool.NewClient()
defer rp.Close()
// Load the config, checking to see if it's new (hasn't been installed before)
cfg, isNew, err = rp.LoadConfig()
if err != nil {
return false, nil, nil, fmt.Errorf("error loading user settings: %w", err)
}
// Check if this is a new install
isUpdate, err := rp.IsFirstRun()
if err != nil {
return false, nil, nil, 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 false, nil, nil, fmt.Errorf("error upgrading configuration with the latest parameters: %w", err)
}
}
cfg.ConfirmUpdateSuggestedSettings()
return isNew, cfg, oldCfg, nil
}
// This function is the exception to the rule-
// we pass cli.Context here and here only because
// otherwise it's very difficult to set config values by CLI flag.
func configureServiceHeadless(c *cli.Command) error {
// Get RP client
rp := rocketpool.NewClient()
defer rp.Close()
_, cfg, _, err := configureServicePrecheck()
if err != nil {
return err
}
// Root params
for _, param := range cfg.GetParameters() {
err := updateConfigParamFromCliArg(c, "", param, cfg)
if err != nil {
return fmt.Errorf("error updating config from provided arguments: %w", err)
}
}
// Subconfigs
for sectionName, subconfig := range cfg.GetSubconfigs() {
for _, param := range subconfig.GetParameters() {
err := updateConfigParamFromCliArg(c, sectionName, param, cfg)
if err != nil {
return fmt.Errorf("error updating config from provided arguments: %w", err)
}
}
}
return nil
}
// Configure the service
func configureService(configPath string, isNative, yes bool, composeFiles []string) error {
// Get RP client
rp := rocketpool.NewClient()
defer rp.Close()
isNew, cfg, oldCfg, err := configureServicePrecheck()
if err != nil {
return err
}
isUpdate := !isNew && oldCfg != nil
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)
}
color.YellowPrintln("WARNING: You have requested to change networks.")
fmt.Println()
color.YellowPrintln("All 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.")
fmt.Println()
color.YellowPrintln("Please confirm you have backed up everything you want to keep, because it will be deleted if you answer `y` to the prompt below.")
fmt.Println()
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(rp, fmt.Sprintf("%s%s", prefix, NodeContainerSuffix), composeFiles)
if err != nil {
color.RedPrintln(err.Error())
fmt.Println("The 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).")
}
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(startServiceParams{
yes: yes,
ignoreConfigSuggestion: true,
composeFiles: composeFiles,
})
}
// Warn if IPv6 is enabled but no public IPv6 address is available
if md.Config.IsIPv6Enabled() && md.Config.GetExternalIpv6() == "" {
color.YellowPrintln("Warning: IPv6 is enabled but no public IPv6 address was detected. Your node will not be reachable by IPv6 peers.")
fmt.Println()
}
// Handle IPv6 toggle: Docker does not allow changing `enable_ipv6` on an existing
// network, so we must tear down every container attached to the project network,
// remove the network itself, and let the service start recreate everything.
ipv6Changed := md.PreviousConfig != nil && md.PreviousConfig.IsIPv6Enabled() != md.Config.IsIPv6Enabled()
if ipv6Changed {
fmt.Println("The IPv6 setting has changed, which requires recreating the Docker network.")
fmt.Println("All Rocket Pool containers will be stopped, removed, and recreated. Chain data and wallet/validator keys will not be touched.")
if !yes && !prompt.Confirm("Would you like to proceed?") {
fmt.Println("Please run `rocketpool service start` when you are ready to apply the changes.")
return nil
}
if err := recreateDockerNetwork(rp, prefix); err != nil {
return fmt.Errorf("error recreating Docker network for IPv6 change: %w", err)
}
fmt.Println()
fmt.Println("Applying changes and starting containers...")
return startService(startServiceParams{
yes: yes,
ignoreConfigSuggestion: true,
composeFiles: composeFiles,
})
}
// 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(composeFiles)
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)
exists, err := rp.ContainerExists(fullName)
if err != nil {
return fmt.Errorf("error checking if container %s exists: %w", fullName, err)
}
if !exists {
fmt.Print("not found, skipping.\n")
continue
}
_, err = rp.StopContainer(fullName)
if err != nil {
return fmt.Errorf("error stopping container: %w", err)
}
fmt.Print("done!\n")
}
fmt.Println()
fmt.Println("Applying changes and restarting containers...")
return startService(startServiceParams{
yes: yes,
ignoreConfigSuggestion: true,
composeFiles: composeFiles,
})
}
} 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 config parameter from a CLI flag
func updateConfigParamFromCliArg(c *cli.Command, 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(rp *rocketpool.Client, nodeContainerName string, composeFiles []string) error {
// Stop all of the containers
fmt.Println("Stopping containers... ")
err := rp.PauseService(composeFiles)
if err != nil {
return fmt.Errorf("error stopping service: %w", err)
}
fmt.Println("done")
// Restart the Node container (it hosts the Smart Node HTTP API and mounts the data folder)
fmt.Println("Starting Node container... ")
output, err := rp.StartContainer(nodeContainerName)
if err != nil {
return fmt.Errorf("error starting Node container: %w", err)
}
if output != nodeContainerName {
return fmt.Errorf("starting Node 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(nodeContainerName, 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(composeFiles)
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(composeFiles)
if err != nil {
return fmt.Errorf("error starting service: %w", err)
}
fmt.Println("done")
return nil
}
// Stop and remove every container that belongs to the compose project, then remove
// the project's Docker network.
func recreateDockerNetwork(rp *rocketpool.Client, prefix string) error {
networkName := fmt.Sprintf("%s_net", prefix)
// Gather the full set of containers to tear down:
// - everything labelled as part of this compose project (catches containers that
// were detached from the network by a previous partial recreate and would
// otherwise survive with a stale network reference),
// - plus anything still attached to the network
toRemove := map[string]struct{}{}
projectContainers, err := rp.GetContainersByPrefix(prefix)
if err != nil {
return fmt.Errorf("error listing project containers for prefix %s: %w", prefix, err)
}
for _, container := range projectContainers {
if container.Names != "" {
toRemove[container.Names] = struct{}{}
}
}
netExists, err := rp.NetworkExists(networkName)
if err != nil {
return fmt.Errorf("error checking if network %s exists: %w", networkName, err)
}
if netExists {
attached, err := rp.GetContainersOnNetwork(networkName)
if err != nil {
return fmt.Errorf("error listing containers on network %s: %w", networkName, err)
}
for _, name := range attached {
toRemove[name] = struct{}{}
}
}
for container := range toRemove {
fmt.Printf("Stopping %s... ", container)
if _, err := rp.StopContainer(container); err != nil {
// Already-stopped containers still need to be removed, so log and continue.
fmt.Println()
color.YellowPrintf("WARNING: stopping %s failed: %s\n", container, err.Error())
} else {
fmt.Println("done!")
}
fmt.Printf("Removing %s... ", container)
if _, err := rp.RemoveContainer(container); err != nil {
fmt.Println()
return fmt.Errorf("error removing container %s: %w", container, err)
}
fmt.Println("done!")
}
if netExists {
fmt.Printf("Removing network %s... ", networkName)
if _, err := rp.RemoveNetwork(networkName); err != nil {
fmt.Println()
return fmt.Errorf("error removing network %s: %w", networkName, err)
}
fmt.Println("done!")
}
return nil
}
type startServiceParams struct {
yes bool // Whether to automatically confirm prompts
// N.B.: This should ALYWAYS be false unless --ignore-slash-timer is set!
ignoreSlashTimer bool // Whether to ignore the slash timer
ignoreConfigSuggestion bool // Whether to skip suggesting the user run config first
composeFiles []string // The compose files to start the service with
}
// Start the Rocket Pool service
func startService(params startServiceParams) error {
// Get RP client
rp := rocketpool.NewClient()
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 {
color.RedPrintln("You are using a locally-managed Execution client and an externally-managed Consensus client.")
color.RedPrintln("This configuration is not compatible with The Merge; please select either locally-managed or externally-managed for both the EC and CC.")
} else if cfg.ExecutionClientMode.Value.(cfgtypes.Mode) == cfgtypes.Mode_External && cfg.ConsensusClientMode.Value.(cfgtypes.Mode) == cfgtypes.Mode_Local {
color.RedPrintln("You are using an externally-managed Execution client and a locally-managed Consensus client.")
color.RedPrintln("This configuration is not compatible with The Merge; please select either locally-managed or externally-managed for both the EC and CC.")
}
if isNew {
return fmt.Errorf("No configuration detected. Please run `rocketpool service config` to set up your Smart Node before running it.")
}
// Warn if IPv6 is enabled but no public IPv6 address is available
if cfg.IsIPv6Enabled() && cfg.GetExternalIpv6() == "" {
color.YellowPrintln("Warning: IPv6 is enabled but no public IPv6 address was detected. Your node will not be reachable by IPv6 peers.")
fmt.Println()
}
// 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 && !params.ignoreConfigSuggestion {
if params.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)
}
err = rp.SaveConfig(cfg)
if err != nil {
return fmt.Errorf("error saving configuration: %w", err)
}
color.GreenPrintln("Updated settings successfully.")
} 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 {
color.RedPrintln("Your configuration encountered errors. You must correct the following in order to start Rocket Pool:")
fmt.Println()
for _, err := range errors {
color.RedPrintf("%s\n", err)
fmt.Println()
}
return nil
}
if !params.ignoreSlashTimer {
// Do the client swap check
err := checkForValidatorChange(rp, cfg)
if err != nil {
color.YellowPrintln("WARNING: couldn't verify that the validator container can be safely restarted:")
color.YellowPrintf("\t%s\n", err.Error())
color.YellowPrintln("If you are changing to a different ETH2 client, it may resubmit an attestation you have already submitted.")
color.YellowPrintln("This will slash your validator!")
color.YellowPrintln("To prevent slashing, you must wait 15 minutes from the time you stopped the clients before starting them again.")
fmt.Println()
color.YellowPrintln("**If you did NOT change clients, you can safely ignore this warning.**")
fmt.Println()
if !prompt.ConfirmYellow("Press y when you understand the above warning, have waited, and are ready to start Rocket Pool:") {
fmt.Println("Cancelled.")
return nil
}
}
} else {
color.YellowPrintln("Ignoring anti-slashing safety delay.")
}
// Detect drift between the saved IPv6 setting and the live Docker network.
prefix := cfg.Smartnode.ProjectName.Value.(string)
networkName := fmt.Sprintf("%s_net", prefix)
netExists, err := rp.NetworkExists(networkName)
if err != nil {
return fmt.Errorf("error checking if network %s exists: %w", networkName, err)
}
if netExists {
liveIPv6, err := rp.GetNetworkIPv6Enabled(networkName)
if err != nil {
return fmt.Errorf("error reading IPv6 setting from network %s: %w", networkName, err)
}
if liveIPv6 != cfg.IsIPv6Enabled() {
color.YellowPrintln("The IPv6 setting in your configuration does not match the live Docker network.")
fmt.Println("Recreating the Docker network to apply the change. All Rocket Pool containers will be stopped, removed, and recreated.")
fmt.Println("Chain data and wallet/validator keys live on named Docker volumes and will not be touched.")
if !params.yes && !prompt.Confirm("Proceed?") {
fmt.Println("Cancelled. The service cannot be started until the Docker network is recreated.")
return nil
}
if err := recreateDockerNetwork(rp, prefix); err != nil {
return fmt.Errorf("error recreating Docker network for IPv6 change: %w", err)
}
fmt.Println()
}
}
// Write a note on doppelganger protection
doppelgangerEnabled, err := cfg.IsDoppelgangerEnabled()
if err != nil {
color.YellowPrintf("Couldn't check if you have Doppelganger Protection enabled: %s\n", err.Error())
color.YellowPrintln("If you do, your validator will miss up to 3 attestations when it starts.")
color.YellowPrintln("This is *intentional* and does not indicate a problem with your node.")
} else if doppelgangerEnabled {
color.YellowPrintln("NOTE: You currently have Doppelganger Protection enabled.")
color.YellowPrintln("Your validator will miss up to 3 attestations when it starts.")
color.YellowPrintln("This is *intentional* and does not indicate a problem with your node.")
}
fmt.Println()
// Start service
err = rp.StartService(params.composeFiles)
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
switch currentValidatorName {
case pendingValidatorName:
fmt.Printf("Validator client [%s] was previously used - no slashing prevention delay necessary.\n", currentValidatorName)
case "":
fmt.Println("This is the first time starting Rocket Pool - no slashing prevention delay necessary.")
default:
consensusClient, _ := cfg.GetSelectedConsensusClient()
// Warn about Lodestar
if consensusClient == cfgtypes.ConsensusClient_Lodestar {
color.YellowPrintln("NOTE:")
color.YellowPrintln("If 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.")
color.YellowPrintln("If you have run it before or you don't have any minipools, you can ignore this message.")
fmt.Println()
}
// 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.Equal(zeroTime) || status == "running" {
color.YellowPrintln("Validator is currently running, stopping it...")
exists, err := rp.ContainerExists(validatorDutyContainerName)
if err != nil {
return fmt.Errorf("Error checking if container [%s] exists: %w", validatorDutyContainerName, err)
}
if !exists {
color.YellowPrintf("Container [%s] does not exist, skipping stop.\n", validatorDutyContainerName)
} else {
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 {
color.RedPrintln("=== WARNING ===")
color.RedPrintf("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)
color.RedPrintf("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)
color.RedPrintln("To prevent slashing, Rocket Pool will delay activating the new client for 15 minutes.")
color.RedPrintln("See the documentation for a more detailed explanation: https://docs.rocketpool.net/node-staking/maintenance/node-migration.html#slashing-and-the-slashing-database")
color.RedPrintln("If you have read the documentation, understand the risks, and want to bypass this cooldown, run `rocketpool service start --ignore-slash-timer`.")
fmt.Println()
// 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("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
}
// 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(yes bool) error {
// Get RP client
rp := rocketpool.NewClient()
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 {
color.YellowPrintln("Geth 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.")
fmt.Println("This will shut down your main execution client and prune its database, freeing up disk space.")
if cfg.UseFallbackClients.Value == false {
color.RedPrintln("You do not have a fallback execution client configured.")
color.RedPrintln("Your node will no longer be able to perform any validation duties (attesting or proposing blocks) until pruning is done.")
color.RedPrintln("Please configure a fallback client with `rocketpool service config` before running this.")
} 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 prompt.Declined(yes, "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("Your disk must have %s GiB free to prune, but it only has %s free. Please free some space before pruning.", humanize.IBytes(pruneFreeSpaceRequired), freeSpaceHuman)
}
fmt.Printf("Your disk has %s free, which is enough to prune.\n", freeSpaceHuman)
if selectedEc == cfgtypes.ExecutionClient_Nethermind {