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