api.go 16 KB

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