/
proxy.go
224 lines (186 loc) · 5.53 KB
/
proxy.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
package proxy
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net"
"net/http"
"strings"
"github.com/CenturyLinkLabs/zodiac/endpoint"
log "github.com/Sirupsen/logrus"
"github.com/gorilla/mux"
"github.com/samalba/dockerclient"
)
type ContainerRequest struct {
Name string
CreateOptions []byte
}
type ProxyFactory func(string, endpoint.Endpoint, bool) Proxy
type Proxy interface {
Serve() error
Stop() error
GetRequests() ([]ContainerRequest, error)
}
type HTTPProxy struct {
address string
containerRequests []ContainerRequest
listener *net.TCPListener
errors []error
imageInspectsCount map[string]int
endpoint endpoint.Endpoint
noBuild bool
}
func NewHTTPProxy(listenAt string, endpoint endpoint.Endpoint, noBuild bool) Proxy {
return &HTTPProxy{
address: listenAt,
endpoint: endpoint,
noBuild: noBuild,
}
}
func (p *HTTPProxy) Serve() error {
r := mux.NewRouter()
r.Path("/{apiVersion:v1.1[5-9]}/containers/create").Methods("POST").HandlerFunc(p.create)
r.Path("/{apiVersion:v1.1[5-9]}/containers/{id}/json").Methods("GET").HandlerFunc(p.inspect)
r.Path("/{apiVersion:v1.1[5-9]}/containers/{id}/start").Methods("POST").HandlerFunc(p.start)
r.Path("/{apiVersion:v1.1[5-9]}/containers/json").Methods("GET").HandlerFunc(p.listAll)
r.Path("/{apiVersion:v1.1[5-9]}/images/{id:.*}/json").Methods("GET").HandlerFunc(p.inspectImage)
r.Path("/{apiVersion:v1.1[5-9]}/build").Methods("POST").HandlerFunc(p.build)
r.Path("/{apiVersion:v1.1[5-9]}/images/create").Methods("POST").HandlerFunc(p.createImage)
r.Path("/{rest:.*}").HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Infof("Unhandled request to: %s\n\n", r.URL)
})
laddr, _ := net.ResolveTCPAddr("tcp", p.address)
listener, _ := net.ListenTCP("tcp", laddr)
p.listener = listener
return http.Serve(listener, r)
}
func (p *HTTPProxy) Stop() error {
p.listener.Close()
return nil
}
func (p *HTTPProxy) GetRequests() ([]ContainerRequest, error) {
if len(p.errors) > 0 {
// TODO: collect errors?
return nil, errors.New("Error parsing compose template")
}
return p.containerRequests, nil
}
func (p *HTTPProxy) create(w http.ResponseWriter, r *http.Request) {
log.Infof("CREATE request to %s", r.URL)
body, err := ioutil.ReadAll(r.Body)
if err != nil {
p.errors = append(p.errors, err)
w.WriteHeader(http.StatusInternalServerError)
return
}
name := r.URL.Query()["name"][0]
req := ContainerRequest{
Name: name,
CreateOptions: body,
}
p.containerRequests = append(p.containerRequests, req)
fmt.Fprintf(w, `{"Id":"doesnt_matter", "Warnings":[]}`)
}
func (p *HTTPProxy) inspect(w http.ResponseWriter, r *http.Request) {
log.Infof("INSPECT request to %s", r.URL)
containerInfo := dockerclient.ContainerInfo{
Id: "id_doesnt_matter",
Name: "name_doesnt_matter",
Config: &dockerclient.ContainerConfig{
Labels: map[string]string{
"com.docker.compose.container-number": "1",
},
},
}
j, err := json.Marshal(containerInfo)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
w.Write(j)
}
func (p *HTTPProxy) start(w http.ResponseWriter, r *http.Request) {
log.Infof("START request to %s", r.URL)
w.WriteHeader(204)
}
func (p *HTTPProxy) listAll(w http.ResponseWriter, r *http.Request) {
log.Infof("LIST ALL request to %s", r.URL)
filters := r.URL.Query()["filters"]
name := filteredServiceName(filters)
containers := []dockerclient.Container{}
for _, req := range p.containerRequests {
if (filters == nil) || (extractReqName(req.Name) == name) {
container := dockerclient.Container{
Id: "abc123",
Image: "doesntmatter",
Names: []string{req.Name},
Labels: map[string]string{
"com.docker.compose.container-number": "1",
},
}
containers = append(containers, container)
}
}
j, err := json.Marshal(containers)
if err != nil {
p.errors = append(p.errors, err)
w.WriteHeader(http.StatusInternalServerError)
return
}
w.Write(j)
}
func (p *HTTPProxy) inspectImage(w http.ResponseWriter, r *http.Request) {
log.Infof("IMAGE INSPECT request to %s", r.URL)
id := mux.Vars(r)["id"]
if p.imageInspectsCount == nil {
p.imageInspectsCount = make(map[string]int)
}
p.imageInspectsCount[id] = p.imageInspectsCount[id] + 1
img := &dockerclient.ImageInfo{}
jres, err := json.Marshal(img)
if err != nil {
p.errors = append(p.errors, err)
w.WriteHeader(http.StatusInternalServerError)
return
}
if p.noBuild || p.imageInspectsCount[id] > 1 {
fmt.Fprintf(w, string(jres))
} else {
w.WriteHeader(http.StatusNotFound)
fmt.Fprintf(w, "No such image: doesnt_matter")
}
}
func (p *HTTPProxy) createImage(w http.ResponseWriter, r *http.Request) {
log.Infof("IMAGE CREATE REQUEST to %s", r.URL)
fmt.Fprintf(w, `{}`)
}
func (p *HTTPProxy) build(w http.ResponseWriter, r *http.Request) {
log.Infof("BUILD REQUEST to %s", r.URL)
svcName := r.URL.Query()["t"][0]
if !p.noBuild {
err := p.endpoint.BuildImage(r.Body, svcName)
if err != nil {
log.Fatal(err)
}
}
fmt.Fprintf(w, `{"stream":"Successfully built abc123\n"}`)
}
func extractReqName(reqName string) string {
parts := strings.Split(reqName, "_")
newParts := parts[1 : len(parts)-1]
return strings.Join(newParts, "_")
}
func filteredServiceName(filters []string) string {
if filters != nil {
filter := filters[0]
x := map[string][]string{}
json.Unmarshal([]byte(filter), &x)
for _, item := range x["label"] {
if strings.HasPrefix(item, "com.docker.compose.service") {
return strings.SplitAfterN(item, "=", 2)[1]
}
}
}
return ""
}