api.go 15 KB

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