go-api-pkg/consul/discovery.go
2023-06-28 22:59:31 +02:00

172 lines
4.5 KiB
Go

package consul
import (
"fmt"
"net/http"
"strconv"
"time"
"git.pbiernat.dev/egommerce/go-api-pkg/config"
consul "github.com/hashicorp/consul/api"
)
type Service struct {
Name string
Address string
appID string
domain string
pathPrefix string
port int
ttl time.Duration
agent *consul.Agent
kv *consul.KV
catalog *consul.Catalog
}
var ErrServiceUnavailable = fmt.Errorf("Service is unavailable")
func NewService(servAddr, id, name, hostname, domain, pathPrefix string, appPort int) (*Service, error) {
s := new(Service)
s.Name = name
s.Address = hostname
s.appID = id
s.domain = domain
s.pathPrefix = pathPrefix
s.port = appPort
s.ttl = time.Second * 15
client, err := consul.NewClient(newClientConfig(servAddr))
if err != nil {
return nil, err
}
s.agent = client.Agent()
s.kv = client.KV()
s.catalog = client.Catalog()
return s, nil
}
func newClientConfig(serverAddr string) *consul.Config {
conf := consul.DefaultConfig()
conf.Address = serverAddr
return conf
}
func (s *Service) GetID() string {
return fmt.Sprintf("%s:%s", s.Name, s.appID)
}
func (s *Service) GetFullAddr() string {
return fmt.Sprintf("http://%s:%d/", s.Address, s.port)
}
func (s *Service) Register() error {
def := &consul.AgentServiceRegistration{
ID: s.GetID(),
Name: s.Name,
Address: s.Address,
Port: s.port,
Tags: s.getTags(),
Check: &consul.AgentServiceCheck{
TTL: s.ttl.String(),
DeregisterCriticalServiceAfter: "5s",
},
}
if err := s.agent.ServiceRegister(def); err != nil {
return err
}
go func(s *Service) { // startup register
ticker := time.NewTicker(time.Millisecond * 100)
for range ticker.C {
if ok, _ := s.healthCheck(); ok {
ticker.Stop()
}
}
}(s)
go func(s *Service) { // TTL
interval := s.ttl - time.Second*2 // 2 seconds overhead
ticker := time.NewTicker(interval)
for range ticker.C {
if _, err := s.healthCheck(); err != nil {
fmt.Printf("TTL Error #: %v\n", err)
}
}
}(s)
return nil
}
func (s *Service) Unregister() error {
return s.agent.ServiceDeregister(s.GetID())
}
func (s *Service) KV() *consul.KV {
return s.kv
}
func (s *Service) Catalog() *consul.Catalog {
return s.catalog
}
func (s *Service) healthCheck() (bool, error) {
alive := func() bool {
client := &http.Client{}
healthUrl := s.GetFullAddr() + "health"
fmt.Printf("Sending request to the %s\n", healthUrl)
req, err := http.NewRequest(http.MethodGet, healthUrl, nil)
if err != nil {
fmt.Printf("Failed to create new Consul request: %v\n", err)
return false
}
req.Header.Set("User-Agent", "Health Check")
resp, err := client.Do(req)
if err != nil {
fmt.Printf("Failed to send Consul request: %v\n", err)
return false
}
defer resp.Body.Close()
return resp.StatusCode == http.StatusOK
}()
if alive {
if err := s.agent.PassTTL("service:"+s.GetID(), "OK"); err != nil {
return false, err
}
return true, nil
}
if err := s.agent.FailTTL("service:"+s.GetID(), ErrServiceUnavailable.Error()); err != nil {
return false, err
}
return false, ErrServiceUnavailable
}
func (s *Service) getTags() []string {
tags := []string{
"traefik.enable=true",
"traefik.http.routers." + s.Name + ".rule=PathPrefix(`" + s.pathPrefix + "`)",
"traefik.http.routers." + s.Name + ".entryPoints=https",
"traefik.http.routers." + s.Name + ".tls=true",
"traefik.http.routers." + s.Name + ".service=" + s.Name,
"traefik.http.routers." + s.Name + ".middlewares=auth_" + s.Name + ",requestid_" + s.Name + ",stripprefix_" + s.Name,
"traefik.http.services." + s.Name + ".loadbalancer.server.scheme=http",
"traefik.http.services." + s.Name + ".loadbalancer.server.port=" + strconv.Itoa(s.port),
"traefik.http.services." + s.Name + ".loadbalancer.passhostheader=false",
"traefik.http.middlewares.auth_" + s.Name + ".plugin.auth.handlerURL=" + config.GetEnv("AUTH_HANDLER_URL", ""),
// "traefik.http.middlewares.auth_" + s.Name + ".forwardauth.authRequestHeaders=Cookie",
// "traefik.http.middlewares.auth_" + s.Name + ".forwardauth.authResponseHeaders=Set-Cookie, Server",
// "traefik.http.middlewares.auth_" + s.Name + ".forwardauth.trustForwardHeader=true",
"traefik.http.middlewares.requestid_" + s.Name + ".plugin.requestid.headerName=X-Request-ID",
"traefik.http.middlewares.stripprefix_" + s.Name + ".stripprefix.prefixes=" + s.pathPrefix,
"traefik.tls.certificates.certfile=/certs/client.cert",
"traefik.tls.certificates.keyfile=/certs/client.key",
}
return tags
}