-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathmain.go
167 lines (137 loc) · 3.22 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
package main
import (
"flag"
"fmt"
"log"
"math/rand"
"net/http"
"net/http/httputil"
"net/url"
"os"
"sort"
"strconv"
"strings"
"github.com/pkg/errors"
)
var (
addr string
logger = log.New(os.Stderr, "sillyproxy: ", log.Flags())
)
func init() {
flag.StringVar(&addr, "addr", ":8080", "listen address")
}
func main() {
var (
colors = []string{"blue", "green"}
backends []backend
)
flag.Parse()
if flag.NFlag() > 0 {
colors = append(colors, flag.Args()...)
}
log.Println("colors", colors)
for _, color := range colors {
backend, err := getColorServiceFromEnv(color)
if err != nil {
log.Println(err)
continue
}
backends = append(backends, backend)
}
rp := httputil.ReverseProxy{
Director: weightedDirector(backends...),
ErrorLog: logger,
}
http.HandleFunc("/down", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusBadGateway)
fmt.Fprintln(w, "no backends available")
})
http.Handle("/", &rp)
log.Println("listen", addr)
if err := http.ListenAndServe(addr, nil); err != nil {
log.Fatalln(err)
}
}
func getColorServiceFromEnv(color string) (backend, error) {
color = strings.ToUpper(color)
serviceEnv := fmt.Sprintf("%s", color)
service := os.Getenv(serviceEnv)
serviceWeight := os.Getenv(serviceEnv + "_WEIGHT")
if service == "" {
return backend{}, errors.Errorf("service %v missing in env, set %v", color, serviceEnv)
}
if serviceWeight == "" {
serviceWeight = "1" // default
}
return parseBackend(strings.ToLower(color), service, serviceWeight)
}
type backend struct {
color string
url *url.URL
weight int
}
func parseBackend(color, location, weight string) (backend, error) {
u, err := url.Parse(location)
if err != nil {
return backend{}, err
}
if u.Scheme == "" {
return backend{}, errors.New("scheme required")
}
if u.Host == "" {
return backend{}, errors.New("host required")
}
w, err := strconv.Atoi(weight)
if err != nil {
log.Println("invalid weight", weight)
if weight != "" {
return backend{}, err
}
w = 1
}
return backend{
color: color,
url: u,
weight: w,
}, nil
}
func (b backend) String() string {
return fmt.Sprintf("backend{color: %v, url: %v, weight: %v}", b.color, b.url, b.weight)
}
func weightedDirector(backends ...backend) func(*http.Request) {
var (
cdf []float64
cum float64
)
// build out a cdf for random, weighted selection
for _, backend := range backends {
log.Println(backend)
cum += float64(backend.weight)
cdf = append(cdf, cum)
}
return func(req *http.Request) {
http.DefaultTransport.(*http.Transport).CloseIdleConnections()
req.Close = true // reconnet each time to backend
log.Println(req.Method, req.RequestURI, req.RemoteAddr)
if len(backends) == 0 {
req.URL.Path = "/down"
req.URL.Scheme = "http"
req.URL.Host = req.Host
log.Println("unroutable request")
return
}
var backend backend
if len(backends) == 1 {
backend = backends[0]
} else {
r := cdf[len(cdf)-1] * rand.Float64()
i := sort.SearchFloat64s(cdf, r)
backend = backends[i]
}
logger.Println("selected", backend)
req.URL.Scheme = backend.url.Scheme
req.URL.Host = backend.url.Host
req.URL.Path = backend.url.Path
req.Header.Set("Color", backend.color)
}
}