go-api-pkg/consul/discovery.go

226 lines
6.2 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"
2024-05-30 17:01:18 +02:00
"git.pbiernat.io/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
2024-07-20 14:42:16 +02:00
tls bool
2022-12-24 17:10:47 +01:00
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
2024-07-19 16:39:11 +02:00
hcTicker *time.Ticker
ttlTicker *time.Ticker
2022-12-01 17:56:11 +01:00
}
var ErrServiceUnavailable = fmt.Errorf("Service is unavailable")
func NewService(servAddr, id, name, useDomainOverIp, addr, 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 = addr
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
2024-07-20 14:42:16 +02:00
s.tls = true // FIXME add arg
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
if useDomainOverIp == "true" { // FIXME types...
s.Address = domain
}
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-29 15:11:22 +02:00
isTLS := s.port == 443
proto := "http"
if isTLS {
proto = "https"
}
2024-07-17 21:53:35 +02:00
return fmt.Sprintf("%s://%s:%d/", proto, 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{
2023-07-06 21:45:45 +02:00
ID: s.GetID(),
// Kind: consul.ServiceKindConnectProxy,
2022-12-01 19:45:47 +01:00
Name: s.Name,
2024-07-17 15:34:55 +02: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-29 14:57:36 +02:00
// Connect: &consul.AgentServiceConnect{Native: true},
2023-07-08 02:22:28 +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
2023-07-08 17:11:53 +02:00
return nil
}
func (s *Service) Unregister() error {
2024-07-19 16:48:08 +02:00
// s.ttlTicker.Stop()
2024-07-19 16:45:42 +02:00
// s.hcTicker.Stop()
2024-07-19 16:41:37 +02:00
2024-07-19 16:30:04 +02:00
s.client.Catalog().Deregister(&consul.CatalogDeregistration{
Address: s.Address,
ServiceID: s.GetID(),
}, nil)
2024-07-17 18:57:50 +02:00
2023-07-08 17:11:53 +02:00
return s.agent.ServiceDeregister(s.GetID())
}
2023-07-29 13:47:51 +02:00
func (s *Service) RegisterHealthChecks() {
2023-07-08 17:11:53 +02:00
go func() { // startup register
2024-07-19 17:06:39 +02:00
t := time.NewTicker(time.Second)
for range t.C {
2023-04-07 10:09:10 +02:00
if ok, _ := s.healthCheck(); ok {
2024-07-19 17:06:39 +02:00
t.Stop()
2022-12-02 03:22:36 +01:00
}
}
2023-07-08 17:11:53 +02:00
}()
2022-12-02 03:22:36 +01:00
2023-07-08 17:11:53 +02:00
go func() { // TTL
2024-07-19 17:06:39 +02:00
t := time.NewTicker(s.ttl)
for range t.C {
2023-06-28 23:34:45 +02:00
if _, err := s.healthCheck(); err != nil {
2024-07-19 17:06:39 +02:00
// fmt.Printf("HealthCheck endpoint not available (%s)#: %v\n", s.GetFullAddr(), err)
t.Stop()
2023-06-28 23:34:45 +02:00
}
}
2023-07-08 17:11:53 +02:00
}()
2022-12-05 19:23:32 +01:00
}
2023-06-29 14:25:08 +02:00
func (s *Service) Connect() (*connect.Service, error) {
2023-07-29 14:57:36 +02:00
// l := hclog.New(&hclog.LoggerOptions{
// Name: "consul-registry",
// Level: hclog.Trace,
// })
svc, err := connect.NewService(s.Name, 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-26 23:14:25 +02:00
fmt.Printf("CONNECT SERVER:: %s CONFIG:: %v\n", s.Name, 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)
2024-07-20 14:18:08 +02:00
fmt.Printf("HealthCheck URL: %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
2022-12-02 03:22:36 +01:00
resp, err := client.Do(req)
if err != nil {
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)
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",
2024-07-17 16:11:14 +02:00
// "traefik.http.middlewares.auth_" + s.Name + ".forwardauth.trustForwardHeader=true",
2024-07-17 17:02:02 +02:00
// "traefik.http.middlewares.auth_" + s.Name + ".forwardauth.authRequestHeaders=Cookie",
// "traefik.http.middlewares.auth_" + s.Name + ".forwardauth.authResponseHeaders=Set-Cookie, Server",
2024-07-20 14:20:01 +02:00
"traefik.http.middlewares.auth_" + s.Name + ".plugin.auth.handlerURL=" + config.GetEnv("AUTH_HANDLER_URL", "https://identity.service.ego.io/api/v1/traefik"),
2024-07-17 16:11:14 +02:00
"traefik.http.middlewares.stripprefix_" + s.Name + ".stripprefix.prefixes=" + s.pathPrefix,
2024-07-17 22:37:26 +02:00
"traefik.http.middlewares.requestid_" + s.Name + ".plugin.requestid.headerName=X-Request-ID",
2024-07-17 22:59:16 +02:00
// "treafik.http.middlewares.retryif_" + s.Name + ".plugin.retryif.attempts=3",
// "treafik.http.middlewares.retryif_" + s.Name + ".plugin.retryif.statusCode=503",
2024-07-16 21:53:59 +02:00
"traefik.http.routers." + s.Name + ".rule=PathPrefix(`" + s.pathPrefix + "`)",
2024-07-20 14:24:38 +02: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",
2024-07-20 14:24:38 +02:00
"traefik.http.routers." + s.Name + ".tls=true",
2022-12-01 19:05:59 +01:00
"traefik.http.routers." + s.Name + ".service=" + s.Name,
2024-07-17 16:03:46 +02:00
// "traefik.http.routers." + s.Name + ".middlewares=auth_" + s.Name + ",stripprefix_" + s.Name,
2024-07-17 22:59:16 +02:00
"traefik.http.routers." + s.Name + ".middlewares=auth_" + s.Name + ",stripprefix_" + s.Name + ",requestid_" + s.Name + "",
2024-07-20 14:20:01 +02:00
"traefik.http.services." + s.Name + ".loadbalancer.server.scheme=https",
2022-12-05 19:23:32 +01:00
"traefik.http.services." + s.Name + ".loadbalancer.server.port=" + strconv.Itoa(s.port),
2024-07-17 17:15:39 +02:00
"traefik.http.services." + s.Name + ".loadbalancer.passhostheader=true",
"traefik.http.services." + s.Name + ".loadbalancer.healthcheck.interval=1s",
"traefik.http.services." + s.Name + ".loadbalancer.healthcheck.timeout=1s",
"traefik.http.services." + s.Name + ".loadbalancer.healthcheck.path=/health",
2024-07-20 14:42:16 +02: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
}