forked from rancher/rancher
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
108 lines (89 loc) · 2.29 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
package main
import (
"flag"
"fmt"
"io"
"net/http"
"strconv"
"sync"
"sync/atomic"
"time"
"github.com/gorilla/mux"
"github.com/rancher/rancher/pkg/remotedialer"
"github.com/sirupsen/logrus"
)
var (
addr string
clients = map[string]*http.Client{}
l sync.Mutex
counter int64
)
func authorizer(req *http.Request) (string, bool, error) {
id := req.Header.Get("x-tunnel-id")
return id, id != "", nil
}
func onError(rw http.ResponseWriter, _ *http.Request, code int, err error) {
rw.WriteHeader(code)
rw.Write([]byte(err.Error()))
}
func ready() bool {
return true
}
func Client(server *remotedialer.Server, rw http.ResponseWriter, req *http.Request) {
timeout := req.URL.Query().Get("timeout")
if timeout == "" {
timeout = "15"
}
vars := mux.Vars(req)
clientKey := vars["id"]
url := fmt.Sprintf("%s://%s%s", vars["scheme"], vars["host"], vars["path"])
client := getClient(server, clientKey, timeout)
id := atomic.AddInt64(&counter, 1)
logrus.Infof("[%03d] REQ t=%s %s", id, timeout, url)
resp, err := client.Get(url)
if err != nil {
logrus.Errorf("[%03d] REQ ERR t=%s %s: %v", id, timeout, url, err)
onError(rw, req, 500, err)
return
}
defer resp.Body.Close()
logrus.Infof("[%03d] REQ OK t=%s %s", id, timeout, url)
rw.WriteHeader(resp.StatusCode)
io.Copy(rw, resp.Body)
logrus.Infof("[%03d] REQ DONE t=%s %s", id, timeout, url)
}
func getClient(server *remotedialer.Server, clientKey, timeout string) *http.Client {
l.Lock()
defer l.Unlock()
key := fmt.Sprintf("%s/%s", clientKey, timeout)
client := clients[key]
if client != nil {
return client
}
dialer := server.Dialer(clientKey, 15*time.Second)
client = &http.Client{
Transport: &http.Transport{
Dial: dialer,
},
}
if timeout != "" {
t, err := strconv.Atoi(timeout)
if err == nil {
client.Timeout = time.Duration(t) * time.Second
}
}
clients[key] = client
return client
}
func main() {
flag.StringVar(&addr, "listen", ":8123", "Listen address")
flag.Parse()
handler := remotedialer.New(authorizer, onError, ready)
router := mux.NewRouter()
router.Handle("/connect", handler)
router.HandleFunc("/client/{id}/{scheme}/{host}{path:.*}", func(rw http.ResponseWriter, req *http.Request) {
Client(handler, rw, req)
})
fmt.Println("Listening on ", addr)
http.ListenAndServe(addr, router)
}