go-api-pkg/consul/discovery.go

199 lines
5.3 KiB
Go
Raw Normal View History

2022-12-01 17:56:11 +01:00
package consul
import (
"fmt"
"net/http"
2022-12-01 19:05:59 +01:00
"strconv"
2022-12-01 17:56:11 +01:00
"time"
2023-06-21 20:45:46 +02:00
"git.pbiernat.dev/egommerce/go-api-pkg/config"
2022-12-01 17:56:11 +01:00
consul "github.com/hashicorp/consul/api"
2023-06-29 14:25:08 +02:00
"github.com/hashicorp/consul/connect"
2022-12-01 17:56:11 +01:00
)
type Service struct {
2022-12-24 17:10:47 +01:00
Name string
Address string
appID string
domain string
pathPrefix string
port int
ttl time.Duration
2023-06-29 14:25:08 +02:00
client *consul.Client
2022-12-24 17:10:47 +01:00
agent *consul.Agent
2023-06-29 14:34:25 +02:00
connect *connect.Service
2022-12-24 17:10:47 +01:00
kv *consul.KV
2022-12-01 17:56:11 +01:00
}
var ErrServiceUnavailable = fmt.Errorf("Service is unavailable")
2022-12-24 17:10:47 +01:00
func NewService(servAddr, id, name, hostname, domain, pathPrefix string, appPort int) (*Service, error) {
2022-12-01 17:56:11 +01:00
s := new(Service)
2022-12-01 23:37:43 +01:00
s.Name = name
s.Address = hostname
2022-12-05 19:23:32 +01:00
s.appID = id
s.domain = domain
2022-12-24 17:10:47 +01:00
s.pathPrefix = pathPrefix
2022-12-05 19:23:32 +01:00
s.port = appPort
2023-06-28 23:07:10 +02:00
s.ttl = time.Second * 10
2022-12-01 17:56:11 +01:00
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
}
2023-06-29 14:25:08 +02:00
s.client = client
2022-12-05 19:23:32 +01:00
s.agent = client.Agent()
s.kv = client.KV()
2022-12-01 17:56:11 +01:00
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 {
2023-06-28 16:37:18 +02:00
return fmt.Sprintf("%s:%s", s.Name, s.appID)
2022-12-01 18:54:19 +01:00
}
2022-12-01 19:34:10 +01:00
func (s *Service) GetFullAddr() string {
2023-07-02 22:38:13 +02:00
return fmt.Sprintf("http://%s:%d/", s.domain, 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{
2023-07-05 23:44:47 +02:00
ID: s.GetID(),
Kind: consul.ServiceKindConnectProxy,
2022-12-01 19:45:47 +01:00
Name: s.Name,
2022-12-01 23:37:43 +01:00
Address: s.Address,
2022-12-05 19:23:32 +01:00
Port: s.port,
2022-12-01 17:56:11 +01:00
Tags: s.getTags(),
2023-07-02 23:03:05 +02:00
Connect: &consul.AgentServiceConnect{
2023-07-05 22:45:12 +02:00
SidecarService: &consul.AgentServiceRegistration{
// Port: s.port,
},
2023-07-02 23:03:05 +02:00
},
2023-07-05 23:44:47 +02:00
Proxy: &consul.AgentServiceConnectProxyConfig{
DestinationServiceName: s.Name,
},
2022-12-01 17:56:11 +01:00
Check: &consul.AgentServiceCheck{
TTL: s.ttl.String(),
2023-06-30 13:04:53 +02:00
Status: "passing",
2023-06-28 23:07:10 +02:00
DeregisterCriticalServiceAfter: "10s",
2022-12-01 17:56:11 +01:00
},
}
2022-12-05 19:23:32 +01:00
if err := s.agent.ServiceRegister(def); err != nil {
2022-12-01 17:56:11 +01:00
return err
}
2022-12-02 03:22:36 +01:00
2022-12-05 21:20:38 +01:00
go func(s *Service) { // startup register
2023-06-28 23:07:10 +02:00
ticker := time.NewTicker(time.Second * 1)
2022-12-02 03:22:36 +01:00
for range ticker.C {
2023-04-07 10:09:10 +02:00
if ok, _ := s.healthCheck(); ok {
2022-12-02 03:22:36 +01:00
ticker.Stop()
}
}
2022-12-05 21:20:38 +01:00
}(s)
2022-12-02 03:22:36 +01:00
2023-06-28 23:34:45 +02:00
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)
2022-12-01 17:56:11 +01:00
return nil
}
func (s *Service) Unregister() error {
2022-12-05 19:23:32 +01:00
return s.agent.ServiceDeregister(s.GetID())
}
2023-06-29 14:25:08 +02:00
func (s *Service) Connect() (*connect.Service, error) {
2023-07-01 18:01:48 +02:00
// srvName := s.Name
2023-07-02 01:32:45 +02:00
srvName := s.Name
2023-07-01 18:01:48 +02:00
svc, err := connect.NewService(srvName, s.client)
2023-06-29 14:34:25 +02:00
s.connect = svc
2023-06-30 13:40:33 +02:00
cnf := svc.ServerTLSConfig()
2023-07-06 19:30:00 +02:00
fmt.Printf("CONNECT SERVER:: %s CONFIG:: %v\n", srvName, cnf)
2023-06-30 13:40:33 +02:00
for k, c := range cnf.Certificates {
2023-06-30 13:43:33 +02:00
fmt.Printf("CONNECT CERT %d: %v", k, c)
2023-06-30 13:40:33 +02:00
}
2023-06-29 14:34:25 +02:00
return svc, err
2022-12-01 17:56:11 +01:00
}
2023-06-29 14:13:23 +02:00
func (s *Service) KV() *consul.KV {
return s.kv
2022-12-24 20:28:37 +01:00
}
2022-12-02 03:22:36 +01:00
func (s *Service) healthCheck() (bool, error) {
alive := func() bool {
client := &http.Client{}
healthUrl := fmt.Sprintf("%s%s?name=%s", s.GetFullAddr(), "health", s.Name)
2022-12-02 03:22:36 +01:00
req, err := http.NewRequest(http.MethodGet, healthUrl, nil)
if err != nil {
return false
2022-12-01 17:56:11 +01:00
}
2023-06-28 23:22:15 +02:00
req.Header.Set("User-Agent", "service/internal")
2022-12-01 17:56:11 +01:00
2023-06-29 15:27:36 +02:00
fmt.Printf("Sending HEALTH CHECK request to: %s\n", healthUrl)
2022-12-02 03:22:36 +01:00
resp, err := client.Do(req)
if err != nil {
2023-07-02 01:46:11 +02:00
fmt.Printf("Sending HEALTH CHECK request error: %v\n", err)
2022-12-02 03:22:36 +01:00
return false
}
defer resp.Body.Close()
2022-12-01 17:56:11 +01:00
2023-06-29 15:59:27 +02:00
var body []byte
resp.Body.Read(body)
fmt.Printf("HEALTH CHECK response to: %v -- %v\n", resp, body)
2022-12-02 03:22:36 +01:00
return resp.StatusCode == http.StatusOK
}()
2022-12-01 17:56:11 +01:00
2022-12-02 03:22:36 +01:00
if alive {
2022-12-05 19:23:32 +01:00
if err := s.agent.PassTTL("service:"+s.GetID(), "OK"); err != nil {
2023-06-28 23:22:15 +02:00
fmt.Printf("Failed to pass TTL: %v", err)
2022-12-02 14:21:33 +01:00
return false, err
2022-12-02 03:22:36 +01:00
}
2022-12-01 17:56:11 +01:00
return true, nil
}
2022-12-05 19:23:32 +01:00
if err := s.agent.FailTTL("service:"+s.GetID(), ErrServiceUnavailable.Error()); err != nil {
2022-12-02 14:21:33 +01:00
return false, err
2022-12-02 03:22:36 +01:00
}
2022-12-01 17:56:11 +01:00
return false, ErrServiceUnavailable
}
func (s *Service) getTags() []string {
tags := []string{
"traefik.enable=true",
2022-12-24 17:25:41 +01:00
"traefik.http.routers." + s.Name + ".rule=PathPrefix(`" + s.pathPrefix + "`)",
2022-12-01 17:56:11 +01:00
"traefik.http.routers." + s.Name + ".entryPoints=https",
2022-12-06 02:19:04 +01:00
"traefik.http.routers." + s.Name + ".tls=true",
2022-12-01 19:05:59 +01:00
"traefik.http.routers." + s.Name + ".service=" + s.Name,
"traefik.http.routers." + s.Name + ".middlewares=auth_" + s.Name + ",requestid_" + s.Name + ",stripprefix_" + s.Name,
2022-12-01 19:05:59 +01:00
"traefik.http.services." + s.Name + ".loadbalancer.server.scheme=http",
2022-12-05 19:23:32 +01:00
"traefik.http.services." + s.Name + ".loadbalancer.server.port=" + strconv.Itoa(s.port),
2022-12-24 15:09:01 +01:00
"traefik.http.services." + s.Name + ".loadbalancer.passhostheader=false",
2023-06-21 20:48:28 +02:00
"traefik.http.middlewares.auth_" + s.Name + ".plugin.auth.handlerURL=" + config.GetEnv("AUTH_HANDLER_URL", ""),
2023-06-14 00:33:27 +02:00
// "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",
2023-04-10 16:03:02 +02:00
"traefik.http.middlewares.requestid_" + s.Name + ".plugin.requestid.headerName=X-Request-ID",
2022-12-24 17:57:59 +01:00
"traefik.http.middlewares.stripprefix_" + s.Name + ".stripprefix.prefixes=" + s.pathPrefix,
2022-12-06 02:21:07 +01:00
"traefik.tls.certificates.certfile=/certs/client.cert",
"traefik.tls.certificates.keyfile=/certs/client.key",
2022-12-01 17:56:11 +01:00
}
return tags
}