zrok/endpoints/backend/http.go

97 lines
2.1 KiB
Go
Raw Normal View History

2022-08-31 20:49:41 +02:00
package backend
2022-07-20 19:18:40 +02:00
import (
"context"
2022-07-21 22:01:39 +02:00
"github.com/openziti-test-kitchen/zrok/util"
"github.com/openziti/sdk-golang/ziti"
"github.com/openziti/sdk-golang/ziti/config"
2022-08-09 19:57:45 +02:00
"github.com/openziti/sdk-golang/ziti/edge"
"github.com/pkg/errors"
2022-08-10 21:16:36 +02:00
"github.com/sirupsen/logrus"
"net"
"net/http"
2022-08-10 21:16:36 +02:00
"net/http/httputil"
"net/url"
"time"
)
2022-08-10 21:16:36 +02:00
type Config struct {
IdentityPath string
EndpointAddress string
Service string
}
2022-08-17 19:21:07 +02:00
type httpBind struct {
2022-08-18 22:57:38 +02:00
cfg *Config
2022-08-09 19:57:45 +02:00
Requests func() int32
listener edge.Listener
handler http.Handler
}
2022-08-17 19:21:07 +02:00
func NewHTTP(cfg *Config) (*httpBind, error) {
options := ziti.ListenOptions{
ConnectTimeout: 5 * time.Minute,
MaxConnections: 64,
}
zcfg, err := config.NewFromFile(cfg.IdentityPath)
if err != nil {
2022-08-09 19:57:45 +02:00
return nil, errors.Wrap(err, "error loading config")
}
2022-07-26 22:00:59 +02:00
listener, err := ziti.NewContextWithConfig(zcfg).ListenWithOptions(cfg.Service, &options)
if err != nil {
2022-08-09 19:57:45 +02:00
return nil, errors.Wrap(err, "error listening")
}
2022-08-17 19:21:07 +02:00
proxy, err := newReverseProxy(cfg.EndpointAddress)
2022-07-21 21:46:14 +02:00
if err != nil {
2022-08-09 19:57:45 +02:00
return nil, err
}
2022-08-09 19:57:45 +02:00
handler := util.NewProxyHandler(proxy)
2022-08-17 19:21:07 +02:00
return &httpBind{
2022-08-18 22:57:38 +02:00
cfg: cfg,
2022-08-09 19:57:45 +02:00
Requests: handler.Requests,
listener: listener,
handler: handler,
}, nil
}
2022-08-18 22:57:38 +02:00
func (self *httpBind) Run() error {
if err := http.Serve(self.listener, self.handler); err != nil {
2022-07-21 21:46:14 +02:00
return err
}
2022-07-21 21:46:14 +02:00
return nil
}
2022-08-10 21:16:36 +02:00
2022-08-17 19:21:07 +02:00
func newReverseProxy(target string) (*httputil.ReverseProxy, error) {
2022-08-10 21:16:36 +02:00
targetURL, err := url.Parse(target)
if err != nil {
return nil, err
}
tpt := http.DefaultTransport.(*http.Transport).Clone()
tpt.DialContext = metricsDial
2022-08-10 21:16:36 +02:00
proxy := httputil.NewSingleHostReverseProxy(targetURL)
proxy.Transport = tpt
2022-08-10 21:16:36 +02:00
director := proxy.Director
proxy.Director = func(req *http.Request) {
director(req)
logrus.Debugf("-> %v", req.URL.String())
req.Header.Set("X-Proxy", "zrok")
}
proxy.ErrorHandler = func(w http.ResponseWriter, r *http.Request, err error) {
logrus.Errorf("error proxying: %v", err)
}
return proxy, nil
}
func metricsDial(_ context.Context, network string, addr string) (net.Conn, error) {
conn, err := net.Dial(network, addr)
if err != nil {
return conn, err
}
return newMetricsConn("self", conn), nil
}