github.com/clly/consul@v1.4.5/command/services/deregister/deregister.go (about) 1 package deregister 2 3 import ( 4 "flag" 5 "fmt" 6 7 "github.com/hashicorp/consul/api" 8 "github.com/hashicorp/consul/command/flags" 9 "github.com/hashicorp/consul/command/services" 10 "github.com/mitchellh/cli" 11 ) 12 13 func New(ui cli.Ui) *cmd { 14 c := &cmd{UI: ui} 15 c.init() 16 return c 17 } 18 19 type cmd struct { 20 UI cli.Ui 21 flags *flag.FlagSet 22 http *flags.HTTPFlags 23 help string 24 flagId string 25 } 26 27 func (c *cmd) init() { 28 c.flags = flag.NewFlagSet("", flag.ContinueOnError) 29 c.flags.StringVar(&c.flagId, "id", "", 30 "ID to delete. This must not be set if arguments are given.") 31 32 c.http = &flags.HTTPFlags{} 33 flags.Merge(c.flags, c.http.ClientFlags()) 34 flags.Merge(c.flags, c.http.ServerFlags()) 35 c.help = flags.Usage(help, c.flags) 36 } 37 38 func (c *cmd) Run(args []string) int { 39 if err := c.flags.Parse(args); err != nil { 40 return 1 41 } 42 43 // Check for arg validation 44 args = c.flags.Args() 45 if len(args) == 0 && c.flagId == "" { 46 c.UI.Error("Service deregistration requires at least one argument or -id.") 47 return 1 48 } else if len(args) > 0 && c.flagId != "" { 49 c.UI.Error("Service deregistration requires arguments or -id, not both.") 50 return 1 51 } 52 53 svcs := []*api.AgentServiceRegistration{&api.AgentServiceRegistration{ 54 ID: c.flagId}} 55 if len(args) > 0 { 56 var err error 57 svcs, err = services.ServicesFromFiles(args) 58 if err != nil { 59 c.UI.Error(fmt.Sprintf("Error: %s", err)) 60 return 1 61 } 62 } 63 64 // Create and test the HTTP client 65 client, err := c.http.APIClient() 66 if err != nil { 67 c.UI.Error(fmt.Sprintf("Error connecting to Consul agent: %s", err)) 68 return 1 69 } 70 71 // Create all the services 72 for _, svc := range svcs { 73 id := svc.ID 74 if id == "" { 75 id = svc.Name 76 } 77 if id == "" { 78 continue 79 } 80 81 if err := client.Agent().ServiceDeregister(id); err != nil { 82 c.UI.Error(fmt.Sprintf("Error registering service %q: %s", 83 svc.Name, err)) 84 return 1 85 } 86 87 c.UI.Output(fmt.Sprintf("Deregistered service: %s", id)) 88 } 89 90 return 0 91 } 92 93 func (c *cmd) Synopsis() string { 94 return synopsis 95 } 96 97 func (c *cmd) Help() string { 98 return c.help 99 } 100 101 const synopsis = "Deregister services with the local agent" 102 const help = ` 103 Usage: consul services deregister [options] [FILE...] 104 105 Deregister one or more services that were previously registered with 106 the local agent. 107 108 $ consul services deregister web.json db.json 109 110 The -id flag may be used to deregister a single service by ID: 111 112 $ consul services deregister -id=web 113 114 Services are deregistered from the local agent catalog. This command must 115 be run against the same agent where the service was registered. 116 `