Compare commits
2 Commits
b829092503
...
e97a13d1e8
| Author | SHA1 | Date | |
|---|---|---|---|
| e97a13d1e8 | |||
| e0d270a2eb |
@@ -1,222 +0,0 @@
|
||||
package consul
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
consul "github.com/hashicorp/consul/api"
|
||||
"github.com/hashicorp/consul/connect"
|
||||
)
|
||||
|
||||
type Service struct {
|
||||
Name string
|
||||
Address string
|
||||
appID string
|
||||
domain string
|
||||
pathPrefix string
|
||||
tls bool
|
||||
port int
|
||||
ttl time.Duration
|
||||
client *consul.Client
|
||||
agent *consul.Agent
|
||||
connect *connect.Service
|
||||
kv *consul.KV
|
||||
|
||||
// hcTicker *time.Ticker
|
||||
// ttlTicker *time.Ticker
|
||||
}
|
||||
|
||||
var ErrServiceUnavailable = fmt.Errorf("Service is unavailable")
|
||||
|
||||
func NewService(servAddr, id, name, useDomainOverIp, addr, domain, pathPrefix string, appPort int) (*Service, error) {
|
||||
s := new(Service)
|
||||
s.Name = name
|
||||
s.Address = addr
|
||||
s.appID = id
|
||||
s.domain = domain
|
||||
s.pathPrefix = pathPrefix
|
||||
s.tls = true // FIXME add arg
|
||||
s.port = appPort
|
||||
s.ttl = time.Second * 10
|
||||
|
||||
if useDomainOverIp == "true" { // FIXME types...
|
||||
s.Address = domain
|
||||
}
|
||||
|
||||
client, err := consul.NewClient(newClientConfig(servAddr))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
s.client = client
|
||||
s.agent = client.Agent()
|
||||
s.kv = client.KV()
|
||||
|
||||
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 {
|
||||
proto := "http"
|
||||
if s.tls {
|
||||
proto = "https"
|
||||
}
|
||||
return fmt.Sprintf("%s://%s:%d/", proto, s.domain, s.port)
|
||||
}
|
||||
|
||||
func (s *Service) Register() error {
|
||||
def := &consul.AgentServiceRegistration{
|
||||
ID: s.GetID(),
|
||||
// Kind: consul.ServiceKindConnectProxy,
|
||||
Name: s.Name,
|
||||
Address: s.Address,
|
||||
Port: s.port,
|
||||
Tags: s.getTags(),
|
||||
Connect: &consul.AgentServiceConnect{Native: true},
|
||||
// Proxy: &consul.AgentServiceConnectProxyConfig{
|
||||
// DestinationServiceName: s.Name,
|
||||
// },
|
||||
Check: &consul.AgentServiceCheck{
|
||||
// Interval: "5s",
|
||||
// Timeout: "1s",
|
||||
TTL: s.ttl.String(),
|
||||
Status: "passing",
|
||||
DeregisterCriticalServiceAfter: "10s",
|
||||
},
|
||||
}
|
||||
|
||||
if err := s.agent.ServiceRegister(def); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
func (s *Service) Unregister() error {
|
||||
// s.ttlTicker.Stop()
|
||||
// s.hcTicker.Stop()
|
||||
|
||||
s.client.Catalog().Deregister(&consul.CatalogDeregistration{
|
||||
Address: s.Address,
|
||||
ServiceID: s.GetID(),
|
||||
}, nil)
|
||||
|
||||
return s.agent.ServiceDeregister(s.GetID())
|
||||
}
|
||||
|
||||
func (s *Service) RegisterHealthChecks() {
|
||||
go func() { // startup register
|
||||
t := time.NewTicker(time.Second)
|
||||
for range t.C {
|
||||
if ok, _ := s.healthCheck(); ok {
|
||||
t.Stop()
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
go func() { // TTL
|
||||
t := time.NewTicker(time.Second * 5)
|
||||
for range t.C {
|
||||
if _, err := s.healthCheck(); err != nil {
|
||||
// fmt.Printf("HealthCheck endpoint not available (%s)#: %v\n", s.GetFullAddr(), err)
|
||||
t.Stop()
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
func (s *Service) Connect() (*connect.Service, error) {
|
||||
// l := hclog.New(&hclog.LoggerOptions{
|
||||
// Name: "consul-registry",
|
||||
// Level: hclog.Trace,
|
||||
// })
|
||||
svc, err := connect.NewService(s.Name, s.client)
|
||||
s.connect = svc
|
||||
fmt.Printf("CONNECT SERVER:: %s CERTS:: %v\n", s.Name, svc.ServerTLSConfig())
|
||||
// for k, c := range cnf.Certificates {
|
||||
// fmt.Printf("CONNECT CERT %d: %v", k, c)
|
||||
// }
|
||||
|
||||
return svc, err
|
||||
}
|
||||
|
||||
func (s *Service) KV() *consul.KV {
|
||||
return s.kv
|
||||
}
|
||||
|
||||
func (s *Service) healthCheck() (bool, error) {
|
||||
alive := func() bool {
|
||||
client := &http.Client{}
|
||||
healthUrl := fmt.Sprintf("%s%s?name=%s", s.GetFullAddr(), "health", s.Name)
|
||||
// fmt.Printf("HealthCheck URL: %s%s?name=%s", s.GetFullAddr(), "health", s.Name)
|
||||
req, err := http.NewRequest(http.MethodGet, healthUrl, nil)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
req.Header.Set("User-Agent", "service/internal")
|
||||
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
var body []byte
|
||||
resp.Body.Read(body)
|
||||
|
||||
return resp.StatusCode == http.StatusOK
|
||||
}()
|
||||
|
||||
if alive {
|
||||
if err := s.agent.PassTTL("service:"+s.GetID(), "OK"); err != nil {
|
||||
fmt.Printf("Failed to pass TTL: %v", err)
|
||||
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.middlewares.auth_" + s.Name + ".forwardauth.trustForwardHeader=true",
|
||||
// "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 + ".plugin.auth.handlerURL=" + config.GetEnv("AUTH_HANDLER_URL", "https://identity.service.ego.io/api/v1/traefik"),
|
||||
// "traefik.http.middlewares.stripprefix_" + s.Name + ".stripprefix.prefixes=" + s.pathPrefix,
|
||||
// "traefik.http.middlewares.requestid_" + s.Name + ".plugin.requestid.headerName=X-Request-ID",
|
||||
// "treafik.http.middlewares.retryif_" + s.Name + ".plugin.retryif.attempts=3",
|
||||
// "treafik.http.middlewares.retryif_" + s.Name + ".plugin.retryif.statusCode=503",
|
||||
// "traefik.http.routers." + s.Name + ".rule=Host(`" + s.domain + "`) && 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 + ",stripprefix_" + s.Name,
|
||||
// "traefik.http.routers." + s.Name + ".middlewares=auth_" + s.Name + ",stripprefix_" + s.Name + ",requestid_" + s.Name + "",
|
||||
// "traefik.http.services." + s.Name + ".loadbalancer.server.scheme=https",
|
||||
// "traefik.http.services." + s.Name + ".loadbalancer.server.port=" + strconv.Itoa(s.port),
|
||||
// "traefik.http.services." + s.Name + ".loadbalancer.passhostheader=true",
|
||||
// "traefik.http.services." + s.Name + ".loadbalancer.healthcheck.interval=5s",
|
||||
// "traefik.http.services." + s.Name + ".loadbalancer.healthcheck.timeout=1s",
|
||||
// "traefik.http.services." + s.Name + ".loadbalancer.healthcheck.path=/health",
|
||||
// "traefik.tls.certificates.certfile=certs/client.crt",
|
||||
// "traefik.tls.certificates.keyfile=certs/client.key",
|
||||
}
|
||||
|
||||
return tags
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
package fluentd
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func ParseAddr(addr string) (string, int, error) {
|
||||
p := strings.Split(addr, ":")
|
||||
fHost := p[0]
|
||||
fPort, err := strconv.Atoi(p[1])
|
||||
if err != nil {
|
||||
return "", 0, err
|
||||
}
|
||||
|
||||
return fHost, fPort, nil
|
||||
}
|
||||
@@ -1,54 +0,0 @@
|
||||
package fluentd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"time"
|
||||
|
||||
"github.com/fluent/fluent-logger-golang/fluent"
|
||||
)
|
||||
|
||||
type Logger struct {
|
||||
fluent *fluent.Fluent
|
||||
appName string
|
||||
}
|
||||
|
||||
func NewLogger(appName, fHost string, fPort int) (*Logger, error) {
|
||||
config := fluent.Config{
|
||||
FluentHost: fHost,
|
||||
FluentPort: fPort,
|
||||
WriteTimeout: 100 * time.Millisecond,
|
||||
}
|
||||
fluent, err := fluent.New(config)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &Logger{fluent, appName}, nil
|
||||
}
|
||||
|
||||
func (l *Logger) Log(format string, v ...any) {
|
||||
mapData := map[string]string{
|
||||
"message": fmt.Sprintf(format, v...),
|
||||
}
|
||||
err := l.fluent.Post(l.appName, mapData)
|
||||
if err != nil {
|
||||
log.Println("Error sending log: ", err)
|
||||
}
|
||||
}
|
||||
|
||||
func (l *Logger) Ping() error {
|
||||
mapData := map[string]string{
|
||||
"message": "Checking is Fluentd alive",
|
||||
}
|
||||
err := l.fluent.Post(l.appName, mapData)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (l *Logger) Close() error {
|
||||
return l.fluent.Close()
|
||||
}
|
||||
2
go.mod
2
go.mod
@@ -1,6 +1,6 @@
|
||||
module git.ego.freeddns.org/egommerce/go-api-pkg
|
||||
|
||||
go 1.18
|
||||
go 1.24
|
||||
|
||||
require (
|
||||
github.com/fluent/fluent-logger-golang v1.9.0
|
||||
|
||||
@@ -1,38 +0,0 @@
|
||||
package redis
|
||||
|
||||
// import (
|
||||
// "context"
|
||||
// "strconv"
|
||||
// "time"
|
||||
|
||||
// "github.com/go-redis/redis/v8"
|
||||
// )
|
||||
|
||||
// func NewCache(host string, port int, password string) *redis.Client {
|
||||
// redis := redis.NewClient(&redis.Options{
|
||||
// Addr: host + ":" + strconv.Itoa(port),
|
||||
// Password: password,
|
||||
// DB: 0,
|
||||
// })
|
||||
// defer redis.Close()
|
||||
|
||||
// return redis
|
||||
// }
|
||||
|
||||
// func Get(ctx context.Context, key string) (float64, error) {
|
||||
// // ctx := context.Background() // FIXME
|
||||
// price, err := s.cache.Get(ctx, key).Float64()
|
||||
// if err != nil {
|
||||
// s.log.Log("cache read error(key not exists): %#v", err)
|
||||
// return 0, err
|
||||
// }
|
||||
|
||||
// return price, nil
|
||||
// }
|
||||
|
||||
// func Set(ctx context.Context, key string, value any, exp time.Duration) error {
|
||||
// // ctx := context.Background() // FIXME
|
||||
// s.cache.Set(ctx, key, value, exp)
|
||||
|
||||
// return nil
|
||||
// }
|
||||
Reference in New Issue
Block a user