/
host.go
243 lines (171 loc) · 4.27 KB
/
host.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
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
/* red-bazaar/http-proxy
* host.go
* mae 02014-02
*/
package main
import (
"sort"
"strings"
"io"
"fmt"
"log"
"time"
"math/rand"
"crypto/md5"
"errors"
"net/http"
"github.com/pmylund/go-cache"
cached "../cache"
)
var (
HostAlreadyPresent = errors.New("Host Already Present")
BackEndAlreadyPresent = errors.New("BackEnd Already Present")
NoBackEndsOnline = errors.New("No BackEnds online")
)
type Host struct {
CName string
BackEnds map[string]*BackEnd
XHeaders []XHeader
/* local cache for session/configuration data */
*cache.Cache
}
/* Weighted Random */
func (host *Host) WeightedBackEnd() (*BackEnd,error) {
if len(host.BackEnds) == 0 {
return nil,NoBackEndsOnline
}
totalWeight := 1 /* must be > 0 */
running := make([]*BackEnd,0)
for _,be := range host.BackEnds {
if be.isOnline() {
running = append(running,be)
totalWeight += be.Weight
}
}
if len(running) == 0 {
return nil,NoBackEndsOnline
}
if len(running) == 1 { /* if we only have the 1 choice, then skip */
return running[0],nil
}
sort.Sort(ByWeight(running))
n := rand.Intn(totalWeight)
for i := len(running) - 1; i >= 0; i-- {
be := running[i]
n -= be.Weight
if n < be.Weight {
return be,nil
}
}
return nil,NoBackEndsOnline
}
func (host *Host) SelectBackEnd() (*BackEnd,error) {
if len(host.BackEnds) == 0 {
return nil,NoBackEndsOnline
}
running := make([]*BackEnd,0)
for _,be := range host.BackEnds {
if be.isOnline() {
running = append(running,be)
}
}
if len(running) == 0 {
return nil,NoBackEndsOnline
}
if len(running) == 1 {
return running[0],nil
}
sort.Sort(ByWeight(running))
return running[0],nil
}
func (host *Host) ServeHTTP(w http.ResponseWriter,req *http.Request) {
w.Header().Set("X-Host",host.CName)
/* read the host, locate a backend
* check for session in cache based on
* ip-address and client agent
*/
userAgent := req.Header.Get("User-Agent")
/* hash the user-agent string into a more compact form */
remotehost := ""
/* strip the port from the host string */
parts := strings.Split(req.Host,":")
if len(parts) != 2 {
remotehost = req.Host
} else {
remotehost = parts[0]
}
h := md5.New()
io.WriteString(h, userAgent)
/* append host ip address to hash of user-agent */
hash := fmt.Sprintf("%x", h.Sum(nil))[:8] + "+" + remotehost
/* lookup a session in the cache */
if x,found := host.Cache.Get(hash); found {
w.Header().Set("X-Session","continue")
/* continue the session with the last backend */
if session,ok := x.(*Session); ok {
/* do a cache lookup of the X-headers + url */
lookup := session.String() + req.URL.String()
if content,ok,_ := cached.Get(lookup); ok {
fmt.Fprintf(w,string(content))
return
}
/* cache miss : */
session.Set(w)
be,err := host.SelectBackEnd()
if err != nil {
http.Error(w,"Service Not Available",503)
return
}
w.Header().Set("X-Served-By",be.RemoteURL.String())
be.ServeHTTP(w,req)
return
}
} /* else lookup a back end to try : */
log.Printf("looking up - %s\n",req.Host)
session := NewSession()
for _,xhead := range host.XHeaders {
session.Add(xhead.Key(),xhead.Set(w))
}
host.Cache.Set(hash,session,0)
/* do a cache lookup */
lookup := session.String() + req.URL.String()
if content,ok,_ := cached.Get(lookup); ok {
fmt.Fprintf(w,string(content))
return
}
/* on cache miss */
be,err := host.SelectBackEnd()
if err != nil {
http.Error(w,"Service Not Available",503)
return
}
w.Header().Set("X-Served-By",be.RemoteURL.String())
be.ServeHTTP(w,req)
}
func (host *Host) AddXHeader(name,value string) error {
xhead,err := ParseXHeader(name,value)
if err != nil {
return err
}
host.XHeaders = append(host.XHeaders,xhead)
return nil
}
func (host *Host) AddBackEnd(url string) (*BackEnd,error) {
if be,exists := host.BackEnds[url]; exists {
return be,BackEndAlreadyPresent
}
be,err := NewBackEnd(url)
if err != nil {
return nil,err
}
host.BackEnds[url] = be
return be,nil
}
func NewHost(cname string) *Host {
h := new(Host)
h.CName = cname
h.BackEnds = make(map[string]*BackEnd,0)
h.XHeaders = make([]XHeader,0)
h.Cache = cache.New(5 * time.Minute,30 * time.Second) /* TODO, add to create */
return h
}