9 "github.com/hashicorp/consul/api"
12 type supervisor interface {
13 Running(ctx context.Context) (bool, error)
14 Start(ctx context.Context) error
17 func newSupervisor(ctx context.Context, name, cmd string, args ...string) supervisor {
18 if _, err := os.Stat("/run/systemd/system"); err == nil {
32 // supervised by systemd/runit/etc and registered with consul
33 type supervisedService struct {
34 name string // name to register with consul
35 cmd string // program to run (absolute path) -- if blank, use name
39 func (s *supervisedService) Boot(ctx context.Context) error {
44 if _, err := os.Stat(bin); err != nil {
47 sup := newSupervisor(ctx, s.name, bin, s.args...)
48 if ok, err := sup.Running(ctx); err != nil {
51 if err := sup.Start(ctx); err != nil {
55 if err := consul.Boot(ctx); err != nil {
58 consul, err := api.NewClient(consulCfg)
62 agent := consul.Agent()
63 svcs, err := agent.Services()
67 if svc, ok := svcs[s.name]; ok {
68 log.Printf("%s is registered: %#v", s.name, svc)
71 return agent.ServiceRegister(&api.AgentServiceRegistration{
74 Port: availablePort(),
78 func availablePort() int {
79 return rand.Intn(10000) + 20000