first working version
This commit is contained in:
parent
372915e24d
commit
6da132106f
18 changed files with 519 additions and 96 deletions
85
pkg/api/v1/client/client.go
Normal file
85
pkg/api/v1/client/client.go
Normal file
|
|
@ -0,0 +1,85 @@
|
|||
package client
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
apiclient "git.giftfish.de/ston1th/haproxy-lb/pkg/api/client"
|
||||
"git.giftfish.de/ston1th/haproxy-lb/pkg/api/v1/schema"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrClientIsNil = errors.New("client is nil")
|
||||
base = "/" + schema.Version
|
||||
)
|
||||
|
||||
type Client struct {
|
||||
c *apiclient.Client
|
||||
}
|
||||
|
||||
func NewClient(c *apiclient.Client) (*Client, error) {
|
||||
if c == nil {
|
||||
return nil, ErrClientIsNil
|
||||
}
|
||||
return &Client{c}, nil
|
||||
}
|
||||
|
||||
func (c *Client) GetLoadBalancers(ctx context.Context) (lbs map[string]schema.LoadBalancer, err error) {
|
||||
return c.GetLoadBalancersWithCluster(ctx, "")
|
||||
}
|
||||
|
||||
func (c *Client) GetLoadBalancersWithCluster(ctx context.Context, cluster string) (lbs map[string]schema.LoadBalancer, err error) {
|
||||
path := base + "/lb"
|
||||
if cluster != "" {
|
||||
path += "/" + cluster
|
||||
}
|
||||
req, err := c.c.NewRequest(ctx, "GET", path, nil)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
lbs = make(map[string]schema.LoadBalancer)
|
||||
_, err = c.c.Do(req, &lbs)
|
||||
return
|
||||
}
|
||||
|
||||
func (c *Client) GetLoadBalancer(ctx context.Context, cluster, name string) (lb schema.LoadBalancer, err error) {
|
||||
path := fmt.Sprintf("%s/lb/%s/%s", base, cluster, name)
|
||||
req, err := c.c.NewRequest(ctx, "GET", path, nil)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
_, err = c.c.Do(req, &lb)
|
||||
return
|
||||
}
|
||||
|
||||
func (c *Client) CreateLoadBalancer(ctx context.Context, cluster, name string, lb schema.LoadBalancer) (err error) {
|
||||
buf := new(bytes.Buffer)
|
||||
path := fmt.Sprintf("%s/lb/%s/%s", base, cluster, name)
|
||||
err = lb.ValidateClient()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
err = json.NewEncoder(buf).Encode(lb)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
req, err := c.c.NewRequest(ctx, "POST", path, buf)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
_, err = c.c.Do(req, nil)
|
||||
return
|
||||
}
|
||||
|
||||
func (c *Client) DeleteLoadBalancer(ctx context.Context, cluster, name string) (err error) {
|
||||
path := fmt.Sprintf("%s/lb/%s/%s", base, cluster, name)
|
||||
req, err := c.c.NewRequest(ctx, "DELETE", path, nil)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
_, err = c.c.Do(req, nil)
|
||||
return
|
||||
}
|
||||
|
|
@ -14,7 +14,7 @@ healthCheckNodePort
|
|||
const Version = "v1"
|
||||
|
||||
type LoadBalancer struct {
|
||||
Name string `json:"name"`
|
||||
Name string `json:"name,omitempty"`
|
||||
IP string `json:"ip,omitempty"`
|
||||
Options Options `json:"options,omitempty"`
|
||||
Ports []Port `json:"ports,omitempty"`
|
||||
|
|
@ -37,13 +37,7 @@ type Server struct {
|
|||
Port int `json:"port,omitempty"`
|
||||
}
|
||||
|
||||
func (lb LoadBalancer) Validate() error {
|
||||
if lb.Name == "" {
|
||||
return errors.New("LoadBalancer.Name can not be empty")
|
||||
}
|
||||
if lb.IP == "" {
|
||||
return errors.New("LoadBalancer.IP can not be empty")
|
||||
}
|
||||
func (lb LoadBalancer) ValidateClient() error {
|
||||
for i, p := range lb.Ports {
|
||||
if p.Port < 0 || p.Port > 65535 {
|
||||
return fmt.Errorf("LoadBalancer.Ports[%d].Port is invalid (range 0-65535", i)
|
||||
|
|
@ -63,6 +57,16 @@ func (lb LoadBalancer) Validate() error {
|
|||
return nil
|
||||
}
|
||||
|
||||
func (lb LoadBalancer) ValidateServer() error {
|
||||
if lb.Name == "" {
|
||||
return errors.New("LoadBalancer.Name can not be empty")
|
||||
}
|
||||
if lb.IP == "" {
|
||||
return errors.New("LoadBalancer.IP can not be empty")
|
||||
}
|
||||
return lb.ValidateClient()
|
||||
}
|
||||
|
||||
func (lb LoadBalancer) JSON() ([]byte, error) {
|
||||
return json.Marshal(lb)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,115 +0,0 @@
|
|||
package server
|
||||
|
||||
import (
|
||||
"git.giftfish.de/ston1th/haproxy-lb/pkg/config"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
weakrand "math/rand"
|
||||
//"net/http"
|
||||
"encoding/hex"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
var cacheSize = 100
|
||||
|
||||
func init() {
|
||||
weakrand.Seed(time.Now().UnixNano())
|
||||
}
|
||||
|
||||
type cache struct {
|
||||
cache map[string]bool
|
||||
mtx sync.Mutex
|
||||
}
|
||||
|
||||
func newCache() *cache {
|
||||
return &cache{
|
||||
cache: make(map[string]bool),
|
||||
}
|
||||
}
|
||||
|
||||
func (c *cache) get(key string) (bool, bool) {
|
||||
c.mtx.Lock()
|
||||
defer c.mtx.Unlock()
|
||||
v, ok := c.cache[key]
|
||||
return v, ok
|
||||
}
|
||||
|
||||
func (c *cache) set(key string, value bool) {
|
||||
c.mtx.Lock()
|
||||
defer c.mtx.Unlock()
|
||||
c.makeRoom()
|
||||
c.cache[key] = value
|
||||
}
|
||||
|
||||
func (c *cache) makeRoom() {
|
||||
if len(c.cache) < cacheSize {
|
||||
return
|
||||
}
|
||||
numToDelete := len(c.cache) / 10
|
||||
if numToDelete < 1 {
|
||||
numToDelete = 1
|
||||
}
|
||||
for deleted := 0; deleted <= numToDelete; deleted++ {
|
||||
rnd := weakrand.Intn(len(c.cache))
|
||||
i := 0
|
||||
for key := range c.cache {
|
||||
if i == rnd {
|
||||
delete(c.cache, key)
|
||||
break
|
||||
}
|
||||
i++
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type auth struct {
|
||||
users map[string]*creds
|
||||
cache *cache
|
||||
// bcryptMtx is there to ensure that bcrypt.CompareHashAndPassword is run
|
||||
// only once in parallel as this is CPU intensive.
|
||||
bcryptMtx sync.Mutex
|
||||
}
|
||||
|
||||
func (a *auth) Auth(user, pass, path string) bool {
|
||||
creds, valid := a.users[user]
|
||||
hash := creds.Hash
|
||||
|
||||
if !valid {
|
||||
// The user is not found. Use a fixed password hash to
|
||||
// prevent user enumeration by timing requests.
|
||||
// This is a bcrypt-hashed version of "fakepassword".
|
||||
hash = "$2y$10$QOauhQNbBCuQDKes6eFzPeMqBSjb7Mr5DUmpZ/VcEd00UAV/LDeSi"
|
||||
}
|
||||
|
||||
cacheKey := hex.EncodeToString(append(append([]byte(user), []byte(hash)...), []byte(pass)...))
|
||||
authOk, ok := a.cache.get(cacheKey)
|
||||
|
||||
if !ok {
|
||||
// This user, hashedPassword, password is not cached.
|
||||
a.bcryptMtx.Lock()
|
||||
err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(pass))
|
||||
a.bcryptMtx.Unlock()
|
||||
|
||||
authOk = err == nil
|
||||
a.cache.set(cacheKey, authOk)
|
||||
}
|
||||
|
||||
return authOk && valid && strings.HasPrefix(path, creds.Prefix)
|
||||
}
|
||||
|
||||
type creds struct {
|
||||
Hash string
|
||||
Prefix string
|
||||
}
|
||||
|
||||
func newAuth(conf config.Config) (a *auth) {
|
||||
a = &auth{
|
||||
users: make(map[string]*creds),
|
||||
cache: newCache(),
|
||||
}
|
||||
for _, u := range conf.Server.BasicAuth {
|
||||
a.users[u.User] = &creds{u.Hash, u.Prefix}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
|
@ -5,6 +5,7 @@ import (
|
|||
//"net/http"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net"
|
||||
|
||||
"git.giftfish.de/ston1th/haproxy-lb/pkg/api/types"
|
||||
"git.giftfish.de/ston1th/haproxy-lb/pkg/api/v1/schema"
|
||||
|
|
@ -13,10 +14,15 @@ import (
|
|||
|
||||
func authHandler(h types.CtxHandler) types.CtxHandler {
|
||||
return func(ctx *types.Context) {
|
||||
// TODO
|
||||
// test:123456
|
||||
// test:$2b$10$zNfGTAQ94vifj2wtGsv1W.yZRe4/rDBzQixpB6FbrTed4BnHuNqBS
|
||||
//bcrypt.CompareHashAndPassword(hash, pw)
|
||||
user, pass, ok := ctx.Request.BasicAuth()
|
||||
if !ok {
|
||||
ctx.Err(types.ErrUnauthorized)
|
||||
return
|
||||
}
|
||||
if !ctx.Data.Auth.Login(user, pass, ctx.Path()) {
|
||||
ctx.Err(types.ErrForbidden)
|
||||
return
|
||||
}
|
||||
h(ctx)
|
||||
}
|
||||
}
|
||||
|
|
@ -34,6 +40,14 @@ func lbname(c, n string) string {
|
|||
return c + "_" + n
|
||||
}
|
||||
|
||||
func getIP(cidr string) (string, error) {
|
||||
ip, _, err := net.ParseCIDR(cidr)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return ip.String(), nil
|
||||
}
|
||||
|
||||
func lbHandler(ctx *types.Context) {
|
||||
cl := ctx.Var("cluster")
|
||||
n := ctx.Var("name")
|
||||
|
|
@ -52,9 +66,6 @@ func lbHandler(ctx *types.Context) {
|
|||
}
|
||||
ctx.Body(b)
|
||||
case "POST":
|
||||
// TODO
|
||||
// handle if loadbalancer already exists
|
||||
// decode existing LB and read Name + IP from there
|
||||
b, err := ctx.ReadBody()
|
||||
if err != nil {
|
||||
ctx.Log.Error(err, "error reading request body", "cluster", cl, "name", n)
|
||||
|
|
@ -69,13 +80,28 @@ func lbHandler(ctx *types.Context) {
|
|||
return
|
||||
}
|
||||
lb.Name = lbname(cl, n)
|
||||
lb.IP, err = ctx.Data.Alloc.AllocIP(context.Background(), name)
|
||||
if err != nil {
|
||||
ctx.Log.Error(err, "error allocating IP for loadbalancer", "cluster", cl, "name", n)
|
||||
cidr, err := ctx.Data.DB.GetIP(name)
|
||||
if err != nil && err != cluster.ErrKeyNotFound {
|
||||
ctx.Log.Error(err, "error getting existing loadbalancer ip", "cluster", cl, "name", n)
|
||||
ctx.Err(types.ErrISE)
|
||||
return
|
||||
}
|
||||
err = lb.Validate()
|
||||
if cidr != "" {
|
||||
lb.IP, err = getIP(cidr)
|
||||
if err != nil {
|
||||
ctx.Log.Error(err, "error parsing existing ip", "cluster", cl, "name", n, "cidr", cidr)
|
||||
ctx.Err(types.ErrISE)
|
||||
return
|
||||
}
|
||||
} else {
|
||||
lb.IP, err = ctx.Data.Alloc.AllocIP(context.Background(), name)
|
||||
if err != nil {
|
||||
ctx.Log.Error(err, "error allocating ip for loadbalancer", "cluster", cl, "name", n)
|
||||
ctx.Err(types.ErrISE)
|
||||
return
|
||||
}
|
||||
}
|
||||
err = lb.ValidateServer()
|
||||
if err != nil {
|
||||
ctx.Log.Error(err, "error validating loadbalancer", "cluster", cl, "name", n)
|
||||
ctx.Err(types.ErrInvalid)
|
||||
|
|
@ -95,8 +121,12 @@ func lbHandler(ctx *types.Context) {
|
|||
}
|
||||
ctx.OK()
|
||||
case "DELETE":
|
||||
if !ctx.Data.DB.LBExists(name) {
|
||||
ctx.Err(types.ErrNotFound)
|
||||
return
|
||||
}
|
||||
err := ctx.Data.Alloc.FreeIP(context.Background(), name)
|
||||
if err != nil {
|
||||
if err != nil && err != cluster.ErrKeyNotFound {
|
||||
ctx.Log.Error(err, "error freeing IP of loadbalancer", "cluster", cl, "name", n)
|
||||
ctx.Err(types.ErrISE)
|
||||
return
|
||||
|
|
|
|||
|
|
@ -24,7 +24,7 @@ var Routes = []types.Route{
|
|||
[]string{"GET"},
|
||||
},
|
||||
{
|
||||
v1 + "/lb/{cluster:[a-zA-Z0-9-]+}/{name:[a-zA-Z0-9-]+$}",
|
||||
v1 + "/lb/{cluster:[a-zA-Z0-9-]+}/{name:[a-zA-Z0-9-_]+$}",
|
||||
authHandler(lbHandler),
|
||||
[]string{"GET", "POST", "DELETE"},
|
||||
},
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue