api.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551
  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/id/" + 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. }
  101. }
  102. }
  103. func makeHandler(ctrl libnetwork.NetworkController, fct processor) http.HandlerFunc {
  104. return func(w http.ResponseWriter, req *http.Request) {
  105. var (
  106. body []byte
  107. err error
  108. )
  109. if req.Body != nil {
  110. body, err = ioutil.ReadAll(req.Body)
  111. if err != nil {
  112. http.Error(w, "Invalid body: "+err.Error(), http.StatusBadRequest)
  113. return
  114. }
  115. }
  116. res, rsp := fct(ctrl, mux.Vars(req), body)
  117. if !rsp.isOK() {
  118. http.Error(w, rsp.Status, rsp.StatusCode)
  119. return
  120. }
  121. if res != nil {
  122. writeJSON(w, rsp.StatusCode, res)
  123. }
  124. }
  125. }
  126. /*****************
  127. Resource Builders
  128. ******************/
  129. func buildNetworkResource(nw libnetwork.Network) *networkResource {
  130. r := &networkResource{}
  131. if nw != nil {
  132. r.Name = nw.Name()
  133. r.ID = nw.ID()
  134. r.Type = nw.Type()
  135. epl := nw.Endpoints()
  136. r.Endpoints = make([]*endpointResource, 0, len(epl))
  137. for _, e := range epl {
  138. epr := buildEndpointResource(e)
  139. r.Endpoints = append(r.Endpoints, epr)
  140. }
  141. }
  142. return r
  143. }
  144. func buildEndpointResource(ep libnetwork.Endpoint) *endpointResource {
  145. r := &endpointResource{}
  146. if ep != nil {
  147. r.Name = ep.Name()
  148. r.ID = ep.ID()
  149. r.Network = ep.Network()
  150. }
  151. return r
  152. }
  153. /****************
  154. Options Parsers
  155. *****************/
  156. func (nc *networkCreate) parseOptions() []libnetwork.NetworkOption {
  157. var setFctList []libnetwork.NetworkOption
  158. if nc.Options != nil {
  159. setFctList = append(setFctList, libnetwork.NetworkOptionGeneric(nc.Options))
  160. }
  161. return setFctList
  162. }
  163. func (ej *endpointJoin) parseOptions() []libnetwork.EndpointOption {
  164. var setFctList []libnetwork.EndpointOption
  165. if ej.HostName != "" {
  166. setFctList = append(setFctList, libnetwork.JoinOptionHostname(ej.HostName))
  167. }
  168. if ej.DomainName != "" {
  169. setFctList = append(setFctList, libnetwork.JoinOptionDomainname(ej.DomainName))
  170. }
  171. if ej.HostsPath != "" {
  172. setFctList = append(setFctList, libnetwork.JoinOptionHostsPath(ej.HostsPath))
  173. }
  174. if ej.ResolvConfPath != "" {
  175. setFctList = append(setFctList, libnetwork.JoinOptionResolvConfPath(ej.ResolvConfPath))
  176. }
  177. if ej.UseDefaultSandbox {
  178. setFctList = append(setFctList, libnetwork.JoinOptionUseDefaultSandbox())
  179. }
  180. if ej.DNS != nil {
  181. for _, d := range ej.DNS {
  182. setFctList = append(setFctList, libnetwork.JoinOptionDNS(d))
  183. }
  184. }
  185. if ej.ExtraHosts != nil {
  186. for _, e := range ej.ExtraHosts {
  187. setFctList = append(setFctList, libnetwork.JoinOptionExtraHost(e.Name, e.Address))
  188. }
  189. }
  190. if ej.ParentUpdates != nil {
  191. for _, p := range ej.ParentUpdates {
  192. setFctList = append(setFctList, libnetwork.JoinOptionParentUpdate(p.EndpointID, p.Name, p.Address))
  193. }
  194. }
  195. return setFctList
  196. }
  197. /******************
  198. Process functions
  199. *******************/
  200. /***************************
  201. NetworkController interface
  202. ****************************/
  203. func procCreateNetwork(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  204. var create networkCreate
  205. err := json.Unmarshal(body, &create)
  206. if err != nil {
  207. return "", &responseStatus{Status: "Invalid body: " + err.Error(), StatusCode: http.StatusBadRequest}
  208. }
  209. nw, err := c.NewNetwork(create.NetworkType, create.Name, create.parseOptions()...)
  210. if err != nil {
  211. return "", convertNetworkError(err)
  212. }
  213. return nw.ID(), &createdResponse
  214. }
  215. func procGetNetwork(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  216. t, by := detectNetworkTarget(vars)
  217. nw, errRsp := findNetwork(c, t, by)
  218. if !errRsp.isOK() {
  219. return nil, errRsp
  220. }
  221. return buildNetworkResource(nw), &successResponse
  222. }
  223. func procGetNetworks(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  224. var list []*networkResource
  225. // Look for query filters and validate
  226. name, queryByName := vars[urlNwName]
  227. shortID, queryByPid := vars[urlNwPID]
  228. if queryByName && queryByPid {
  229. return nil, &badQueryResponse
  230. }
  231. if queryByName {
  232. if nw, errRsp := findNetwork(c, name, byName); errRsp.isOK() {
  233. list = append(list, buildNetworkResource(nw))
  234. }
  235. } else if queryByPid {
  236. // Return all the prefix-matching networks
  237. l := func(nw libnetwork.Network) bool {
  238. if strings.HasPrefix(nw.ID(), shortID) {
  239. list = append(list, buildNetworkResource(nw))
  240. }
  241. return false
  242. }
  243. c.WalkNetworks(l)
  244. } else {
  245. for _, nw := range c.Networks() {
  246. list = append(list, buildNetworkResource(nw))
  247. }
  248. }
  249. return list, &successResponse
  250. }
  251. /******************
  252. Network interface
  253. *******************/
  254. func procCreateEndpoint(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  255. var ec endpointCreate
  256. err := json.Unmarshal(body, &ec)
  257. if err != nil {
  258. return "", &responseStatus{Status: "Invalid body: " + err.Error(), StatusCode: http.StatusBadRequest}
  259. }
  260. nwT, nwBy := detectNetworkTarget(vars)
  261. n, errRsp := findNetwork(c, nwT, nwBy)
  262. if !errRsp.isOK() {
  263. return "", errRsp
  264. }
  265. var setFctList []libnetwork.EndpointOption
  266. if ec.ExposedPorts != nil {
  267. setFctList = append(setFctList, libnetwork.CreateOptionExposedPorts(ec.ExposedPorts))
  268. }
  269. if ec.PortMapping != nil {
  270. setFctList = append(setFctList, libnetwork.CreateOptionPortMapping(ec.PortMapping))
  271. }
  272. ep, err := n.CreateEndpoint(ec.Name, setFctList...)
  273. if err != nil {
  274. return "", convertNetworkError(err)
  275. }
  276. return ep.ID(), &createdResponse
  277. }
  278. func procGetEndpoint(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  279. nwT, nwBy := detectNetworkTarget(vars)
  280. epT, epBy := detectEndpointTarget(vars)
  281. ep, errRsp := findEndpoint(c, nwT, epT, nwBy, epBy)
  282. if !errRsp.isOK() {
  283. return nil, errRsp
  284. }
  285. return buildEndpointResource(ep), &successResponse
  286. }
  287. func procGetEndpoints(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  288. // Look for query filters and validate
  289. name, queryByName := vars[urlEpName]
  290. shortID, queryByPid := vars[urlEpPID]
  291. if queryByName && queryByPid {
  292. return nil, &badQueryResponse
  293. }
  294. nwT, nwBy := detectNetworkTarget(vars)
  295. nw, errRsp := findNetwork(c, nwT, nwBy)
  296. if !errRsp.isOK() {
  297. return nil, errRsp
  298. }
  299. var list []*endpointResource
  300. // If query parameter is specified, return a filtered collection
  301. if queryByName {
  302. if ep, errRsp := findEndpoint(c, nwT, name, nwBy, byName); errRsp.isOK() {
  303. list = append(list, buildEndpointResource(ep))
  304. }
  305. } else if queryByPid {
  306. // Return all the prefix-matching networks
  307. l := func(ep libnetwork.Endpoint) bool {
  308. if strings.HasPrefix(ep.ID(), shortID) {
  309. list = append(list, buildEndpointResource(ep))
  310. }
  311. return false
  312. }
  313. nw.WalkEndpoints(l)
  314. } else {
  315. for _, ep := range nw.Endpoints() {
  316. epr := buildEndpointResource(ep)
  317. list = append(list, epr)
  318. }
  319. }
  320. return list, &successResponse
  321. }
  322. func procDeleteNetwork(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  323. target, by := detectNetworkTarget(vars)
  324. nw, errRsp := findNetwork(c, target, by)
  325. if !errRsp.isOK() {
  326. return nil, errRsp
  327. }
  328. err := nw.Delete()
  329. if err != nil {
  330. return nil, convertNetworkError(err)
  331. }
  332. return nil, &successResponse
  333. }
  334. /******************
  335. Endpoint interface
  336. *******************/
  337. func procJoinEndpoint(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  338. var ej endpointJoin
  339. err := json.Unmarshal(body, &ej)
  340. if err != nil {
  341. return nil, &responseStatus{Status: "Invalid body: " + err.Error(), StatusCode: http.StatusBadRequest}
  342. }
  343. nwT, nwBy := detectNetworkTarget(vars)
  344. epT, epBy := detectEndpointTarget(vars)
  345. ep, errRsp := findEndpoint(c, nwT, epT, nwBy, epBy)
  346. if !errRsp.isOK() {
  347. return nil, errRsp
  348. }
  349. cd, err := ep.Join(ej.ContainerID, ej.parseOptions()...)
  350. if err != nil {
  351. return nil, convertNetworkError(err)
  352. }
  353. return cd, &successResponse
  354. }
  355. func procLeaveEndpoint(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  356. nwT, nwBy := detectNetworkTarget(vars)
  357. epT, epBy := detectEndpointTarget(vars)
  358. ep, errRsp := findEndpoint(c, nwT, epT, nwBy, epBy)
  359. if !errRsp.isOK() {
  360. return nil, errRsp
  361. }
  362. err := ep.Leave(vars[urlCnID])
  363. if err != nil {
  364. return nil, convertNetworkError(err)
  365. }
  366. return nil, &successResponse
  367. }
  368. func procDeleteEndpoint(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  369. nwT, nwBy := detectNetworkTarget(vars)
  370. epT, epBy := detectEndpointTarget(vars)
  371. ep, errRsp := findEndpoint(c, nwT, epT, nwBy, epBy)
  372. if !errRsp.isOK() {
  373. return nil, errRsp
  374. }
  375. err := ep.Delete()
  376. if err != nil {
  377. return nil, convertNetworkError(err)
  378. }
  379. return nil, &successResponse
  380. }
  381. /***********
  382. Utilities
  383. ************/
  384. const (
  385. byID = iota
  386. byName
  387. )
  388. func detectNetworkTarget(vars map[string]string) (string, int) {
  389. if target, ok := vars[urlNwName]; ok {
  390. return target, byName
  391. }
  392. if target, ok := vars[urlNwID]; ok {
  393. return target, byID
  394. }
  395. // vars are populated from the URL, following cannot happen
  396. panic("Missing URL variable parameter for network")
  397. }
  398. func detectEndpointTarget(vars map[string]string) (string, int) {
  399. if target, ok := vars[urlEpName]; ok {
  400. return target, byName
  401. }
  402. if target, ok := vars[urlEpID]; ok {
  403. return target, byID
  404. }
  405. // vars are populated from the URL, following cannot happen
  406. panic("Missing URL variable parameter for endpoint")
  407. }
  408. func findNetwork(c libnetwork.NetworkController, s string, by int) (libnetwork.Network, *responseStatus) {
  409. var (
  410. nw libnetwork.Network
  411. err error
  412. )
  413. switch by {
  414. case byID:
  415. nw, err = c.NetworkByID(s)
  416. case byName:
  417. nw, err = c.NetworkByName(s)
  418. default:
  419. panic(fmt.Sprintf("unexpected selector for network search: %d", by))
  420. }
  421. if err != nil {
  422. if _, ok := err.(libnetwork.ErrNoSuchNetwork); ok {
  423. return nil, &responseStatus{Status: "Resource not found: Network", StatusCode: http.StatusNotFound}
  424. }
  425. return nil, &responseStatus{Status: err.Error(), StatusCode: http.StatusBadRequest}
  426. }
  427. return nw, &successResponse
  428. }
  429. func findEndpoint(c libnetwork.NetworkController, ns, es string, nwBy, epBy int) (libnetwork.Endpoint, *responseStatus) {
  430. nw, errRsp := findNetwork(c, ns, nwBy)
  431. if !errRsp.isOK() {
  432. return nil, errRsp
  433. }
  434. var (
  435. err error
  436. ep libnetwork.Endpoint
  437. )
  438. switch epBy {
  439. case byID:
  440. ep, err = nw.EndpointByID(es)
  441. case byName:
  442. ep, err = nw.EndpointByName(es)
  443. default:
  444. panic(fmt.Sprintf("unexpected selector for endpoint search: %d", epBy))
  445. }
  446. if err != nil {
  447. if _, ok := err.(libnetwork.ErrNoSuchEndpoint); ok {
  448. return nil, &responseStatus{Status: "Resource not found: Endpoint", StatusCode: http.StatusNotFound}
  449. }
  450. return nil, &responseStatus{Status: err.Error(), StatusCode: http.StatusBadRequest}
  451. }
  452. return ep, &successResponse
  453. }
  454. func convertNetworkError(err error) *responseStatus {
  455. var code int
  456. switch err.(type) {
  457. case types.BadRequestError:
  458. code = http.StatusBadRequest
  459. case types.ForbiddenError:
  460. code = http.StatusForbidden
  461. case types.NotFoundError:
  462. code = http.StatusNotFound
  463. case types.TimeoutError:
  464. code = http.StatusRequestTimeout
  465. case types.NotImplementedError:
  466. code = http.StatusNotImplemented
  467. case types.NoServiceError:
  468. code = http.StatusServiceUnavailable
  469. case types.InternalError:
  470. code = http.StatusInternalServerError
  471. default:
  472. code = http.StatusInternalServerError
  473. }
  474. return &responseStatus{Status: err.Error(), StatusCode: code}
  475. }
  476. func writeJSON(w http.ResponseWriter, code int, v interface{}) error {
  477. w.Header().Set("Content-Type", "application/json")
  478. w.WriteHeader(code)
  479. return json.NewEncoder(w).Encode(v)
  480. }