api.go 15 KB

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