package consul import ( "fmt" "log" "net/http" "time" consul "github.com/hashicorp/consul/api" ) type Service struct { AppID string Name string Address string IP string Port int TTL time.Duration ConsulAgent *consul.Agent } var ErrServiceUnavailable = fmt.Errorf("Service is unavailable") func NewService(serverAddr, appID, appName, ip, domain string, appPort int) (*Service, error) { s := new(Service) s.AppID = appID s.Name = appName s.Address = domain s.IP = ip s.Port = appPort s.TTL = time.Second * 15 client, err := consul.NewClient(newClientConfig(serverAddr)) if err != nil { return nil, err } s.ConsulAgent = client.Agent() return s, nil } func newClientConfig(serverAddr string) *consul.Config { conf := consul.DefaultConfig() conf.Address = serverAddr return conf } func (s *Service) Register() error { def := &consul.AgentServiceRegistration{ ID: s.Name + "_" + s.AppID, Name: s.Name, Address: s.IP, Port: s.Port, Tags: s.getTags(), Check: &consul.AgentServiceCheck{ TTL: s.TTL.String(), }, } if err := s.ConsulAgent.ServiceRegister(def); err != nil { return err } go s.UpdateTTL(def) return nil } func (s *Service) Unregister() error { return s.ConsulAgent.ServiceDeregister(s.AppID) } func (s *Service) UpdateTTL(service *consul.AgentServiceRegistration) { ticker := time.NewTicker(s.TTL / 2) for range ticker.C { ok, err := s.check() if !ok { if err := s.ConsulAgent.FailTTL("service:"+s.Name+"_"+s.AppID, err.Error()); err != nil { log.Println(err) } } else { if err := s.ConsulAgent.PassTTL("service:"+s.AppID, "OK"); err != nil { log.Println(err) } } } } func (s *Service) check() (bool, error) { client := &http.Client{} healthUrl := fmt.Sprintf("http://%s:%d/health", s.IP, s.Port) req, err := http.NewRequest(http.MethodGet, healthUrl, nil) if err != nil { return false, ErrServiceUnavailable } req.Header.Set("User-Agent", "Health Check") resp, err := client.Do(req) if err != nil { return false, ErrServiceUnavailable } defer resp.Body.Close() if resp.StatusCode == http.StatusOK { return true, nil } return false, ErrServiceUnavailable } func (s *Service) getTags() []string { fullName := fmt.Sprintf("%s-%s", s.Name, s.AppID) bFullAddr := fmt.Sprintf("http://%s:%d/", s.IP, s.Port) // FIXME: declare one once - dont need to refresh.... tags := []string{ "traefik.enable=true", "traefik.http.routers." + s.Name + ".rule=Host(`" + s.Address + "`)", "traefik.http.routers." + s.Name + ".entryPoints=https", "traefik.http.routers." + s.Name + ".service=" + s.Name, "traefik.http.routers." + s.Name + ".middlewares=compress,requestid", "traefik.http.routers." + s.Name + ".tls=true", // "traefik.http.services." + s.Name + ".loadbalancer.server.scheme=http", // "traefik.http.services." + s.Name + ".loadbalancer.server.port=" + port, "traefik.http.services." + s.Name + ".loadbalancer.passhostheader=false", "traefik.http.services." + s.Name + ".loadbalancer.servers." + fullName + ".url=" + bFullAddr, "traefik.http.middlewares.compress.compress=true", "traefik.http.middlewares.requestid.plugin.requestid.headerName=X-Request-ID", // "traefik.http.services." + fullName + ".loadbalancer.healthcheck.path=/health", // "traefik.http.services." + fullName + ".loadbalancer.healthcheck.interval=10s", } return tags }