aboutsummaryrefslogtreecommitdiff
path: root/middleware/kubernetes/apiproxy.go
blob: f6d2c00fa73671d1bcdfc6cbc51a662302ed96e6 (plain) (blame)
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
package kubernetes

import (
	"fmt"
	"io"
	"log"
	"net"
	"net/http"

	"github.com/coredns/coredns/middleware/pkg/healthcheck"
)

type proxyHandler struct {
	healthcheck.HealthCheck
}

type apiProxy struct {
	http.Server
	listener net.Listener
	handler  proxyHandler
}

func (p *proxyHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	upstream := p.Select()
	network := "tcp"
	if upstream.Network != "" {
		network = upstream.Network
	}
	address := upstream.Name
	d, err := net.Dial(network, address)
	if err != nil {
		log.Printf("[ERROR] Unable to establish connection to upstream %s://%s: %s", network, address, err)
		http.Error(w, fmt.Sprintf("Unable to establish connection to upstream %s://%s: %s", network, address, err), 500)
		return
	}
	hj, ok := w.(http.Hijacker)
	if !ok {
		log.Printf("[ERROR] Unable to establish connection: no hijacker")
		http.Error(w, "Unable to establish connection: no hijacker", 500)
		return
	}
	nc, _, err := hj.Hijack()
	if err != nil {
		log.Printf("[ERROR] Unable to hijack connection: %s", err)
		http.Error(w, fmt.Sprintf("Unable to hijack connection: %s", err), 500)
		return
	}
	defer nc.Close()
	defer d.Close()

	err = r.Write(d)
	if err != nil {
		log.Printf("[ERROR] Unable to copy connection to upstream %s://%s: %s", network, address, err)
		http.Error(w, fmt.Sprintf("Unable to copy connection to upstream %s://%s: %s", network, address, err), 500)
		return
	}

	errChan := make(chan error, 2)
	cp := func(dst io.Writer, src io.Reader) {
		_, err := io.Copy(dst, src)
		errChan <- err
	}
	go cp(d, nc)
	go cp(nc, d)
	<-errChan
}

func (p *apiProxy) Run() {
	p.handler.Start()
	p.Serve(p.listener)
}

func (p *apiProxy) Stop() {
	p.handler.Stop()
	p.listener.Close()
}