api.go 13 KB

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