Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added dynamic load balancing feature #1

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
tcpsplice
monitor.go
tcpsplice.conf
13 changes: 9 additions & 4 deletions monitor.html
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@
{
background-color: #f0f0f0;
}
.session:nth-child(odd)
.session:nth-child(odd)
{
background-color: #f8f8f8;
}
Expand Down Expand Up @@ -115,6 +115,10 @@
{
width: 230px;
}
.xxlarge
{
width: 300px;
}
.large
{
width: 170px;
Expand Down Expand Up @@ -190,7 +194,7 @@
if (ids.length > 0)
{
services += '<div class="session"><span class="large">source address</span><span class="large">target address</span>' +
'<span class="medium">duration</span><span class="xlarge">uplink &#9650;</span>' +
'<span class="xxlarge">target name</span><span class="small">duration</span><span class="xlarge">uplink &#9650;</span>' +
'<span class="xlarge">downlink &#9660;</span><span class="large">metadata</span><span class="small">abort</span></div>';
}
else
Expand All @@ -201,14 +205,15 @@
{
info = sessions[session[0]];
services += sprintf('<div class="session%s">' +
'<span class="large">%s</span><span class="large">%s</span><span class="medium">%s</span>' +
'<span class="large">%s</span><span class="large">%s</span><span class="xxlarge">%s</span>' +
'<span class="small">%s</span>' +
'<span class="xlarge">%s - %.1fMbps - %.1fMbps</span>' +
'<span class="xlarge">%s - %.1fMbps - %.1fMbps</span>' +
'<span class="large">%s</span>' +
'<span class="small"><a href="#" onclick="return terminate(\'%s\');">&#10060;</a></span>' +
'</div>',
info.done ? " done" : "",
info.source, info.target, age(info.duration),
info.source, info.target, info.targetName, age(info.duration),
size(info.bytes[0]), info.mean[0], info.last[0],
size(info.bytes[1]), info.mean[1], info.last[1],
info.meta, session[0]);
Expand Down
129 changes: 102 additions & 27 deletions tcpsplice.go
Original file line number Diff line number Diff line change
@@ -1,28 +1,31 @@
package main

import (
"bytes"
"crypto/md5"
"encoding/json"
"fmt"
"github.com/pyke369/golang-support/uconfig"
"github.com/pyke369/golang-support/ulog"
"io/ioutil"
"math"
"math/rand"
"net"
"net/http"
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
"sync"
"time"
)

const progname = "tcpsplice"
const version = "1.0.2"
const version = "1.0.3"

type Session struct {
id, service, source, target, meta string
id, service, source, target, meta, targetName string
started, active, last time.Time
sourceRead, targetWritten, targetRead, sourceWritten int64
sourceMeanThroughput, targetMeanThroughput float64
Expand All @@ -31,22 +34,61 @@ type Session struct {
abort chan bool
}

type Backend struct {
Fqdn string
Port int
}

var (
config *uconfig.UConfig
logger *ulog.ULog
start time.Time
statistics chan *Session
sessions map[string]*Session
sessionsLock sync.RWMutex
backendsURL bytes.Buffer
)

func serviceHandler(service string, listener *net.TCPListener) {
//Init service
remotes := make([]string, 0)
listenPort := listener.Addr().(*net.TCPAddr).Port
backendUrl := config.GetString(fmt.Sprintf("services.%s.backend_url", service), "")
static := true
if strings.EqualFold(config.GetString(fmt.Sprintf("services.%s.remote_type", service), "static"), "dynamic") {
logger.Info("%s Service : Dynamic backends are defined", service)
//Initializing backends
remotes = backendHandler(backendUrl, service, listenPort)
if len(remotes) == 0 {
logger.Warn("%s Service : Error while initializing Dynamic Backend, switching in static mode", service)
} else {
// Consider dynamic configuration is working so disabling static mode
static = false
backendTicker := time.NewTicker(time.Millisecond * 1000)
go func() {
for {
select {
case <-backendTicker.C:
tmpRemotes := make([]string, 0)
tmpRemotes = backendHandler(backendUrl, service, listenPort)
if len(tmpRemotes) > 0 {
remotes = tmpRemotes
}
}
}
}()
}
}
if static {
logger.Info("%s Service : Static backends will be used", service)
remotes = config.GetPaths(fmt.Sprintf("services.%s.remote", service))
}
for {
if source, err := listener.AcceptTCP(); err == nil {
remotes := config.GetPaths(fmt.Sprintf("services.%s.remote", service))
logger.Info("%s Service : Start Listening on port %v", service, listenPort)
if len(remotes) > 0 {
go func() {
remote := config.GetString(remotes[rand.Int31n(int32(len(remotes)))], "")
remote := remotes[rand.Int31n(int32(len(remotes)))]
if target, err := net.DialTimeout("tcp", remote,
time.Second*time.Duration(config.GetDurationBounds(fmt.Sprintf("services.%s.connect_timeout", service), 10, 2, 60))); err == nil {
incomingSize := config.GetSizeBounds(fmt.Sprintf("services.%s.incoming_buffer_size", service), 64*1024, 4*1024, 512*1024)
Expand All @@ -62,19 +104,20 @@ func serviceHandler(service string, listener *net.TCPListener) {
target.(*net.TCPConn).SetReadBuffer(int(outgoingSize))
target.(*net.TCPConn).SetWriteBuffer(int(outgoingSize))
session := &Session{
id: fmt.Sprintf("%x", md5.Sum([]byte(fmt.Sprintf("%s%s", source.RemoteAddr(), target.RemoteAddr())))),
service: service,
source: fmt.Sprintf("%s", source.RemoteAddr()),
target: fmt.Sprintf("%s", target.RemoteAddr()),
started: time.Now(),
active: time.Now(),
last: time.Time{},
meta: "-",
abort: make(chan bool, 1),
id: fmt.Sprintf("%x", md5.Sum([]byte(fmt.Sprintf("%s%s", source.RemoteAddr(), target.RemoteAddr())))),
service: service,
source: fmt.Sprintf("%s", source.RemoteAddr()),
target: fmt.Sprintf("%s", target.RemoteAddr()),
targetName: strings.Split(remote, ":")[0],
started: time.Now(),
active: time.Now(),
last: time.Time{},
meta: "-",
abort: make(chan bool, 1),
}
if logMinimumSize == 0 {
session.loggued = true
logger.Info(map[string]interface{}{"type": "splice", "id": session.id, "service": service, "source": session.source, "target": session.target})
logger.Info(map[string]interface{}{"type": "splice", "id": session.id, "service": service, "source": session.source, "target": session.target, "targetName": session.targetName})
}
if sessionMinimumSize == 0 {
statistics <- session
Expand Down Expand Up @@ -106,7 +149,7 @@ func serviceHandler(service string, listener *net.TCPListener) {
session.targetWritten += int64(written)
}
if err != nil {
logger.Warn(map[string]interface{}{"type": "error", "id": session.id, "service": service, "source": session.source, "target": session.target, "error": "target write timeout"})
logger.Warn(map[string]interface{}{"type": "error", "id": session.id, "service": service, "source": session.source, "target": session.target, "targetName": session.targetName, "error": "target write timeout"})
break
}
}
Expand Down Expand Up @@ -156,7 +199,7 @@ func serviceHandler(service string, listener *net.TCPListener) {
}
if !session.loggued && (session.targetWritten >= logMinimumSize || session.sourceWritten >= logMinimumSize) {
session.loggued = true
logger.Info(map[string]interface{}{"type": "splice", "id": session.id, "service": service, "source": session.source, "target": session.target})
logger.Info(map[string]interface{}{"type": "splice", "id": session.id, "service": service, "source": session.source, "target": session.target, "targetName": session.targetName})
}
if (session.targetWritten >= sessionMinimumSize || session.sourceWritten >= sessionMinimumSize) && time.Now().Sub(session.last) >= time.Second*2 {
session.last = time.Now()
Expand Down Expand Up @@ -212,15 +255,16 @@ func monitorHandler(response http.ResponseWriter, request *http.Request) {
sessionsLock.RLock()
for id, session := range sessions {
s[id] = map[string]interface{}{
"started": session.started.Unix(),
"duration": time.Now().Sub(session.started) / time.Second,
"source": session.source,
"target": session.target,
"bytes": [2]int64{session.sourceRead, session.targetRead},
"mean": [2]float64{session.sourceMeanThroughput, session.targetMeanThroughput},
"last": [2]float64{session.sourceLastThroughput, session.targetLastThroughput},
"meta": session.meta,
"done": session.done,
"started": session.started.Unix(),
"duration": time.Now().Sub(session.started) / time.Second,
"source": session.source,
"target": session.target,
"targetName": session.targetName,
"bytes": [2]int64{session.sourceRead, session.targetRead},
"mean": [2]float64{session.sourceMeanThroughput, session.targetMeanThroughput},
"last": [2]float64{session.sourceLastThroughput, session.targetLastThroughput},
"meta": session.meta,
"done": session.done,
}
}
sessionsLock.RUnlock()
Expand All @@ -244,7 +288,8 @@ func monitorHandler(response http.ResponseWriter, request *http.Request) {
sessionsLock.RUnlock()
} else {
response.Header().Set("Content-Type", "text/html; charset=utf-8")
response.Write(monitorContent)
monitorFile, _ := ioutil.ReadFile("monitor.html")
response.Write(monitorFile)
}
}

Expand Down Expand Up @@ -296,6 +341,36 @@ func baseHandler(next http.Handler) http.Handler {
})
}

func backendHandler(backendUrl string, service string, port int) []string {
backends := make([]Backend, 0)
backendArray := make([]string, 0)
//Makes HTTP request
resp, err := http.Get(backendUrl)
defer resp.Body.Close()
if err != nil {
logger.Warn("%s Service : %s", service, err)
return backendArray
}
// Parses JSON response into
err = json.NewDecoder(resp.Body).Decode(&backends)
if err != nil {
logger.Warn("%s Service : %s", service, err)
return backendArray
}
// Converts Backend Array to String Array Containing URLs
for _, backend := range backends {
if backend.Port == 0 {
backend.Port = port
}
var backendRTMPUrl bytes.Buffer
backendRTMPUrl.WriteString(backend.Fqdn)
backendRTMPUrl.WriteString(":")
backendRTMPUrl.WriteString(strconv.Itoa(backend.Port))
backendArray = append(backendArray, backendRTMPUrl.String())
}
return backendArray
}

func main() {
var err error

Expand Down Expand Up @@ -349,7 +424,7 @@ func main() {
case session := <-statistics:
sessionsLock.Lock()
if sessions[session.id] == nil {
sessions[session.id] = &Session{service: session.service, source: session.source, target: session.target, started: session.started, abort: session.abort}
sessions[session.id] = &Session{service: session.service, source: session.source, target: session.target, targetName: session.targetName, started: session.started, abort: session.abort}
}
sessionsLock.Unlock()
duration := math.Max(float64(time.Now().Sub(session.started))/float64(time.Second), 0.001)
Expand Down