go-api-pkg/consul/discovery.go

150 lines
3.7 KiB
Go
Raw Normal View History

2022-12-01 17:56:11 +01:00
package consul
import (
"fmt"
"log"
"net/http"
2022-12-01 19:05:59 +01:00
"strconv"
2022-12-01 17:56:11 +01:00
"time"
consul "github.com/hashicorp/consul/api"
)
type Service struct {
AppID string
Name string
2022-12-01 23:37:43 +01:00
Domain string
2022-12-01 17:56:11 +01:00
Address string
Port int
TTL time.Duration
ConsulAgent *consul.Agent
}
var ErrServiceUnavailable = fmt.Errorf("Service is unavailable")
2022-12-01 23:37:43 +01:00
func NewService(servAddr, id, name, hostname, domain string, appPort int) (*Service, error) {
2022-12-01 17:56:11 +01:00
s := new(Service)
2022-12-01 23:24:25 +01:00
s.AppID = id
2022-12-01 23:37:43 +01:00
s.Name = name
s.Address = hostname
s.Domain = domain
2022-12-01 17:56:11 +01:00
s.Port = appPort
s.TTL = time.Second * 15
2022-12-01 23:24:25 +01:00
client, err := consul.NewClient(newClientConfig(servAddr))
2022-12-01 17:56:11 +01:00
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
}
2022-12-01 18:54:19 +01:00
func (s *Service) GetID() string {
return fmt.Sprintf("%s_%s", s.Name, s.AppID)
}
2022-12-01 19:34:10 +01:00
func (s *Service) GetFullAddr() string {
2022-12-01 23:37:43 +01:00
return fmt.Sprintf("http://%s:%d/", s.Address, s.Port)
2022-12-01 19:34:10 +01:00
}
2022-12-01 17:56:11 +01:00
func (s *Service) Register() error {
def := &consul.AgentServiceRegistration{
2022-12-01 18:54:19 +01:00
ID: s.GetID(),
2022-12-01 19:45:47 +01:00
Name: s.Name,
2022-12-01 23:37:43 +01:00
Address: s.Address,
2022-12-01 17:56:11 +01:00
Port: s.Port,
Tags: s.getTags(),
2022-12-02 01:20:55 +01:00
// Meta: s.getMetadata(),
2022-12-01 17:56:11 +01:00
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 18:54:19 +01:00
return s.ConsulAgent.ServiceDeregister(s.GetID())
2022-12-01 17:56:11 +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 18:54:19 +01:00
if err := s.ConsulAgent.FailTTL("service:"+s.GetID(), err.Error()); err != nil {
2022-12-01 17:56:11 +01:00
log.Println(err)
2022-12-01 23:12:53 +01:00
fmt.Println(err)
2022-12-01 17:56:11 +01:00
}
} else {
2022-12-01 18:54:19 +01:00
if err := s.ConsulAgent.PassTTL("service:"+s.GetID(), "OK"); err != nil {
2022-12-01 17:56:11 +01:00
log.Println(err)
2022-12-01 23:12:53 +01:00
fmt.Println(err)
2022-12-01 17:56:11 +01:00
}
}
}
}
func (s *Service) check() (bool, error) {
client := &http.Client{}
2022-12-01 23:12:53 +01:00
healthUrl := fmt.Sprintf("%shealth", s.GetFullAddr())
fmt.Println("HCheck: " + healthUrl)
2022-12-01 17:56:11 +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
}
2022-12-01 19:34:10 +01:00
func (s *Service) getMetadata() map[string]string {
m := map[string]string{}
2022-12-01 20:19:28 +01:00
2022-12-01 19:34:10 +01:00
return m
}
2022-12-01 17:56:11 +01:00
func (s *Service) getTags() []string {
tags := []string{
"traefik.enable=true",
2022-12-01 23:37:43 +01:00
"traefik.http.routers." + s.Name + ".rule=Host(`" + s.Domain + "`)",
2022-12-01 17:56:11 +01:00
"traefik.http.routers." + s.Name + ".entryPoints=https",
2022-12-01 19:05:59 +01:00
"traefik.http.routers." + s.Name + ".tls=true",
"traefik.http.routers." + s.Name + ".service=" + s.Name,
"traefik.http.routers." + s.Name + ".middlewares=compress,requestid",
"traefik.http.services." + s.Name + ".loadbalancer.passhostheader=false",
"traefik.http.services." + s.Name + ".loadbalancer.server.scheme=http",
"traefik.http.services." + s.Name + ".loadbalancer.server.port=" + strconv.Itoa(s.Port),
"traefik.http.middlewares.compress.compress=true",
"traefik.http.middlewares.requestid.plugin.requestid.headerName=X-Request-ID",
2022-12-01 18:54:19 +01:00
// "traefik.http.services." + s.Name + ".loadbalancer.servers." + fullName + "=" + bFullAddr,
// "traefik.http.services." + s.Name + ".loadbalancer.servers." + fullName + ".url=" + bFullAddr,
2022-12-01 19:02:46 +01:00
// "traefik.http.services." + s.Name + ".loadbalancer.healthcheck.path=/health",
// "traefik.http.services." + s.Name + ".loadbalancer.healthcheck.interval=10s",
2022-12-01 17:56:11 +01:00
}
return tags
}