1
0
mirror of https://github.com/bingohuang/docker-labs.git synced 2025-07-14 01:57:32 +08:00

Add reverse proxy endpoint.

It works by using the Host of the request. When it receives something in
the form of: `<node>.<session>.play-with-docker.com` it does a reverse
proxy http request to `node`, validating that the `node` actually belongs
to the `session`.
If the node has a prefix `ip` and continues with a valid IP address
where the dots where replaces by underscores (like `ip10_0_0_1`) then it
will remove the `ip` prefix and and replace the underscores by dots, and
assume it is an ip address.
This commit is contained in:
Jonathan Leibiusky @xetorthio 2016-11-17 17:37:40 -03:00
parent a85bb4a1d7
commit ec9d34ffda
4 changed files with 57 additions and 0 deletions

3
api.go
View File

@ -59,6 +59,9 @@ func main() {
r.Handle("/sessions/{sessionId}/ws/", server)
// Reverse proxy
r.Host(`{node}.{session}.play-with-docker.com`).Handler(handlers.NewMultipleHostReverseProxy())
n := negroni.Classic()
n.UseHandler(r)

37
handlers/reverseproxy.go Normal file
View File

@ -0,0 +1,37 @@
package handlers
import (
"net"
"net/http"
"net/http/httputil"
"strings"
"github.com/gorilla/mux"
)
func NewMultipleHostReverseProxy() *httputil.ReverseProxy {
director := func(req *http.Request) {
v := mux.Vars(req)
node := v["node"]
if strings.HasPrefix(node, "ip") {
// Node is actually an ip, need to convert underscores by dots.
ip := strings.Replace(strings.TrimPrefix(node, "ip"), "_", ".", -1)
if net.ParseIP(ip) == nil {
// Not a valid IP, so treat this is a hostname.
} else {
node = ip
}
}
// Validate that the node actually exists in the network
// TODO:
// Only proxy http for now
req.URL.Scheme = "http"
req.URL.Host = node
}
return &httputil.ReverseProxy{Director: director}
}

View File

@ -52,6 +52,17 @@ func CreateNetwork(name string) error {
return nil
}
func ConnectNetwork(containerId, networkId string) error {
err := c.NetworkConnect(context.Background(), networkId, containerId, &network.EndpointSettings{})
if err != nil {
log.Printf("Connection container to network err [%s]\n", err)
return err
}
return nil
}
func DeleteNetwork(id string) error {
err := c.NetworkRemove(context.Background(), id)

View File

@ -109,6 +109,12 @@ func NewSession() (*Session, error) {
return nil, err
}
// Connect PWD daemon to the new network
if err := ConnectNetwork("pwd", s.Id); err != nil {
log.Println("ERROR NETWORKING")
return nil, err
}
// We store sessions as soon as we create one so we don't delete new sessions on an api restart
if err := saveSessionsToDisk(); err != nil {
return nil, err