2015-05-03 13:20:36 +08:00
|
|
|
package proxy
|
|
|
|
|
|
|
|
import (
|
2016-06-04 03:34:31 +08:00
|
|
|
"fmt"
|
2015-05-03 13:20:36 +08:00
|
|
|
"io"
|
|
|
|
"io/ioutil"
|
|
|
|
"net/http"
|
2015-05-05 10:58:18 +08:00
|
|
|
"net/url"
|
2015-11-17 00:22:06 +08:00
|
|
|
"path"
|
2015-05-05 10:58:18 +08:00
|
|
|
"strconv"
|
|
|
|
"strings"
|
2015-05-03 13:20:36 +08:00
|
|
|
"time"
|
2015-05-25 08:58:17 +08:00
|
|
|
|
2015-10-27 03:34:31 +08:00
|
|
|
"github.com/mholt/caddy/caddy/parse"
|
2015-11-17 00:22:06 +08:00
|
|
|
"github.com/mholt/caddy/middleware"
|
2015-05-03 13:20:36 +08:00
|
|
|
)
|
|
|
|
|
2015-05-31 02:34:54 +08:00
|
|
|
var (
|
2015-10-10 06:35:34 +08:00
|
|
|
supportedPolicies = make(map[string]func() Policy)
|
2015-05-31 02:34:54 +08:00
|
|
|
)
|
2015-05-29 06:56:11 +08:00
|
|
|
|
2015-05-05 10:58:18 +08:00
|
|
|
type staticUpstream struct {
|
2016-01-23 11:18:10 +08:00
|
|
|
from string
|
2016-05-01 03:41:30 +08:00
|
|
|
upstreamHeaders http.Header
|
|
|
|
downstreamHeaders http.Header
|
2016-01-23 11:18:10 +08:00
|
|
|
Hosts HostPool
|
|
|
|
Policy Policy
|
|
|
|
insecureSkipVerify bool
|
2015-05-03 13:20:36 +08:00
|
|
|
|
|
|
|
FailTimeout time.Duration
|
|
|
|
MaxFails int32
|
2016-03-08 22:24:00 +08:00
|
|
|
MaxConns int64
|
2015-05-03 13:20:36 +08:00
|
|
|
HealthCheck struct {
|
|
|
|
Path string
|
|
|
|
Interval time.Duration
|
|
|
|
}
|
2015-06-04 21:57:39 +08:00
|
|
|
WithoutPathPrefix string
|
2015-11-17 00:22:06 +08:00
|
|
|
IgnoredSubPaths []string
|
2015-05-03 13:20:36 +08:00
|
|
|
}
|
|
|
|
|
2015-05-25 08:58:17 +08:00
|
|
|
// NewStaticUpstreams parses the configuration input and sets up
|
2015-05-05 10:58:18 +08:00
|
|
|
// static upstreams for the proxy middleware.
|
|
|
|
func NewStaticUpstreams(c parse.Dispenser) ([]Upstream, error) {
|
|
|
|
var upstreams []Upstream
|
|
|
|
for c.Next() {
|
|
|
|
upstream := &staticUpstream{
|
2016-05-01 03:41:30 +08:00
|
|
|
from: "",
|
|
|
|
upstreamHeaders: make(http.Header),
|
|
|
|
downstreamHeaders: make(http.Header),
|
|
|
|
Hosts: nil,
|
|
|
|
Policy: &Random{},
|
|
|
|
FailTimeout: 10 * time.Second,
|
|
|
|
MaxFails: 1,
|
|
|
|
MaxConns: 0,
|
2015-05-05 10:58:18 +08:00
|
|
|
}
|
2015-05-31 02:34:54 +08:00
|
|
|
|
2015-05-05 10:58:18 +08:00
|
|
|
if !c.Args(&upstream.from) {
|
|
|
|
return upstreams, c.ArgErr()
|
|
|
|
}
|
2016-06-04 03:34:31 +08:00
|
|
|
|
|
|
|
var to []string
|
|
|
|
for _, t := range c.RemainingArgs() {
|
|
|
|
parsed, err := parseUpstream(t)
|
|
|
|
if err != nil {
|
|
|
|
return upstreams, err
|
|
|
|
}
|
|
|
|
to = append(to, parsed...)
|
2015-05-05 10:58:18 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
for c.NextBlock() {
|
2016-06-04 03:34:31 +08:00
|
|
|
switch c.Val() {
|
|
|
|
case "upstream":
|
|
|
|
if !c.NextArg() {
|
|
|
|
return upstreams, c.ArgErr()
|
|
|
|
}
|
|
|
|
parsed, err := parseUpstream(c.Val())
|
|
|
|
if err != nil {
|
|
|
|
return upstreams, err
|
|
|
|
}
|
|
|
|
to = append(to, parsed...)
|
|
|
|
default:
|
|
|
|
if err := parseBlock(&c, upstream); err != nil {
|
|
|
|
return upstreams, err
|
|
|
|
}
|
2015-05-05 10:58:18 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-06-04 03:34:31 +08:00
|
|
|
if len(to) == 0 {
|
|
|
|
return upstreams, c.ArgErr()
|
|
|
|
}
|
|
|
|
|
2015-05-05 10:58:18 +08:00
|
|
|
upstream.Hosts = make([]*UpstreamHost, len(to))
|
|
|
|
for i, host := range to {
|
2016-03-10 22:45:23 +08:00
|
|
|
uh, err := upstream.NewHost(host)
|
|
|
|
if err != nil {
|
2015-05-05 10:58:18 +08:00
|
|
|
return upstreams, err
|
|
|
|
}
|
|
|
|
upstream.Hosts[i] = uh
|
|
|
|
}
|
|
|
|
|
|
|
|
if upstream.HealthCheck.Path != "" {
|
|
|
|
go upstream.HealthCheckWorker(nil)
|
|
|
|
}
|
|
|
|
upstreams = append(upstreams, upstream)
|
|
|
|
}
|
|
|
|
return upstreams, nil
|
|
|
|
}
|
|
|
|
|
2015-05-29 06:56:11 +08:00
|
|
|
// RegisterPolicy adds a custom policy to the proxy.
|
2015-05-29 07:53:54 +08:00
|
|
|
func RegisterPolicy(name string, policy func() Policy) {
|
|
|
|
supportedPolicies[name] = policy
|
2015-05-29 06:56:11 +08:00
|
|
|
}
|
|
|
|
|
2015-05-05 10:58:18 +08:00
|
|
|
func (u *staticUpstream) From() string {
|
|
|
|
return u.from
|
2015-05-03 13:20:36 +08:00
|
|
|
}
|
|
|
|
|
2016-03-10 22:45:23 +08:00
|
|
|
func (u *staticUpstream) NewHost(host string) (*UpstreamHost, error) {
|
|
|
|
if !strings.HasPrefix(host, "http") &&
|
|
|
|
!strings.HasPrefix(host, "unix:") {
|
|
|
|
host = "http://" + host
|
|
|
|
}
|
|
|
|
uh := &UpstreamHost{
|
2016-05-01 03:41:30 +08:00
|
|
|
Name: host,
|
|
|
|
Conns: 0,
|
|
|
|
Fails: 0,
|
|
|
|
FailTimeout: u.FailTimeout,
|
|
|
|
Unhealthy: false,
|
|
|
|
UpstreamHeaders: u.upstreamHeaders,
|
|
|
|
DownstreamHeaders: u.downstreamHeaders,
|
2016-03-10 22:45:23 +08:00
|
|
|
CheckDown: func(u *staticUpstream) UpstreamHostDownFunc {
|
|
|
|
return func(uh *UpstreamHost) bool {
|
|
|
|
if uh.Unhealthy {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
if uh.Fails >= u.MaxFails &&
|
|
|
|
u.MaxFails != 0 {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
}(u),
|
|
|
|
WithoutPathPrefix: u.WithoutPathPrefix,
|
|
|
|
MaxConns: u.MaxConns,
|
|
|
|
}
|
|
|
|
|
|
|
|
baseURL, err := url.Parse(uh.Name)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
uh.ReverseProxy = NewSingleHostReverseProxy(baseURL, uh.WithoutPathPrefix)
|
|
|
|
if u.insecureSkipVerify {
|
|
|
|
uh.ReverseProxy.Transport = InsecureTransport
|
|
|
|
}
|
|
|
|
return uh, nil
|
|
|
|
}
|
|
|
|
|
2016-06-04 03:34:31 +08:00
|
|
|
func parseUpstream(u string) ([]string, error) {
|
|
|
|
if !strings.HasPrefix(u, "unix:") {
|
|
|
|
colonIdx := strings.LastIndex(u, ":")
|
|
|
|
protoIdx := strings.Index(u, "://")
|
|
|
|
|
|
|
|
if colonIdx != -1 && colonIdx != protoIdx {
|
|
|
|
us := u[:colonIdx]
|
|
|
|
ports := u[len(us)+1:]
|
|
|
|
if separators := strings.Count(ports, "-"); separators > 1 {
|
|
|
|
return nil, fmt.Errorf("port range [%s] is invalid", ports)
|
|
|
|
} else if separators == 1 {
|
|
|
|
portsStr := strings.Split(ports, "-")
|
|
|
|
pIni, err := strconv.Atoi(portsStr[0])
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
pEnd, err := strconv.Atoi(portsStr[1])
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
if pEnd <= pIni {
|
|
|
|
return nil, fmt.Errorf("port range [%s] is invalid", ports)
|
|
|
|
}
|
|
|
|
|
|
|
|
hosts := []string{}
|
|
|
|
for p := pIni; p <= pEnd; p++ {
|
|
|
|
hosts = append(hosts, fmt.Sprintf("%s:%d", us, p))
|
|
|
|
}
|
|
|
|
return hosts, nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return []string{u}, nil
|
|
|
|
|
|
|
|
}
|
|
|
|
|
2015-10-10 06:35:34 +08:00
|
|
|
func parseBlock(c *parse.Dispenser, u *staticUpstream) error {
|
|
|
|
switch c.Val() {
|
|
|
|
case "policy":
|
|
|
|
if !c.NextArg() {
|
|
|
|
return c.ArgErr()
|
|
|
|
}
|
|
|
|
policyCreateFunc, ok := supportedPolicies[c.Val()]
|
|
|
|
if !ok {
|
|
|
|
return c.ArgErr()
|
|
|
|
}
|
|
|
|
u.Policy = policyCreateFunc()
|
|
|
|
case "fail_timeout":
|
|
|
|
if !c.NextArg() {
|
|
|
|
return c.ArgErr()
|
|
|
|
}
|
|
|
|
dur, err := time.ParseDuration(c.Val())
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
u.FailTimeout = dur
|
|
|
|
case "max_fails":
|
|
|
|
if !c.NextArg() {
|
|
|
|
return c.ArgErr()
|
|
|
|
}
|
|
|
|
n, err := strconv.Atoi(c.Val())
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
u.MaxFails = int32(n)
|
2016-03-08 22:24:00 +08:00
|
|
|
case "max_conns":
|
|
|
|
if !c.NextArg() {
|
|
|
|
return c.ArgErr()
|
|
|
|
}
|
|
|
|
n, err := strconv.ParseInt(c.Val(), 10, 64)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
u.MaxConns = n
|
2015-10-10 06:35:34 +08:00
|
|
|
case "health_check":
|
|
|
|
if !c.NextArg() {
|
|
|
|
return c.ArgErr()
|
|
|
|
}
|
|
|
|
u.HealthCheck.Path = c.Val()
|
|
|
|
u.HealthCheck.Interval = 30 * time.Second
|
|
|
|
if c.NextArg() {
|
|
|
|
dur, err := time.ParseDuration(c.Val())
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
u.HealthCheck.Interval = dur
|
|
|
|
}
|
2016-05-01 03:41:30 +08:00
|
|
|
case "header_upstream":
|
|
|
|
fallthrough
|
2015-10-10 06:35:34 +08:00
|
|
|
case "proxy_header":
|
|
|
|
var header, value string
|
|
|
|
if !c.Args(&header, &value) {
|
|
|
|
return c.ArgErr()
|
|
|
|
}
|
2016-05-01 03:41:30 +08:00
|
|
|
u.upstreamHeaders.Add(header, value)
|
|
|
|
case "header_downstream":
|
|
|
|
var header, value string
|
|
|
|
if !c.Args(&header, &value) {
|
|
|
|
return c.ArgErr()
|
|
|
|
}
|
|
|
|
u.downstreamHeaders.Add(header, value)
|
2015-10-10 06:35:34 +08:00
|
|
|
case "websocket":
|
2016-05-01 03:41:30 +08:00
|
|
|
u.upstreamHeaders.Add("Connection", "{>Connection}")
|
|
|
|
u.upstreamHeaders.Add("Upgrade", "{>Upgrade}")
|
2015-10-10 06:35:34 +08:00
|
|
|
case "without":
|
|
|
|
if !c.NextArg() {
|
|
|
|
return c.ArgErr()
|
|
|
|
}
|
|
|
|
u.WithoutPathPrefix = c.Val()
|
2015-11-17 00:22:06 +08:00
|
|
|
case "except":
|
|
|
|
ignoredPaths := c.RemainingArgs()
|
|
|
|
if len(ignoredPaths) == 0 {
|
|
|
|
return c.ArgErr()
|
|
|
|
}
|
|
|
|
u.IgnoredSubPaths = ignoredPaths
|
2016-01-23 11:18:10 +08:00
|
|
|
case "insecure_skip_verify":
|
|
|
|
u.insecureSkipVerify = true
|
2015-10-10 06:35:34 +08:00
|
|
|
default:
|
|
|
|
return c.Errf("unknown property '%s'", c.Val())
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2015-05-05 10:58:18 +08:00
|
|
|
func (u *staticUpstream) healthCheck() {
|
2015-05-03 13:20:36 +08:00
|
|
|
for _, host := range u.Hosts {
|
2015-05-25 08:58:17 +08:00
|
|
|
hostURL := host.Name + u.HealthCheck.Path
|
|
|
|
if r, err := http.Get(hostURL); err == nil {
|
2015-05-03 13:20:36 +08:00
|
|
|
io.Copy(ioutil.Discard, r.Body)
|
|
|
|
r.Body.Close()
|
|
|
|
host.Unhealthy = r.StatusCode < 200 || r.StatusCode >= 400
|
|
|
|
} else {
|
|
|
|
host.Unhealthy = true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-05-05 10:58:18 +08:00
|
|
|
func (u *staticUpstream) HealthCheckWorker(stop chan struct{}) {
|
2015-05-03 13:20:36 +08:00
|
|
|
ticker := time.NewTicker(u.HealthCheck.Interval)
|
|
|
|
u.healthCheck()
|
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case <-ticker.C:
|
|
|
|
u.healthCheck()
|
|
|
|
case <-stop:
|
|
|
|
// TODO: the library should provide a stop channel and global
|
|
|
|
// waitgroup to allow goroutines started by plugins a chance
|
|
|
|
// to clean themselves up.
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-05-05 10:58:18 +08:00
|
|
|
func (u *staticUpstream) Select() *UpstreamHost {
|
2015-05-03 13:20:36 +08:00
|
|
|
pool := u.Hosts
|
|
|
|
if len(pool) == 1 {
|
2016-03-10 22:42:19 +08:00
|
|
|
if !pool[0].Available() {
|
2015-05-03 13:20:36 +08:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
return pool[0]
|
|
|
|
}
|
2016-03-10 22:42:19 +08:00
|
|
|
allUnavailable := true
|
2015-05-03 13:20:36 +08:00
|
|
|
for _, host := range pool {
|
2016-03-10 22:42:19 +08:00
|
|
|
if host.Available() {
|
|
|
|
allUnavailable = false
|
2015-05-03 13:20:36 +08:00
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
2016-03-10 22:42:19 +08:00
|
|
|
if allUnavailable {
|
2015-05-03 13:20:36 +08:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
if u.Policy == nil {
|
|
|
|
return (&Random{}).Select(pool)
|
|
|
|
}
|
2015-05-25 08:58:17 +08:00
|
|
|
return u.Policy.Select(pool)
|
2015-05-03 13:20:36 +08:00
|
|
|
}
|
2015-11-17 00:22:06 +08:00
|
|
|
|
2016-03-20 15:02:17 +08:00
|
|
|
func (u *staticUpstream) AllowedPath(requestPath string) bool {
|
2015-11-17 00:22:06 +08:00
|
|
|
for _, ignoredSubPath := range u.IgnoredSubPaths {
|
|
|
|
if middleware.Path(path.Clean(requestPath)).Matches(path.Join(u.From(), ignoredSubPath)) {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return true
|
|
|
|
}
|