github.com/mutagen-io/mutagen@v0.18.0-rc1/cmd/mutagen/daemon/stop.go (about)

     1  package daemon
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  
     7  	"github.com/spf13/cobra"
     8  
     9  	"github.com/mutagen-io/mutagen/cmd"
    10  
    11  	"github.com/mutagen-io/mutagen/pkg/daemon"
    12  	daemonsvc "github.com/mutagen-io/mutagen/pkg/service/daemon"
    13  )
    14  
    15  // stopMain is the entry point for the stop command.
    16  func stopMain(_ *cobra.Command, _ []string) error {
    17  	// If the daemon is registered with the system, it may have a different stop
    18  	// mechanism, so see if the system should handle it.
    19  	if handled, err := daemon.RegisteredStop(); err != nil {
    20  		return fmt.Errorf("unable to stop daemon using system mechanism: %w", err)
    21  	} else if handled {
    22  		return nil
    23  	}
    24  
    25  	// Connect to the daemon and defer closure of the connection. We avoid
    26  	// version compatibility checks since they would remove the ability to
    27  	// terminate an incompatible daemon. This is fine since the daemon service
    28  	// portion of the daemon API is stable.
    29  	daemonConnection, err := Connect(false, false)
    30  	if err != nil {
    31  		return fmt.Errorf("unable to connect to daemon: %w", err)
    32  	}
    33  	defer daemonConnection.Close()
    34  
    35  	// Create a daemon service client.
    36  	daemonService := daemonsvc.NewDaemonClient(daemonConnection)
    37  
    38  	// Invoke shutdown. We don't check the response or error, because the daemon
    39  	// may terminate before it has a chance to send the response.
    40  	daemonService.Terminate(context.Background(), &daemonsvc.TerminateRequest{})
    41  
    42  	// Success.
    43  	return nil
    44  }
    45  
    46  // stopCommand is the stop command.
    47  var stopCommand = &cobra.Command{
    48  	Use:          "stop",
    49  	Short:        "Stop the Mutagen daemon if it's running",
    50  	Args:         cmd.DisallowArguments,
    51  	RunE:         stopMain,
    52  	SilenceUsage: true,
    53  }
    54  
    55  // stopConfiguration stores configuration for the stop command.
    56  var stopConfiguration struct {
    57  	// help indicates whether or not to show help information and exit.
    58  	help bool
    59  }
    60  
    61  func init() {
    62  	// Grab a handle for the command line flags.
    63  	flags := stopCommand.Flags()
    64  
    65  	// Disable alphabetical sorting of flags in help output.
    66  	flags.SortFlags = false
    67  
    68  	// Manually add a help flag to override the default message. Cobra will
    69  	// still implement its logic automatically.
    70  	flags.BoolVarP(&stopConfiguration.help, "help", "h", false, "Show help information")
    71  }