api.go 14 KB

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