some work done

This commit is contained in:
ston1th 2021-03-01 07:40:10 +01:00
commit 09fe1cd163
13 changed files with 174 additions and 45 deletions

29
pkg/haproxy/config.go Normal file
View file

@ -0,0 +1,29 @@
package haproxy
type Config struct {
LoadBalancers []LoadBalancer
}
type LoadBalancer struct {
Name string
IP string
Options Options
Ports []Port
}
type Options struct {
Frontend []string
Backend []string
DefaultServer string
}
type Port struct {
Port int
Servers []Server
}
type Server struct {
Name string
IP string
Port int
}

View file

@ -1,7 +1,10 @@
package haproxy
import (
"bytes"
"context"
"crypto/sha256"
"io"
"io/ioutil"
"os"
"sync"
@ -18,6 +21,7 @@ type HAProxyManager struct {
configFile string
serviceManager ServiceManager
template *template.Template
hash []byte
}
func NewHAProxyManager(configFile string) (*HAProxyManager, error) {
@ -32,26 +36,32 @@ func NewHAProxyManager(configFile string) (*HAProxyManager, error) {
}, nil
}
func (ha *HAProxyManager) checkConfig(ctx context.Context, configFile string) error {
return exec.CommandContext(ctx, "haproxy", "-c", "-f", configFile).Run()
}
func (ha *HAProxyManager) UpdateConfig(ctx context.Context, lbs []config.LoadBalancer) error {
ha.Lock()
defer ha.Unlock()
func (ha *HAProxyManager) checkConfig(ctx context.Context, lbs Config) (hash []byte, err error) {
tmp, err := ioutil.TempFile(os.TempDir(), "haproxy_")
if err != nil {
return err
return
}
defer tmp.Close()
defer os.Remove(tmp.Name())
err = ha.template.Execute(tmp, lbs)
h := sha256.New()
w := io.MultiWriter(tmp, h)
err = ha.template.Execute(w, lbs)
if err != nil {
return
}
hash = h.Sum(nil)
return hash, exec.CommandContext(ctx, "haproxy", "-c", "-f", tmp.Name()).Run()
}
func (ha *HAProxyManager) UpdateConfig(ctx context.Context, lbs Config) error {
ha.Lock()
defer ha.Unlock()
hash, err := ha.checkConfig(ctx, lbs)
if err != nil {
return err
}
err = ha.checkConfig(ctx, tmp.Name())
if err != nil {
return err
if bytes.Equal(ha.hash, hash) {
return nil
}
file, err := os.OpenFile(ha.configFile, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
if err != nil {
@ -63,5 +73,6 @@ func (ha *HAProxyManager) UpdateConfig(ctx context.Context, lbs []config.LoadBal
return err
}
file.Close()
ha.hash = hash
return ha.serviceManager.Reload()
}

View file

@ -15,7 +15,7 @@ defaults
timeout client 5000ms
timeout tunnel 3600s
timeout check 10s
{{ range $item := . -}}
{{ range $item := .LoadBalancers -}}
{{ range $port := $item.Ports -}}
frontend fr_{{ $item.Name }}_{{ $port.Port }}
bind {{ $item.IP }}:{{ $port.Port }}