Merge pull request #8 from integration-system/websocket_proxy

add websocket proxy
This commit is contained in:
Yan authored and GitHub committed 2019-12-13 17:56:58 +03:00
commit bdb0c50a22
10 files changed
+229 -8

No files matched your search

+1 -1
View File
@@ -1 +1 @@
2.1.0
2.2.0
+2
View File
@@ -1,3 +1,5 @@
## 2.2.0
* add websocket proxy
## 2.1.0
* fix proxy path
* add skip authenticate
Generated
+20 -3
View File
@@ -41,6 +41,14 @@
revision = "06ea1031745cb8b3dab3f6a236daf2b0aa468b7e"
version = "v3.2.0"
[[projects]]
branch = "master"
digest = "1:35e6ba92e1d4e89f4dc51b9868a5d35c3a03d9d2ffc956380502835cf0812a73"
name = "github.com/fasthttp/websocket"
packages = ["."]
pruneopts = "UT"
revision = "1e7306f3b587255aa9ddb1d5dd122750e00623cf"
[[projects]]
digest = "1:abeb38ade3f32a92943e5be54f55ed6d6e3b6602761d74b4aab4c9dd45c18abd"
name = "github.com/fsnotify/fsnotify"
@@ -183,7 +191,7 @@
version = "v1.3.0"
[[projects]]
digest = "1:2f0bb39ac14ba6a8b8d3b065e10fbfce9f555bda35935fda71001dbba703b707"
digest = "1:fd6dd9f3a50fce97343298aec27f3748df9ed9fc30abe082bfc01ef6c00f2f8a"
name = "github.com/integration-system/isp-lib"
packages = [
"backend",
@@ -201,8 +209,8 @@
"utils",
]
pruneopts = "UT"
revision = "9ecfa413468d829dce66fe95562b4366b0dfb2a0"
version = "v2.0.0"
revision = "abfa9a9776d64e6d04d495bfe00db8ca4dcbe7fc"
version = "v2.0.1"
[[projects]]
branch = "master"
@@ -378,6 +386,14 @@
pruneopts = "UT"
revision = "cac0b30c2563378d434b5af411844adff8e32960"
[[projects]]
branch = "master"
digest = "1:8232b87605be15cba8bb9b5089d91a79bb678406aa8b48aaf7b582a104aa5b14"
name = "github.com/savsgio/gotils"
packages = ["."]
pruneopts = "UT"
revision = "524bc4f475005d9dbedc1bc77248a07aef318ef0"
[[projects]]
digest = "1:04457f9f6f3ffc5fea48e71d62f2ca256637dee0a04d710288e27e05c8b41976"
name = "github.com/sirupsen/logrus"
@@ -633,6 +649,7 @@
analyzer-version = 1
input-imports = [
"github.com/dgrijalva/jwt-go",
"github.com/fasthttp/websocket",
"github.com/go-pg/pg",
"github.com/go-pg/pg/orm",
"github.com/go-redis/redis",
+4
View File
@@ -32,6 +32,10 @@
name = "github.com/valyala/fasthttp"
branch = "master"
[[override]]
name = "github.com/fasthttp/websocket"
branch = "master"
[prune]
go-tests = true
unused-packages = true
+2
View File
@@ -20,4 +20,6 @@ const (
ErrorClientDatabase = 615
ErrorSnapshotAccounting = 616
ErrorUnloadAccounting = 617
ErrorWebsocketProxy = 618
)
+6
View File
@@ -8,6 +8,7 @@ import (
"isp-gate-service/proxy/grpc"
"isp-gate-service/proxy/health_check"
"isp-gate-service/proxy/http"
"isp-gate-service/proxy/websocket"
"strings"
)
@@ -15,6 +16,7 @@ var store = make(map[string]Proxy)
const (
httpProtocol = "http"
websocketProtocol = "websocket"
grpcProtocol = "grpc"
healthCheckProtocol = "healthсheck"
)
@@ -45,6 +47,10 @@ func Init(protocol, pathPrefix string, skipAuth bool) (Proxy, error) {
proxy := health_check.NewProxy(skipAuth)
store[pathPrefix] = proxy
return proxy, nil
case websocketProtocol:
proxy := websocket.NewProxy(skipAuth)
store[pathPrefix] = proxy
return proxy, nil
default:
return nil, errors.Errorf("unknown protocol '%s'", protocol)
}
+2 -2
View File
@@ -20,7 +20,7 @@ type grpcProxy struct {
skipAuth bool
}
func NewProxy(skiAuth bool) *grpcProxy {
func NewProxy(skipAuth bool) *grpcProxy {
return &grpcProxy{
client: backend.NewRxGrpcClient(
backend.WithDialOptions(
@@ -31,7 +31,7 @@ func NewProxy(skiAuth bool) *grpcProxy {
backend.WithDialingErrorHandler(func(err error) {
log.Errorf(log_code.ErrorClientGrpc, "dialing err: %v", err)
})),
skipAuth: skiAuth,
skipAuth: skipAuth,
}
}
+7 -2
View File
@@ -23,6 +23,10 @@ func NewProxy(skipAuth bool) *httpProxy {
}
func (p *httpProxy) Consumer(addressList []structure.AddressConfiguration) bool {
if len(addressList) == 0 {
p.client = nil
return true
}
addresses := make([]string, len(addressList))
for key, addr := range addressList {
addresses[key] = addr.GetAddress()
@@ -35,7 +39,8 @@ func (p *httpProxy) Consumer(addressList []structure.AddressConfiguration) bool
}
func (p *httpProxy) ProxyRequest(ctx *fasthttp.RequestCtx, path string) domain.ProxyResponse {
if p.client == nil {
client := p.client
if client == nil {
msg := "client undefined"
log.Error(log_code.ErrorClientHttp, msg)
utils.WriteError(ctx, msg, codes.Internal, nil)
@@ -53,7 +58,7 @@ func (p *httpProxy) ProxyRequest(ctx *fasthttp.RequestCtx, path string) domain.P
req.Header.Add("X-Forwarded-For", addr)
}
err := p.client.Do(req, res)
err := client.Do(req, res)
if err != nil {
log.Error(log_code.ErrorClientHttp, err)
}
+28
View File
@@ -0,0 +1,28 @@
package websocket
import (
"github.com/integration-system/isp-lib/structure"
"sync"
)
type RoundRobinAddrs struct {
mu *sync.Mutex
addrs []structure.AddressConfiguration
index int
}
func (u *RoundRobinAddrs) Get() structure.AddressConfiguration {
u.mu.Lock()
u.index = (u.index + 1) % len(u.addrs)
addr := u.addrs[u.index]
u.mu.Unlock()
return addr
}
func NewRoundRobinAddrs(addrs []structure.AddressConfiguration) *RoundRobinAddrs {
return &RoundRobinAddrs{
addrs: addrs,
index: -1,
mu: new(sync.Mutex),
}
}
+157
View File
@@ -0,0 +1,157 @@
package websocket
import (
"errors"
"github.com/fasthttp/websocket"
"github.com/integration-system/isp-lib/structure"
log "github.com/integration-system/isp-log"
"github.com/valyala/fasthttp"
"google.golang.org/grpc/codes"
"io"
"isp-gate-service/domain"
"isp-gate-service/log_code"
"isp-gate-service/utils"
"net"
"net/http"
"net/http/cookiejar"
"net/url"
)
const (
writeBufSize = 4 << 10
readBufSize = 4 << 10
)
// used to filter client request headers
var forbiddenDuplicateHeaders = map[string]struct{}{
"Upgrade": {},
"Connection": {},
"Sec-Websocket-Key": {},
"Sec-Websocket-Version": {},
"Sec-Websocket-Extensions": {},
"Sec-Websocket-Protocol": {},
}
var upgrader = websocket.FastHTTPUpgrader{
ReadBufferSize: readBufSize,
WriteBufferSize: writeBufSize,
CheckOrigin: func(ctx *fasthttp.RequestCtx) bool {
return true
},
}
type websocketProxy struct {
addrs *RoundRobinAddrs
skipAuth bool
}
func NewProxy(skipAuth bool) *websocketProxy {
return &websocketProxy{addrs: nil, skipAuth: skipAuth}
}
func (p *websocketProxy) Consumer(addressList []structure.AddressConfiguration) bool {
if len(addressList) == 0 {
p.addrs = nil
} else {
p.addrs = NewRoundRobinAddrs(addressList)
}
return true
}
func (p *websocketProxy) ProxyRequest(ctx *fasthttp.RequestCtx, path string) domain.ProxyResponse {
addrs := p.addrs
if addrs == nil {
msg := "no available address"
log.Error(log_code.ErrorWebsocketProxy, msg)
utils.WriteError(ctx, msg, codes.Internal, nil)
return domain.Create().
SetRequestBody(ctx.Request.Body()).
SetResponseBody(ctx.Response.Body()).
SetError(errors.New(msg))
}
reqHeaders := fasthttp.RequestHeader{}
ctx.Request.Header.CopyTo(&reqHeaders)
reqHost := string(ctx.Request.URI().Host())
reqScheme := string(ctx.Request.URI().Scheme())
if addr, _, err := net.SplitHostPort(ctx.RemoteAddr().String()); err == nil {
reqHeaders.Add("X-Forwarded-For", addr)
}
err := upgrader.Upgrade(ctx, func(incomingConn *websocket.Conn) {
outgoingDialer := websocket.Dialer{
ReadBufferSize: readBufSize,
WriteBufferSize: writeBufSize,
NetDial: func(network, address string) (net.Conn, error) {
return net.Dial(network, address)
},
}
addr := addrs.Get()
urlAddr := "ws://" + addr.GetAddress() + "/" + path
header := http.Header{}
reqHeaders.VisitAll(func(key, value []byte) {
keyStr := string(key)
if _, forbidden := forbiddenDuplicateHeaders[keyStr]; !forbidden {
header.Add(keyStr, string(value))
}
})
cookie := make([]*http.Cookie, 0)
reqHeaders.VisitAllCookie(func(key, value []byte) {
cookie = append(cookie, &http.Cookie{Domain: reqHost, Name: string(key), Value: string(value)})
})
cookies := &cookiejar.Jar{}
cookies.SetCookies(&url.URL{Host: reqHost, Scheme: reqScheme}, cookie)
outgoingDialer.Jar = cookies
outgoingConn, _, err := outgoingDialer.Dial(urlAddr, header)
if err == nil {
go func() {
_ = p.proxyConn(outgoingConn, incomingConn)
}()
_ = p.proxyConn(incomingConn, outgoingConn)
} else {
log.Errorf(log_code.ErrorWebsocketProxy, "unable to connect to service %s: %v", urlAddr, err)
_ = incomingConn.Close()
}
})
return domain.Create().
SetRequestBody(ctx.Request.Body()).
SetResponseBody(ctx.Response.Body()).
SetError(err)
}
func (p *websocketProxy) SkipAuth() bool {
return p.skipAuth
}
// no-op
func (p *websocketProxy) Close() {
}
func (p *websocketProxy) proxyConn(from, to *websocket.Conn) error {
defer func() {
_ = from.Close()
_ = to.Close()
}()
for {
msgType, reader, err := from.NextReader()
if err != nil {
return err
}
writer, err := to.NextWriter(msgType)
if err != nil {
return err
}
if _, err := io.Copy(writer, reader); err != nil {
return err
}
if err := writer.Close(); err != nil {
return err
}
}
}