| 1 |
package handlers |
| 2 |
|
| 3 |
import ( |
| 4 |
"bytes" |
| 5 |
"context" |
| 6 |
"errors" |
| 7 |
"io" |
| 8 |
"io/ioutil" |
| 9 |
"log" |
| 10 |
"net/http" |
| 11 |
"net/url" |
| 12 |
"path" |
| 13 |
"strconv" |
| 14 |
|
| 15 |
"github.com/coreos/discovery.etcd.io/handlers/httperror" |
| 16 |
"github.com/prometheus/client_golang/prometheus" |
| 17 |
) |
| 18 |
|
| 19 |
func init() { |
| 20 |
tokenCounter = prometheus.NewCounterVec( |
| 21 |
prometheus.CounterOpts{ |
| 22 |
Name: "endpoint_token_requests_total", |
| 23 |
Help: "How many /token requests processed, partitioned by status code and HTTP method.", |
| 24 |
}, |
| 25 |
[]string{"code", "method"}, |
| 26 |
) |
| 27 |
prometheus.MustRegister(tokenCounter) |
| 28 |
} |
| 29 |
|
| 30 |
var tokenCounter *prometheus.CounterVec |
| 31 |
|
| 32 |
func (st *State) proxyRequest(r *http.Request) (*http.Response, error) { |
| 33 |
body, _ := ioutil.ReadAll(r.Body) |
| 34 |
|
| 35 |
for i := 0; i <= 10; i++ { |
| 36 |
u := url.URL{ |
| 37 |
Scheme: "http", |
| 38 |
Host: st.getCurrentLeader(), |
| 39 |
Path: path.Join("v2", "keys", "_etcd", "registry", r.URL.Path), |
| 40 |
RawQuery: r.URL.RawQuery, |
| 41 |
} |
| 42 |
|
| 43 |
buf := bytes.NewBuffer(body) |
| 44 |
outreq, err := http.NewRequest(r.Method, u.String(), buf) |
| 45 |
if err != nil { |
| 46 |
return nil, err |
| 47 |
} |
| 48 |
|
| 49 |
copyHeader(outreq.Header, r.Header) |
| 50 |
|
| 51 |
client := http.Client{} |
| 52 |
resp, err := client.Do(outreq) |
| 53 |
if err != nil { |
| 54 |
return nil, err |
| 55 |
} |
| 56 |
|
| 57 |
|
| 58 |
if resp.StatusCode == 307 && |
| 59 |
(r.Method == "PUT" || r.Method == "DELETE") { |
| 60 |
u, err := resp.Location() |
| 61 |
if err != nil { |
| 62 |
return nil, err |
| 63 |
} |
| 64 |
st.setCurrentLeader(u.Host) |
| 65 |
continue |
| 66 |
} |
| 67 |
|
| 68 |
return resp, nil |
| 69 |
} |
| 70 |
|
| 71 |
return nil, errors.New("All attempts at proxying to etcd failed") |
| 72 |
} |
| 73 |
|
| 74 |
|
| 75 |
func copyHeader(dst, src http.Header) { |
| 76 |
for k, v := range src { |
| 77 |
for _, q := range v { |
| 78 |
dst.Add(k, q) |
| 79 |
} |
| 80 |
} |
| 81 |
} |
| 82 |
|
| 83 |
func TokenHandler(ctx context.Context, w http.ResponseWriter, r *http.Request) { |
| 84 |
st := ctx.Value(stateKey).(*State) |
| 85 |
|
| 86 |
resp, err := st.proxyRequest(r) |
| 87 |
if err != nil { |
| 88 |
log.Printf("Error making request: %v", err) |
| 89 |
httperror.Error(w, r, "", 500, tokenCounter) |
| 90 |
} |
| 91 |
|
| 92 |
copyHeader(w.Header(), resp.Header) |
| 93 |
w.WriteHeader(resp.StatusCode) |
| 94 |
io.Copy(w, resp.Body) |
| 95 |
tokenCounter.WithLabelValues(strconv.Itoa(resp.StatusCode), r.Method).Add(1) |
| 96 |
} |