TUN-3492: Refactor OriginService, shrink its interface

This commit is contained in:
Adam Chalmers
2020-10-30 16:37:40 -05:00
parent 18c359cb86
commit d01770107e
12 changed files with 214 additions and 185 deletions

View File

@@ -1,24 +1,17 @@
package ingress
import (
"context"
"crypto/tls"
"fmt"
"net"
"net/http"
"net/url"
"regexp"
"strings"
"sync"
"time"
"github.com/pkg/errors"
"github.com/urfave/cli/v2"
"github.com/cloudflare/cloudflared/cmd/cloudflared/config"
"github.com/cloudflare/cloudflared/logger"
"github.com/cloudflare/cloudflared/tlsconfig"
"github.com/cloudflare/cloudflared/validation"
)
var (
@@ -28,82 +21,6 @@ var (
ErrURLIncompatibleWithIngress = errors.New("You can't set the --url flag (or $TUNNEL_URL) when using multiple-origin ingress rules")
)
// Finalize the rules by adding missing struct fields and validating each origin.
func (ing *Ingress) setHTTPTransport(logger logger.Service) error {
for ruleNumber, rule := range ing.Rules {
cfg := rule.Config
originCertPool, err := tlsconfig.LoadOriginCA(cfg.CAPool, nil)
if err != nil {
return errors.Wrap(err, "Error loading cert pool")
}
httpTransport := &http.Transport{
Proxy: http.ProxyFromEnvironment,
MaxIdleConns: cfg.KeepAliveConnections,
MaxIdleConnsPerHost: cfg.KeepAliveConnections,
IdleConnTimeout: cfg.KeepAliveTimeout,
TLSHandshakeTimeout: cfg.TLSTimeout,
ExpectContinueTimeout: 1 * time.Second,
TLSClientConfig: &tls.Config{RootCAs: originCertPool, InsecureSkipVerify: cfg.NoTLSVerify},
}
if _, isHelloWorld := rule.Service.(*HelloWorld); !isHelloWorld && cfg.OriginServerName != "" {
httpTransport.TLSClientConfig.ServerName = cfg.OriginServerName
}
dialer := &net.Dialer{
Timeout: cfg.ConnectTimeout,
KeepAlive: cfg.TCPKeepAlive,
}
if cfg.NoHappyEyeballs {
dialer.FallbackDelay = -1 // As of Golang 1.12, a negative delay disables "happy eyeballs"
}
// DialContext depends on which kind of origin is being used.
dialContext := dialer.DialContext
switch service := rule.Service.(type) {
// If this origin is a unix socket, enforce network type "unix".
case UnixSocketPath:
httpTransport.DialContext = func(ctx context.Context, _, _ string) (net.Conn, error) {
return dialContext(ctx, "unix", service.Address())
}
// Otherwise, use the regular network config.
default:
httpTransport.DialContext = dialContext
}
ing.Rules[ruleNumber].HTTPTransport = httpTransport
ing.Rules[ruleNumber].ClientTLSConfig = httpTransport.TLSClientConfig
}
// Validate each origin
for _, rule := range ing.Rules {
// If tunnel running in bastion mode, a connection to origin will not exist until initiated by the client.
if rule.Config.BastionMode {
continue
}
// Unix sockets don't have validation
if _, ok := rule.Service.(UnixSocketPath); ok {
continue
}
switch service := rule.Service.(type) {
case UnixSocketPath:
continue
case *HelloWorld:
continue
default:
if err := validation.ValidateHTTPService(service.Address(), rule.Hostname, rule.HTTPTransport); err != nil {
logger.Errorf("unable to connect to the origin: %s", err)
}
}
}
return nil
}
// FindMatchingRule returns the index of the Ingress Rule which matches the given
// hostname and path. This function assumes the last rule matches everything,
// which is the case if the rules were instantiated via the ingress#Validate method
@@ -154,14 +71,13 @@ func NewSingleOrigin(c *cli.Context, compatibilityMode bool, logger logger.Servi
},
defaults: originRequestFromSingeRule(c),
}
err = ing.setHTTPTransport(logger)
return ing, err
}
// Get a single origin service from the CLI/config.
func parseSingleOriginService(c *cli.Context, compatibilityMode bool) (OriginService, error) {
if c.IsSet("hello-world") {
return new(HelloWorld), nil
return new(helloWorld), nil
}
if c.IsSet("url") {
originURLStr, err := config.ValidateUrl(c, compatibilityMode)
@@ -172,14 +88,14 @@ func parseSingleOriginService(c *cli.Context, compatibilityMode bool) (OriginSer
if err != nil {
return nil, errors.Wrap(err, "couldn't parse origin URL")
}
return &URL{URL: originURL, RootURL: originURL}, nil
return &localService{URL: originURL, RootURL: originURL}, nil
}
if c.IsSet("unix-socket") {
unixSocket, err := config.ValidateUnixSocket(c)
path, err := config.ValidateUnixSocket(c)
if err != nil {
return nil, errors.Wrap(err, "Error validating --unix-socket")
}
return UnixSocketPath(unixSocket), nil
return &unixSocketPath{path: path}, nil
}
return nil, errors.New("You must either set ingress rules in your config file, or use --url or use --unix-socket")
}
@@ -192,7 +108,7 @@ func (ing Ingress) IsEmpty() bool {
// StartOrigins will start any origin services managed by cloudflared, e.g. proxy servers or Hello World.
func (ing Ingress) StartOrigins(wg *sync.WaitGroup, log logger.Service, shutdownC <-chan struct{}, errC chan error) error {
for _, rule := range ing.Rules {
if err := rule.Service.Start(wg, log, shutdownC, errC, rule.Config); err != nil {
if err := rule.Service.start(wg, log, shutdownC, errC, rule.Config); err != nil {
return err
}
}
@@ -209,11 +125,12 @@ func validate(ingress []config.UnvalidatedIngressRule, defaults OriginRequestCon
for i, r := range ingress {
var service OriginService
if strings.HasPrefix(r.Service, "unix:") {
if prefix := "unix:"; strings.HasPrefix(r.Service, prefix) {
// No validation necessary for unix socket filepath services
service = UnixSocketPath(strings.TrimPrefix(r.Service, "unix:"))
path := strings.TrimPrefix(r.Service, prefix)
service = &unixSocketPath{path: path}
} else if r.Service == "hello_world" || r.Service == "hello-world" || r.Service == "helloworld" {
service = new(HelloWorld)
service = new(helloWorld)
} else {
// Validate URL services
u, err := url.Parse(r.Service)
@@ -228,7 +145,7 @@ func validate(ingress []config.UnvalidatedIngressRule, defaults OriginRequestCon
if u.Path != "" {
return Ingress{}, fmt.Errorf("%s is an invalid address, ingress rules don't support proxying to a different path on the origin service. The path will be the same as the eyeball request's path", r.Service)
}
serviceURL := URL{URL: u}
serviceURL := localService{URL: u}
service = &serviceURL
}
@@ -262,7 +179,7 @@ func validate(ingress []config.UnvalidatedIngressRule, defaults OriginRequestCon
Hostname: r.Hostname,
Service: service,
Path: pathRegex,
Config: SetConfig(defaults, r.OriginRequest),
Config: setConfig(defaults, r.OriginRequest),
}
}
return Ingress{Rules: rules, defaults: defaults}, nil
@@ -279,20 +196,10 @@ func (e errRuleShouldNotBeCatchAll) Error() string {
"will never be triggered.", e.i+1, e.hostname)
}
// ParseIngress parses, validates and initializes HTTP transports to each origin.
func ParseIngress(conf *config.Configuration, logger logger.Service) (Ingress, error) {
ing, err := ParseIngressDryRun(conf)
if err != nil {
return Ingress{}, err
}
err = ing.setHTTPTransport(logger)
return ing, err
}
// ParseIngressDryRun parses ingress rules, but does not send HTTP requests to the origins.
func ParseIngressDryRun(conf *config.Configuration) (Ingress, error) {
// ParseIngress parses ingress rules, but does not send HTTP requests to the origins.
func ParseIngress(conf *config.Configuration) (Ingress, error) {
if len(conf.Ingress) == 0 {
return Ingress{}, ErrNoIngressRules
}
return validate(conf.Ingress, OriginRequestFromYAML(conf.OriginRequest))
return validate(conf.Ingress, originRequestFromYAML(conf.OriginRequest))
}