Skip to content

Commit

Permalink
switch proxy matcher usage, add random selection
Browse files Browse the repository at this point in the history
  • Loading branch information
umputun committed May 16, 2021
1 parent 2d3a796 commit 9f1f440
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 4 deletions.
2 changes: 1 addition & 1 deletion app/discovery/discovery.go
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,7 @@ func (s *Service) Match(srv, src string) (res Matches) {
}
}

return Matches{MTProxy, nil}
return res
}

// ScheduleHealthCheck starts background loop with health-check
Expand Down
31 changes: 28 additions & 3 deletions app/proxy/proxy.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"
"fmt"
"io"
"math/rand"
"net"
"net/http"
"net/http/httputil"
Expand Down Expand Up @@ -44,7 +45,7 @@ type Http struct { // nolint golint
// Matcher source info (server and route) to the destination url
// If no match found return ok=false
type Matcher interface {
Match(srv, src string) (string, discovery.MatchType, bool)
Match(srv, src string) (res discovery.Matches)
Servers() (servers []string)
Mappers() (mappers []discovery.URLMapper)
CheckHealth() (pingResult map[string]error)
Expand Down Expand Up @@ -111,6 +112,8 @@ func (h *Http) Run(ctx context.Context) error {
h.gzipHandler(),
)

rand.Seed(time.Now().UnixNano())

if len(h.SSLConfig.FQDNs) == 0 && h.SSLConfig.SSLMode == SSLAuto {
// discovery async and may happen not right away. Try to get servers for some time
for i := 0; i < 100; i++ {
Expand Down Expand Up @@ -201,7 +204,8 @@ func (h *Http) proxyHandler() http.HandlerFunc {
if server == "" {
server = strings.Split(r.Host, ":")[0]
}
u, mt, ok := h.Match(server, r.URL.Path)
matches := h.Match(server, r.URL.Path) // get all matches for the server:path pair
u, ok := h.getMatch(matches)
if !ok { // no route match
if h.isAssetRequest(r) {
assetsHandler.ServeHTTP(w, r)
Expand All @@ -212,7 +216,7 @@ func (h *Http) proxyHandler() http.HandlerFunc {
return
}

switch mt {
switch matches.MatchType {
case discovery.MTProxy:
uu, err := url.Parse(u)
if err != nil {
Expand All @@ -239,6 +243,27 @@ func (h *Http) proxyHandler() http.HandlerFunc {
}
}

func (h *Http) getMatch(mm discovery.Matches) (u string, ok bool) {
if len(mm.Routes) == 0 {
return "", false
}

var urls []string
for _, m := range mm.Routes {
if m.Alive {
urls = append(urls, m.Destination)
}
}
switch len(urls) {
case 0:
return "", false
case 1:
return urls[0], true
default:
return urls[rand.Intn(len(urls)-1)], true
}
}

func (h *Http) assetsHandler() http.HandlerFunc {
if h.AssetsLocation == "" || h.AssetsWebRoot == "" {
return func(writer http.ResponseWriter, request *http.Request) {}
Expand Down

0 comments on commit 9f1f440

Please sign in to comment.