go-api-pkg/consul/discovery.go

133 lines
3.4 KiB
Go
Raw Normal View History

2022-12-01 04:05:41 +01:00
package consul
import (
"fmt"
"log"
"net/http"
"time"
consul "github.com/hashicorp/consul/api"
)
type Service struct {
2022-12-01 07:56:31 +01:00
AppID string
2022-12-01 04:05:41 +01:00
Name string
Address string
2022-12-01 07:56:31 +01:00
IP string
2022-12-01 04:05:41 +01:00
Port int
TTL time.Duration
ConsulAgent *consul.Agent
}
var ErrServiceUnavailable = fmt.Errorf("Service is unavailable")
2022-12-01 07:56:31 +01:00
func NewService(serverAddr, appID, appName, ip, domain string, appPort int) (*Service, error) {
2022-12-01 04:05:41 +01:00
s := new(Service)
2022-12-01 07:56:31 +01:00
s.AppID = appID
2022-12-01 04:05:41 +01:00
s.Name = appName
2022-12-01 07:56:31 +01:00
s.Address = domain
s.IP = ip
2022-12-01 04:05:41 +01:00
s.Port = appPort
2022-12-01 08:36:44 +01:00
s.TTL = time.Second * 15
2022-12-01 04:05:41 +01:00
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{
2022-12-01 17:15:21 +01:00
ID: s.Name + "_" + s.AppID,
2022-12-01 04:05:41 +01:00
Name: s.Name,
2022-12-01 07:56:31 +01:00
Address: s.IP,
2022-12-01 04:05:41 +01:00
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 {
2022-12-01 07:56:31 +01:00
return s.ConsulAgent.ServiceDeregister(s.AppID)
2022-12-01 04:05:41 +01:00
}
func (s *Service) UpdateTTL(service *consul.AgentServiceRegistration) {
ticker := time.NewTicker(s.TTL / 2)
for range ticker.C {
ok, err := s.check()
if !ok {
2022-12-01 17:15:21 +01:00
if err := s.ConsulAgent.FailTTL("service:"+s.Name+"_"+s.AppID, err.Error()); err != nil {
2022-12-01 04:05:41 +01:00
log.Println(err)
}
} else {
2022-12-01 09:08:41 +01:00
if err := s.ConsulAgent.PassTTL("service:"+s.AppID, "OK"); err != nil {
2022-12-01 04:05:41 +01:00
log.Println(err)
}
}
}
}
func (s *Service) check() (bool, error) {
client := &http.Client{}
2022-12-01 07:56:31 +01:00
healthUrl := fmt.Sprintf("http://%s:%d/health", s.IP, s.Port)
2022-12-01 04:05:41 +01:00
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 {
2022-12-01 10:28:17 +01:00
fullName := fmt.Sprintf("%s-%s", s.Name, s.AppID)
2022-12-01 09:45:23 +01:00
bFullAddr := fmt.Sprintf("http://%s:%d/", s.IP, s.Port) // FIXME: declare one once - dont need to refresh....
2022-12-01 04:05:41 +01:00
tags := []string{
"traefik.enable=true",
2022-12-01 07:56:31 +01:00
"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",
2022-12-01 17:07:30 +01:00
"traefik.http.services." + s.Name + ".loadbalancer.servers." + fullName + ".url=" + bFullAddr,
2022-12-01 04:05:41 +01:00
"traefik.http.middlewares.compress.compress=true",
"traefik.http.middlewares.requestid.plugin.requestid.headerName=X-Request-ID",
2022-12-01 07:56:31 +01:00
// "traefik.http.services." + fullName + ".loadbalancer.healthcheck.path=/health",
// "traefik.http.services." + fullName + ".loadbalancer.healthcheck.interval=10s",
2022-12-01 04:05:41 +01:00
}
return tags
}