github.com/Axway/agent-sdk@v1.1.101/pkg/cmd/service/cmd.go (about) 1 package service 2 3 import ( 4 "fmt" 5 "os" 6 "strings" 7 8 corecmd "github.com/Axway/agent-sdk/pkg/cmd" 9 "github.com/spf13/cobra" 10 ) 11 12 var argDescriptions = map[string]string{ 13 "install": "install the service, add --user and --group flags if necessary", 14 "update": "update the service, add --user and --group flags if necessary", 15 "remove": "remove the installed service", 16 "start": "start the installed service", 17 "stop": "stop the installed service", 18 "status": "get the status of the installed service", 19 "logs": "get the logs of the service", 20 "enable": "enable the service to persist on reboots of the OS", 21 "name": "get the name of the service", 22 } 23 24 // GenServiceCmd - generates the command version for a Beat. 25 func GenServiceCmd(pathArg string) *cobra.Command { 26 // Create the validArgs array and the descriptions 27 longDesc := "" 28 validArgs := make([]string, 0, len(argDescriptions)) 29 for k := range argDescriptions { 30 validArgs = append(validArgs, k) 31 longDesc = fmt.Sprintf("%s\n%s\t\t%s", longDesc, k, argDescriptions[k]) 32 } 33 shortDesc := fmt.Sprintf("Manage the OS service (%s)", strings.Join(validArgs, ", ")) 34 longDesc = fmt.Sprintf("%s\n%s", shortDesc, longDesc) 35 36 cmd := &cobra.Command{ 37 Use: "service command [flags]", 38 Aliases: []string{"svc"}, 39 ValidArgs: validArgs, 40 Short: shortDesc, 41 Long: longDesc, 42 RunE: func(cmd *cobra.Command, args []string) error { 43 if globalAgentService == nil { 44 var err error 45 globalAgentService, err = newAgentService() 46 if err != nil { 47 return err 48 } 49 } 50 51 if len(args) != 1 { 52 fmt.Printf("must provide exactly 1 arg to service command (%s)\n", strings.Join(validArgs, ", ")) 53 return nil 54 } 55 if _, ok := argDescriptions[args[0]]; !ok { 56 fmt.Printf("invalid command to service (%s)\n", strings.Join(validArgs, ", ")) 57 return nil 58 } 59 globalAgentService.PathArg = fmt.Sprintf("--%s", pathArg) 60 globalAgentService.Path = cmd.Flag(pathArg).Value.String() 61 if pflag := cmd.Flag(corecmd.EnvFileFlag); pflag != nil { 62 globalAgentService.EnvFile = pflag.Value.String() 63 } 64 65 if globalAgentService.Path == "." || globalAgentService.Path == "" { 66 var err error 67 globalAgentService.Path, err = os.Getwd() 68 if err != nil { 69 fmt.Printf("error determining current working directory: %s\n", err.Error()) 70 return err 71 } 72 } 73 globalAgentService.User = cmd.Flag("user").Value.String() 74 globalAgentService.Group = cmd.Flag("group").Value.String() 75 76 return globalAgentService.HandleServiceFlag(args[0]) 77 }, 78 } 79 80 cmd.Flags().StringP("user", "u", "", "The OS user that will execute the service") 81 cmd.Flags().StringP("group", "g", "", "The OS group that will execute the service") 82 return cmd 83 }