Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 9 additions & 3 deletions backend/backend.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
package backend

import "sync"
import (
"sync"
"sync/atomic"
)

type Backend struct {
url string
healthy bool
healthy atomic.Bool
}

func NewBackend(url string) *Backend {
Expand All @@ -16,7 +19,7 @@ func (b *Backend) GetUrl() string {
}

func (b *Backend) IsHealthy() bool {
return b.healthy
return b.healthy.Load()
}

type BackendPool struct {
Expand All @@ -25,6 +28,9 @@ type BackendPool struct {
}

func NewBackendPool(bs []*Backend) *BackendPool {
if len(bs) < 1 {
panic("backend pool is empty")
}
return &BackendPool{bs: bs}
}

Expand Down
16 changes: 14 additions & 2 deletions listener/listener.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,10 @@ package listener
import (
"context"
"errors"
"fmt"
"log"
"net"
"sync"
"time"
)

type ProxyIO interface {
Expand All @@ -21,6 +22,9 @@ type Listener struct {
}

func NewListener(px ProxyIO) *Listener {
if px == nil {
panic("proxy cannot be nil")
}
return &Listener{
proxy: px,
activeConns: make(map[net.Conn]struct{}),
Expand All @@ -36,6 +40,8 @@ func (l *Listener) Listen(ln net.Listener) {
if errors.Is(err, net.ErrClosed) {
return
}
log.Printf("accept error: %v", err)
time.Sleep(1 * time.Second)
continue
}
l.mu.Lock()
Expand All @@ -44,6 +50,12 @@ func (l *Listener) Listen(ln net.Listener) {
l.wg.Add(1)
go func() {
defer l.wg.Done()
defer func() {
if r := recover(); r != nil {
log.Printf("panic handling connection %s: %v",
conn.RemoteAddr(), r)
}
}()
defer conn.Close()
defer func() {
l.mu.Lock()
Expand All @@ -52,7 +64,7 @@ func (l *Listener) Listen(ln net.Listener) {
}()
err := l.proxy.Handle(conn)
if err != nil {
fmt.Println(err)
log.Printf("connection %s: %v", conn.RemoteAddr(), err)
}
}()
}
Expand Down
3 changes: 2 additions & 1 deletion main.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"load-balancer/proxy"
"load-balancer/router"
"load-balancer/router/roundrobin"
"log"
"net"
"os"
"os/signal"
Expand All @@ -20,7 +21,7 @@ func main() {
host := "[::1]"
ln, err := net.Listen("tcp", fmt.Sprintf(":%d", port))
if err != nil {
panic(err)
log.Fatalf("failed to listen on port %d: %v", port, err)
}
b := backend.NewBackend("localhost:80")
b1 := backend.NewBackend("localhost:8081")
Expand Down
23 changes: 16 additions & 7 deletions proxy/proxy.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import (
)

type RouterIO interface {
Route(string) *backend.Backend
Route(string) (*backend.Backend, error)
}

type Proxy struct {
Expand All @@ -19,6 +19,9 @@ type Proxy struct {
}

func NewProxy(rt RouterIO) *Proxy {
if rt == nil {
panic("router cannot be nil")
}
return &Proxy{
router: rt,
dialTimeout: 10 * time.Second,
Expand All @@ -28,30 +31,36 @@ func NewProxy(rt RouterIO) *Proxy {

func (p *Proxy) Handle(conn net.Conn) error {
localAddr := conn.LocalAddr().String()
b := p.router.Route(localAddr)
if b == nil {
return fmt.Errorf("no available backend")
b, err := p.router.Route(localAddr)
if err != nil {
return fmt.Errorf("routing: %w", err)
}
backendConn, err := net.DialTimeout("tcp", b.GetUrl(), p.dialTimeout)
if err != nil {
return err
return fmt.Errorf("dial %s: %w", b.GetUrl(), err)
}
defer backendConn.Close()
err = conn.SetDeadline(time.Now().Add(p.connTimeout))
if err != nil {
return err
return fmt.Errorf("set deadline %s: %w", conn.RemoteAddr(), err)
}
err = backendConn.SetDeadline(time.Now().Add(p.connTimeout))
if err != nil {
return err
return fmt.Errorf("set deadline %s: %w", backendConn.RemoteAddr(), err)
}
ch := make(chan error, 2)
go func() {
_, localErr := io.Copy(backendConn, conn)
if localErr != nil {
localErr = fmt.Errorf("copy from %s to %s: %w", conn.RemoteAddr(), backendConn.RemoteAddr(), localErr)
}
ch <- localErr
}()
go func() {
_, localErr := io.Copy(conn, backendConn)
if localErr != nil {
localErr = fmt.Errorf("copy from %s to %s: %w", backendConn.RemoteAddr(), conn.RemoteAddr(), localErr)
}
ch <- localErr
}()
for range 2 {
Expand Down
19 changes: 15 additions & 4 deletions router/roundrobin/round_robin.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
package roundrobin

import (
"errors"
"load-balancer/backend"
"sync"
)

var ErrNoBackends = errors.New("no backends available")

type BackendPoolIO interface {
GetPool() []*backend.Backend
}
Expand All @@ -16,14 +19,22 @@ type RoundRobin struct {
}

func NewRoundRobin(bs BackendPoolIO) *RoundRobin {
if bs == nil {
panic("backend pool cannot be nil")
}
return &RoundRobin{bp: bs}
}

func (rr *RoundRobin) GetBackend() *backend.Backend {
func (rr *RoundRobin) GetBackend() (*backend.Backend, error) {
rr.mu.Lock()
defer rr.mu.Unlock()
bp := rr.bp.GetPool()
b := bp[rr.index]
rr.index = (rr.index + 1) % len(bp)
return b
for range len(bp) {
b := bp[rr.index]
rr.index = (rr.index + 1) % len(bp)
if b.IsHealthy() {
return b, nil
}
}
return nil, ErrNoBackends
}
7 changes: 5 additions & 2 deletions router/router.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,22 @@ package router
import "load-balancer/backend"

type AlgoIO interface {
GetBackend() *backend.Backend
GetBackend() (*backend.Backend, error)
}

type Router struct {
router map[string]AlgoIO
}

func NewRouter(path string, be AlgoIO) *Router {
if be == nil {
panic("algorithm cannot be nil")
}
router := make(map[string]AlgoIO)
router[path] = be
return &Router{router: router}
}

func (r *Router) Route(path string) *backend.Backend {
func (r *Router) Route(path string) (*backend.Backend, error) {
return r.router[path].GetBackend()
}
Loading