api.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481
  1. package api
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "io/ioutil"
  6. "net/http"
  7. "github.com/docker/libnetwork"
  8. "github.com/gorilla/mux"
  9. )
  10. var (
  11. successResponse = responseStatus{Status: "Success", StatusCode: http.StatusOK}
  12. createdResponse = responseStatus{Status: "Created", StatusCode: http.StatusCreated}
  13. mismatchResponse = responseStatus{Status: "Body/URI parameter mismatch", StatusCode: http.StatusBadRequest}
  14. )
  15. const (
  16. urlNwName = "name"
  17. urlNwID = "id"
  18. urlEpName = "endpoint-name"
  19. urlEpID = "endpoint-id"
  20. urlCnID = "container-id"
  21. )
  22. // NewHTTPHandler creates and initialize the HTTP handler to serve the requests for libnetwork
  23. func NewHTTPHandler(c libnetwork.NetworkController) func(w http.ResponseWriter, req *http.Request) {
  24. h := &httpHandler{c: c}
  25. h.initRouter()
  26. return h.handleRequest
  27. }
  28. type responseStatus struct {
  29. Status string
  30. StatusCode int
  31. }
  32. func (r *responseStatus) isOK() bool {
  33. return r.StatusCode == http.StatusOK || r.StatusCode == http.StatusCreated
  34. }
  35. type processor func(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus)
  36. type httpHandler struct {
  37. c libnetwork.NetworkController
  38. r *mux.Router
  39. }
  40. func (h *httpHandler) handleRequest(w http.ResponseWriter, req *http.Request) {
  41. // Make sure the service is there
  42. if h.c == nil {
  43. http.Error(w, "NetworkController is not available", http.StatusServiceUnavailable)
  44. return
  45. }
  46. // Get handler from router and execute it
  47. h.r.ServeHTTP(w, req)
  48. }
  49. func (h *httpHandler) initRouter() {
  50. m := map[string]map[string]processor{
  51. "GET": {
  52. "/networks": procGetNetworks,
  53. "/networks/name/{" + urlNwName + ":.*}": procGetNetwork,
  54. "/networks/id/{" + urlNwID + ":.*}": procGetNetwork,
  55. "/networks/name/{" + urlNwName + ":.*}/endpoints/": procGetEndpoints,
  56. "/networks/id/{" + urlNwID + ":.*}/endpoints/": procGetEndpoints,
  57. "/networks/name/{" + urlNwName + ":.*}/endpoints/name/{" + urlEpName + ":.*}": procGetEndpoint,
  58. "/networks/id/{" + urlNwID + ":.*}/endpoints/name/{" + urlEpName + ":.*}": procGetEndpoint,
  59. "/networks/name/{" + urlNwName + ":.*}/endpoints/id/{" + urlEpID + ":.*}": procGetEndpoint,
  60. "/networks/id/{" + urlNwID + ":.*}/endpoints/id/{" + urlEpID + ":.*}": procGetEndpoint,
  61. },
  62. "POST": {
  63. "/networks/name/{" + urlNwName + ":.*}": procCreateNetwork,
  64. "/networks/name/{" + urlNwName + ":.*}/endpoint/name/{" + urlEpName + ":.*}": procCreateEndpoint,
  65. "/networks/name/{" + urlNwName + ":.*}/endpoint/name/{" + urlEpName + ":.*}/container/{" + urlCnID + ":.*}": procJoinEndpoint,
  66. },
  67. "DELETE": {
  68. "/networks/name/{" + urlNwName + ":.*}": procDeleteNetwork,
  69. "/networks/id/{" + urlNwID + ":.*}": procDeleteNetwork,
  70. "/networks/name/{" + urlNwName + ":.*}/endpoints/name/{" + urlEpName + ":.*}": procDeleteEndpoint,
  71. "/networks/name/{" + urlNwName + ":.*}/endpoints/id/{" + urlEpID + ":.*}": procDeleteEndpoint,
  72. "/networks/id/{" + urlNwID + ":.*}/endpoints/name/{" + urlEpName + ":.*}": procDeleteEndpoint,
  73. "/networks/id/{" + urlNwID + ":.*}/endpoints/id/{" + urlEpID + ":.*}": procDeleteEndpoint,
  74. "/networks/name/{" + urlNwName + ":.*}/endpoint/name/{" + urlEpName + ":.*}/container/{" + urlCnID + ":.*}": procLeaveEndpoint,
  75. "/networks/name/{" + urlNwName + ":.*}/endpoint/id/{" + urlEpID + ":.*}/container/{" + urlCnID + ":.*}": procLeaveEndpoint,
  76. "/networks/id/{" + urlNwID + ":.*}/endpoint/name/{" + urlEpName + ":.*}/container/{" + urlCnID + ":.*}": procLeaveEndpoint,
  77. "/networks/id/{" + urlNwID + ":.*}/endpoint/id/{" + urlEpID + ":.*}/container/{" + urlCnID + ":.*}": procLeaveEndpoint,
  78. },
  79. }
  80. h.r = mux.NewRouter()
  81. for method, routes := range m {
  82. for route, fct := range routes {
  83. f := makeHandler(h.c, fct)
  84. h.r.Path(route).Methods(method).HandlerFunc(f)
  85. }
  86. }
  87. }
  88. func makeHandler(ctrl libnetwork.NetworkController, fct processor) http.HandlerFunc {
  89. return func(w http.ResponseWriter, req *http.Request) {
  90. var (
  91. body []byte
  92. err error
  93. )
  94. if req.Body != nil {
  95. body, err = ioutil.ReadAll(req.Body)
  96. if err != nil {
  97. http.Error(w, "Invalid body: "+err.Error(), http.StatusBadRequest)
  98. return
  99. }
  100. }
  101. res, rsp := fct(ctrl, mux.Vars(req), body)
  102. if !rsp.isOK() {
  103. http.Error(w, rsp.Status, rsp.StatusCode)
  104. return
  105. }
  106. if res != nil {
  107. writeJSON(w, rsp.StatusCode, res)
  108. }
  109. }
  110. }
  111. /*****************
  112. Resource Builders
  113. ******************/
  114. func buildNetworkResource(nw libnetwork.Network) *networkResource {
  115. r := &networkResource{}
  116. if nw != nil {
  117. r.Name = nw.Name()
  118. r.ID = nw.ID()
  119. r.Type = nw.Type()
  120. epl := nw.Endpoints()
  121. r.Endpoints = make([]*endpointResource, 0, len(epl))
  122. for _, e := range epl {
  123. epr := buildEndpointResource(e)
  124. r.Endpoints = append(r.Endpoints, epr)
  125. }
  126. }
  127. return r
  128. }
  129. func buildEndpointResource(ep libnetwork.Endpoint) *endpointResource {
  130. r := &endpointResource{}
  131. if ep != nil {
  132. r.Name = ep.Name()
  133. r.ID = ep.ID()
  134. r.Network = ep.Network()
  135. }
  136. return r
  137. }
  138. /**************
  139. Options Parser
  140. ***************/
  141. func (ej *endpointJoin) parseOptions() []libnetwork.EndpointOption {
  142. var setFctList []libnetwork.EndpointOption
  143. if ej.HostName != "" {
  144. setFctList = append(setFctList, libnetwork.JoinOptionHostname(ej.HostName))
  145. }
  146. if ej.DomainName != "" {
  147. setFctList = append(setFctList, libnetwork.JoinOptionDomainname(ej.DomainName))
  148. }
  149. if ej.HostsPath != "" {
  150. setFctList = append(setFctList, libnetwork.JoinOptionHostsPath(ej.HostsPath))
  151. }
  152. if ej.ResolvConfPath != "" {
  153. setFctList = append(setFctList, libnetwork.JoinOptionResolvConfPath(ej.ResolvConfPath))
  154. }
  155. if ej.UseDefaultSandbox {
  156. setFctList = append(setFctList, libnetwork.JoinOptionUseDefaultSandbox())
  157. }
  158. if ej.DNS != nil {
  159. for _, d := range ej.DNS {
  160. setFctList = append(setFctList, libnetwork.JoinOptionDNS(d))
  161. }
  162. }
  163. if ej.ExtraHosts != nil {
  164. for _, e := range ej.ExtraHosts {
  165. setFctList = append(setFctList, libnetwork.JoinOptionExtraHost(e.Name, e.Address))
  166. }
  167. }
  168. if ej.ParentUpdates != nil {
  169. for _, p := range ej.ParentUpdates {
  170. setFctList = append(setFctList, libnetwork.JoinOptionParentUpdate(p.EndpointID, p.Name, p.Address))
  171. }
  172. }
  173. return setFctList
  174. }
  175. /******************
  176. Process functions
  177. *******************/
  178. /***************************
  179. NetworkController interface
  180. ****************************/
  181. func procCreateNetwork(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  182. var create networkCreate
  183. err := json.Unmarshal(body, &create)
  184. if err != nil {
  185. return "", &responseStatus{Status: "Invalid body: " + err.Error(), StatusCode: http.StatusBadRequest}
  186. }
  187. name := vars[urlNwName]
  188. if name != create.Name {
  189. return "", &mismatchResponse
  190. }
  191. nw, err := c.NewNetwork(create.NetworkType, name, nil)
  192. if err != nil {
  193. return "", convertNetworkError(err)
  194. }
  195. return nw.ID(), &createdResponse
  196. }
  197. func procGetNetwork(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  198. t, by := detectNetworkTarget(vars)
  199. nw, errRsp := findNetwork(c, t, by)
  200. if !errRsp.isOK() {
  201. return nil, errRsp
  202. }
  203. return buildNetworkResource(nw), &successResponse
  204. }
  205. func procGetNetworks(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  206. var list []*networkResource
  207. for _, nw := range c.Networks() {
  208. nwr := buildNetworkResource(nw)
  209. list = append(list, nwr)
  210. }
  211. return list, &successResponse
  212. }
  213. /******************
  214. Network interface
  215. *******************/
  216. func procCreateEndpoint(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  217. var ec endpointCreate
  218. err := json.Unmarshal(body, &ec)
  219. if err != nil {
  220. return "", &responseStatus{Status: "Invalid body: " + err.Error(), StatusCode: http.StatusBadRequest}
  221. }
  222. epn := vars[urlEpName]
  223. if ec.Name != epn {
  224. return "", &mismatchResponse
  225. }
  226. nwT, nwBy := detectNetworkTarget(vars)
  227. n, errRsp := findNetwork(c, nwT, nwBy)
  228. if !errRsp.isOK() {
  229. return "", errRsp
  230. }
  231. if ec.NetworkID != n.ID() {
  232. return "", &mismatchResponse
  233. }
  234. var setFctList []libnetwork.EndpointOption
  235. if ec.ExposedPorts != nil {
  236. setFctList = append(setFctList, libnetwork.CreateOptionExposedPorts(ec.ExposedPorts))
  237. }
  238. if ec.PortMapping != nil {
  239. setFctList = append(setFctList, libnetwork.CreateOptionPortMapping(ec.PortMapping))
  240. }
  241. ep, err := n.CreateEndpoint(epn, setFctList...)
  242. if err != nil {
  243. return "", convertNetworkError(err)
  244. }
  245. return ep.ID(), &createdResponse
  246. }
  247. func procGetEndpoint(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  248. nwT, nwBy := detectNetworkTarget(vars)
  249. epT, epBy := detectEndpointTarget(vars)
  250. ep, errRsp := findEndpoint(c, nwT, epT, nwBy, epBy)
  251. if !errRsp.isOK() {
  252. return nil, errRsp
  253. }
  254. return buildEndpointResource(ep), &successResponse
  255. }
  256. func procGetEndpoints(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  257. target, by := detectNetworkTarget(vars)
  258. nw, errRsp := findNetwork(c, target, by)
  259. if !errRsp.isOK() {
  260. return nil, errRsp
  261. }
  262. var list []*endpointResource
  263. for _, ep := range nw.Endpoints() {
  264. epr := buildEndpointResource(ep)
  265. list = append(list, epr)
  266. }
  267. return list, &successResponse
  268. }
  269. func procDeleteNetwork(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  270. target, by := detectNetworkTarget(vars)
  271. nw, errRsp := findNetwork(c, target, by)
  272. if !errRsp.isOK() {
  273. return nil, errRsp
  274. }
  275. err := nw.Delete()
  276. if err != nil {
  277. return nil, convertNetworkError(err)
  278. }
  279. return nil, &successResponse
  280. }
  281. /******************
  282. Endpoint interface
  283. *******************/
  284. func procJoinEndpoint(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  285. var ej endpointJoin
  286. err := json.Unmarshal(body, &ej)
  287. if err != nil {
  288. return nil, &responseStatus{Status: "Invalid body: " + err.Error(), StatusCode: http.StatusBadRequest}
  289. }
  290. cid := vars[urlCnID]
  291. if ej.ContainerID != cid {
  292. return "", &mismatchResponse
  293. }
  294. nwT, nwBy := detectNetworkTarget(vars)
  295. epT, epBy := detectEndpointTarget(vars)
  296. ep, errRsp := findEndpoint(c, nwT, epT, nwBy, epBy)
  297. if !errRsp.isOK() {
  298. return nil, errRsp
  299. }
  300. cd, err := ep.Join(ej.ContainerID, ej.parseOptions()...)
  301. if err != nil {
  302. return nil, convertNetworkError(err)
  303. }
  304. return cd, &successResponse
  305. }
  306. func procLeaveEndpoint(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  307. nwT, nwBy := detectNetworkTarget(vars)
  308. epT, epBy := detectEndpointTarget(vars)
  309. ep, errRsp := findEndpoint(c, nwT, epT, nwBy, epBy)
  310. if !errRsp.isOK() {
  311. return nil, errRsp
  312. }
  313. err := ep.Leave(vars[urlCnID])
  314. if err != nil {
  315. return nil, convertNetworkError(err)
  316. }
  317. return nil, &successResponse
  318. }
  319. func procDeleteEndpoint(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  320. nwT, nwBy := detectNetworkTarget(vars)
  321. epT, epBy := detectEndpointTarget(vars)
  322. ep, errRsp := findEndpoint(c, nwT, epT, nwBy, epBy)
  323. if !errRsp.isOK() {
  324. return nil, errRsp
  325. }
  326. err := ep.Delete()
  327. if err != nil {
  328. return nil, convertNetworkError(err)
  329. }
  330. return nil, &successResponse
  331. }
  332. /***********
  333. Utilities
  334. ************/
  335. const (
  336. byID = iota
  337. byName
  338. )
  339. func detectNetworkTarget(vars map[string]string) (string, int) {
  340. if target, ok := vars[urlNwName]; ok {
  341. return target, byName
  342. }
  343. if target, ok := vars[urlNwID]; ok {
  344. return target, byID
  345. }
  346. // vars are populated from the URL, following cannot happen
  347. panic("Missing URL variable parameter for network")
  348. }
  349. func detectEndpointTarget(vars map[string]string) (string, int) {
  350. if target, ok := vars[urlEpName]; ok {
  351. return target, byName
  352. }
  353. if target, ok := vars[urlEpID]; ok {
  354. return target, byID
  355. }
  356. // vars are populated from the URL, following cannot happen
  357. panic("Missing URL variable parameter for endpoint")
  358. }
  359. func findNetwork(c libnetwork.NetworkController, s string, by int) (libnetwork.Network, *responseStatus) {
  360. var (
  361. nw libnetwork.Network
  362. err error
  363. )
  364. switch by {
  365. case byID:
  366. nw, err = c.NetworkByID(s)
  367. case byName:
  368. nw, err = c.NetworkByName(s)
  369. default:
  370. panic(fmt.Sprintf("unexpected selector for network search: %d", by))
  371. }
  372. if err != nil {
  373. if err == libnetwork.ErrNoSuchNetwork {
  374. return nil, &responseStatus{Status: "Resource not found: Network", StatusCode: http.StatusNotFound}
  375. }
  376. return nil, &responseStatus{Status: err.Error(), StatusCode: http.StatusBadRequest}
  377. }
  378. return nw, &successResponse
  379. }
  380. func findEndpoint(c libnetwork.NetworkController, ns, es string, nwBy, epBy int) (libnetwork.Endpoint, *responseStatus) {
  381. nw, errRsp := findNetwork(c, ns, nwBy)
  382. if !errRsp.isOK() {
  383. return nil, errRsp
  384. }
  385. var (
  386. err error
  387. ep libnetwork.Endpoint
  388. )
  389. switch epBy {
  390. case byID:
  391. ep, err = nw.EndpointByID(es)
  392. case byName:
  393. ep, err = nw.EndpointByName(es)
  394. default:
  395. panic(fmt.Sprintf("unexpected selector for endpoint search: %d", epBy))
  396. }
  397. if err != nil {
  398. if err == libnetwork.ErrNoSuchEndpoint {
  399. return nil, &responseStatus{Status: "Resource not found: Endpoint", StatusCode: http.StatusNotFound}
  400. }
  401. return nil, &responseStatus{Status: err.Error(), StatusCode: http.StatusBadRequest}
  402. }
  403. return ep, &successResponse
  404. }
  405. func convertNetworkError(err error) *responseStatus {
  406. // No real libnetwork error => http error code conversion for now.
  407. // Will came in later when new interface for libnetwork error is vailable
  408. return &responseStatus{Status: err.Error(), StatusCode: http.StatusBadRequest}
  409. }
  410. func writeJSON(w http.ResponseWriter, code int, v interface{}) error {
  411. w.Header().Set("Content-Type", "application/json")
  412. w.WriteHeader(code)
  413. return json.NewEncoder(w).Encode(v)
  414. }