diff --git a/rocketpool-cli/service/commands.go b/rocketpool-cli/service/commands.go index 4ef8531558..2b97ee6404 100644 --- a/rocketpool-cli/service/commands.go +++ b/rocketpool-cli/service/commands.go @@ -235,7 +235,7 @@ func RegisterCommands(app *cli.Command, name string, aliases []string) { Name: "start", Aliases: []string{"s"}, Usage: "Start the Rocket Pool service", - UsageText: "rocketpool service start", + UsageText: "rocketpool service start [options] [services...]", Flags: []cli.Flag{ &cli.BoolFlag{ Name: "ignore-slash-timer", @@ -249,17 +249,13 @@ func RegisterCommands(app *cli.Command, name string, aliases []string) { }, Action: func(ctx context.Context, c *cli.Command) error { - // Validate args - if err := cliutils.ValidateArgCount(c, 0); err != nil { - return err - } - // Run command return startService(startServiceParams{ yes: c.Bool("yes"), ignoreSlashTimer: c.Bool("ignore-slash-timer"), ignoreConfigSuggestion: false, composeFiles: getComposeFiles(c), + serviceNames: resolveServiceNames(c.Args().Slice()), }) }, @@ -269,7 +265,7 @@ func RegisterCommands(app *cli.Command, name string, aliases []string) { Name: "stop", Aliases: []string{"pause", "p", "o"}, Usage: "Pause the Rocket Pool service", - UsageText: "rocketpool service stop [options]", + UsageText: "rocketpool service stop [options] [services...]", Flags: []cli.Flag{ &cli.BoolFlag{ Name: "yes", @@ -279,13 +275,8 @@ func RegisterCommands(app *cli.Command, name string, aliases []string) { }, Action: func(ctx context.Context, c *cli.Command) error { - // Validate args - if err := cliutils.ValidateArgCount(c, 0); err != nil { - return err - } - // Run command - _, err := pauseService(c.Bool("yes"), getComposeFiles(c)) + _, err := pauseService(c.Bool("yes"), getComposeFiles(c), resolveServiceNames(c.Args().Slice())...) return err }, diff --git a/rocketpool-cli/service/service.go b/rocketpool-cli/service/service.go index 7129129227..480d595545 100644 --- a/rocketpool-cli/service/service.go +++ b/rocketpool-cli/service/service.go @@ -4,6 +4,7 @@ import ( "fmt" "os" "path/filepath" + "slices" "strings" "time" @@ -658,6 +659,7 @@ type startServiceParams struct { 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 + serviceNames []string // The services to start; all of them if empty } // Start the Rocket Pool service @@ -667,6 +669,11 @@ func startService(params startServiceParams) error { rp := rocketpool.NewClient() defer rp.Close() + // A partial start (service names given) must only touch the named services, so it skips + // the steps below that act on the whole stack + partialStart := len(params.serviceNames) > 0 + includesValidator := startsValidator(params.serviceNames) + // Update the Prometheus template with the assigned ports cfg, isNew, err := rp.LoadConfig() if err != nil { @@ -700,7 +707,11 @@ func startService(params startServiceParams) error { if err != nil { return fmt.Errorf("error checking for first-run status: %w", err) } - if isUpdate && !params.ignoreConfigSuggestion { + if isUpdate && partialStart { + // Applying the new defaults (and clearing the upgrade flag) is left to a full start, so it still gets the upgrade prompt + color.YellowPrintln("Smart Node upgrade detected. The latest defaults (such as container versions) are only applied by a full `rocketpool service start`; starting the selected services with your current settings.") + fmt.Println() + } else 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 { @@ -747,10 +758,24 @@ func startService(params startServiceParams) error { return nil } + // Detect drift between the saved IPv6 setting and the live Docker network. + // Fixing it recreates every container, so a partial start bails out before anything is stopped. + prefix := cfg.Smartnode.ProjectName.Value.(string) + networkName := fmt.Sprintf("%s_net", prefix) + networkDrift, err := hasIPv6NetworkDrift(rp, networkName, cfg.IsIPv6Enabled()) + if err != nil { + return err + } + if networkDrift && partialStart { + return fmt.Errorf("The IPv6 setting in your configuration does not match the live Docker network.\nApplying it means recreating the network, which stops and recreates every Rocket Pool container, so it can't be done while starting only %s.\nPlease run `rocketpool service start` without service names to apply it.", strings.Join(params.serviceNames, ", ")) + } + if !cfg.HasRocketPoolContracts() { fmt.Println("Rocket Pool contracts are not configured. Starting configured services; validator and watchtower services are disabled.") - } else if !params.ignoreSlashTimer { - // Do the client swap check + } else if params.ignoreSlashTimer { + color.YellowPrintln("Ignoring anti-slashing safety delay.") + } else if includesValidator { + // Do the client swap check. It can stop the running validator, so it only runs when the validator is being started. err := checkForValidatorChange(rp, cfg) if err != nil { color.YellowPrintln("WARNING: couldn't verify that the validator container can be safely restarted:") @@ -766,61 +791,74 @@ func startService(params startServiceParams) error { 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) + // Apply a changed IPv6 setting by recreating the Docker network (full starts only, see above) + if networkDrift { + 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 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() + 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 cfg.HasRocketPoolContracts() && 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.") + if includesValidator { + 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 cfg.HasRocketPoolContracts() && 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() } - fmt.Println() // Start service - err = rp.StartService(params.composeFiles) + err = rp.StartService(params.composeFiles, params.serviceNames...) if err != nil { return err } - // Remove the upgrade flag if it's there + // Remove the upgrade flag if it's there; a partial start leaves it so the next full start still offers the upgrade prompt + if partialStart { + return nil + } return rp.RemoveUpgradeFlagFile() } +// Whether a start of the given services (all of them if none are given) starts the validator client +func startsValidator(serviceNames []string) bool { + return len(serviceNames) == 0 || slices.Contains(serviceNames, "validator") +} + +// Check whether the IPv6 setting of the live Docker network differs from the configured one. +// Returns false if the network doesn't exist yet. +func hasIPv6NetworkDrift(rp *rocketpool.Client, networkName string, configIPv6 bool) (bool, error) { + netExists, err := rp.NetworkExists(networkName) + if err != nil { + return false, fmt.Errorf("error checking if network %s exists: %w", networkName, err) + } + if !netExists { + return false, nil + } + liveIPv6, err := rp.GetNetworkIPv6Enabled(networkName) + if err != nil { + return false, fmt.Errorf("error reading IPv6 setting from network %s: %w", networkName, err) + } + return liveIPv6 != configIPv6, nil +} + func checkForValidatorChange(rp *rocketpool.Client, cfg *config.RocketPoolConfig) error { // Get the container prefix @@ -1353,8 +1391,8 @@ func pruneDocker(deleteAllImages bool, composeFiles []string) error { 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(yes bool, composeFiles []string) (bool, error) { +// Pause the Rocket Pool service, or only the given services if any are provided. Returns whether the action proceeded (was confirmed by user and no error occurred before starting it) +func pauseService(yes bool, composeFiles []string, serviceNames ...string) (bool, error) { // Get RP client rp := rocketpool.NewClient() @@ -1380,13 +1418,17 @@ func pauseService(yes bool, composeFiles []string) (bool, error) { fmt.Println() // Prompt for confirmation - if prompt.Declined(yes, "Are you sure you want to pause the Rocket Pool service? Any staking minipools and megapool validators will be penalized!") { + confirmText := "Are you sure you want to pause the Rocket Pool service? Any staking minipools and megapool validators will be penalized!" + if len(serviceNames) > 0 { + confirmText = fmt.Sprintf("Are you sure you want to pause %s? If this stops your Execution client, Consensus client or Validator client, any staking minipools and megapool validators will be penalized!", strings.Join(serviceNames, ", ")) + } + if prompt.Declined(yes, "%s", confirmText) { fmt.Println("Cancelled.") return false, nil } // Pause service - err = rp.PauseService(composeFiles) + err = rp.PauseService(composeFiles, serviceNames...) return true, err } @@ -1413,6 +1455,19 @@ func terminateService(yes bool, composeFiles []string, configPath string) error func serviceLogs(tail, since, until string, composeFiles []string, aliasedNames ...string) error { // Handle name aliasing + serviceNames := resolveServiceNames(aliasedNames) + + // Get RP client + rp := rocketpool.NewClient() + defer rp.Close() + + // Print service logs + return rp.PrintServiceLogs(composeFiles, tail, since, until, serviceNames...) + +} + +// Map the service name aliases accepted by the CLI (e.g. "ec", "cc", "vc") to their compose service names +func resolveServiceNames(aliasedNames []string) []string { serviceNames := []string{} for _, name := range aliasedNames { trueName := name @@ -1426,14 +1481,7 @@ func serviceLogs(tail, since, until string, composeFiles []string, aliasedNames } serviceNames = append(serviceNames, trueName) } - - // Get RP client - rp := rocketpool.NewClient() - defer rp.Close() - - // Print service logs - return rp.PrintServiceLogs(composeFiles, tail, since, until, serviceNames...) - + return serviceNames } // View the Rocket Pool service compose config diff --git a/rocketpool-cli/service/service_names_test.go b/rocketpool-cli/service/service_names_test.go new file mode 100644 index 0000000000..d42ede6f00 --- /dev/null +++ b/rocketpool-cli/service/service_names_test.go @@ -0,0 +1,48 @@ +package service + +import ( + "slices" + "testing" +) + +func TestResolveServiceNames(t *testing.T) { + for _, tc := range []struct { + name string + in []string + want []string + }{ + {"none", nil, []string{}}, + {"compose names unchanged", []string{"eth1", "eth2", "validator", "grafana"}, []string{"eth1", "eth2", "validator", "grafana"}}, + {"execution aliases", []string{"ec", "el", "execution"}, []string{"eth1", "eth1", "eth1"}}, + {"consensus aliases", []string{"cc", "cl", "bc", "bn", "beacon", "consensus"}, []string{"eth2", "eth2", "eth2", "eth2", "eth2", "eth2"}}, + {"validator alias", []string{"vc"}, []string{"validator"}}, + {"mixed", []string{"grafana", "cc", "prometheus"}, []string{"grafana", "eth2", "prometheus"}}, + } { + t.Run(tc.name, func(t *testing.T) { + if got := resolveServiceNames(tc.in); !slices.Equal(got, tc.want) { + t.Fatalf("got %q, want %q", got, tc.want) + } + }) + } +} + +func TestStartsValidator(t *testing.T) { + for _, tc := range []struct { + name string + in []string + want bool + }{ + {"full start", nil, true}, + {"full start, empty list", []string{}, true}, + {"grafana only", []string{"grafana"}, false}, + {"clients without validator", []string{"eth1", "eth2"}, false}, + {"validator", []string{"grafana", "validator"}, true}, + {"vc alias", resolveServiceNames([]string{"vc"}), true}, + } { + t.Run(tc.name, func(t *testing.T) { + if got := startsValidator(tc.in); got != tc.want { + t.Fatalf("got %v, want %v", got, tc.want) + } + }) + } +} diff --git a/shared/services/rocketpool/client.go b/shared/services/rocketpool/client.go index 5bbad499a9..ce87a52bcf 100644 --- a/shared/services/rocketpool/client.go +++ b/shared/services/rocketpool/client.go @@ -427,8 +427,8 @@ func (c *Client) InstallUpdateTracker(verbose bool) error { return c.runScript(assets.InstallUpdateTrackerScript(), verbose, nil) } -// Start the Rocket Pool service -func (c *Client) StartService(composeFiles []string) error { +// Start the Rocket Pool service, or only the given services if any are provided +func (c *Client) StartService(composeFiles []string, serviceNames ...string) error { cfg, isNew, err := c.LoadConfig() if err != nil { return err @@ -439,23 +439,41 @@ func (c *Client) StartService(composeFiles []string) error { } } - // Start all of the containers - cmd, err := c.compose(composeFiles, "up -d --remove-orphans --quiet-pull") + // Start the containers + cmd, err := c.compose(composeFiles, startArgs(serviceNames)) if err != nil { return err } return c.printOutput(cmd) } -// Pause the Rocket Pool service -func (c *Client) PauseService(composeFiles []string) error { - cmd, err := c.compose(composeFiles, "stop") +// Build the docker compose arguments for starting the given services (all of them if none are given). +// Removing orphaned containers acts on the whole project, so only a full start does it. +func startArgs(serviceNames []string) string { + if len(serviceNames) == 0 { + return "up -d --remove-orphans --quiet-pull" + } + return composeArgs("up -d --quiet-pull", serviceNames) +} + +// Pause the Rocket Pool service, or only the given services if any are provided +func (c *Client) PauseService(composeFiles []string, serviceNames ...string) error { + cmd, err := c.compose(composeFiles, composeArgs("stop", serviceNames)) if err != nil { return err } return c.printOutput(cmd) } +// Append the given service names to a docker compose subcommand +func composeArgs(command string, serviceNames []string) string { + parts := []string{command} + for _, serviceName := range serviceNames { + parts = append(parts, shellescape.Quote(serviceName)) + } + return strings.Join(parts, " ") +} + // Stop the Rocket Pool service func (c *Client) StopService(composeFiles []string) error { cmd, err := c.compose(composeFiles, "down -v") diff --git a/shared/services/rocketpool/service_start_stop_test.go b/shared/services/rocketpool/service_start_stop_test.go new file mode 100644 index 0000000000..5ea57783d2 --- /dev/null +++ b/shared/services/rocketpool/service_start_stop_test.go @@ -0,0 +1,41 @@ +package rocketpool + +import "testing" + +func TestComposeArgs(t *testing.T) { + for _, tc := range []struct { + name, command string + services []string + want string + }{ + {"stop all", "stop", nil, "stop"}, + {"stop empty list", "stop", []string{}, "stop"}, + {"stop several", "stop", []string{"grafana", "prometheus"}, "stop grafana prometheus"}, + {"name needs quotes", "stop", []string{"grafana; rm -rf /"}, "stop 'grafana; rm -rf /'"}, + } { + t.Run(tc.name, func(t *testing.T) { + if got := composeArgs(tc.command, tc.services); got != tc.want { + t.Fatalf("got %q, want %q", got, tc.want) + } + }) + } +} + +func TestStartArgs(t *testing.T) { + for _, tc := range []struct { + name string + services []string + want string + }{ + {"start all", nil, "up -d --remove-orphans --quiet-pull"}, + {"start all, empty list", []string{}, "up -d --remove-orphans --quiet-pull"}, + {"start one leaves orphans alone", []string{"grafana"}, "up -d --quiet-pull grafana"}, + {"start several", []string{"eth2", "validator"}, "up -d --quiet-pull eth2 validator"}, + } { + t.Run(tc.name, func(t *testing.T) { + if got := startArgs(tc.services); got != tc.want { + t.Fatalf("got %q, want %q", got, tc.want) + } + }) + } +}