api.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762
  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. {"/services", []string{"network", nwName}, procGetServices},
  82. {"/services", []string{"name", epName}, procGetServices},
  83. {"/services", []string{"partial-id", epPID}, procGetServices},
  84. {"/services", nil, procGetServices},
  85. {"/services/" + epID, nil, procGetService},
  86. {"/services/" + epID + "/backend", nil, procGetContainers},
  87. },
  88. "POST": {
  89. {"/networks", nil, procCreateNetwork},
  90. {"/networks/" + nwID + "/endpoints", nil, procCreateEndpoint},
  91. {"/networks/" + nwID + "/endpoints/" + epID + "/containers", nil, procJoinEndpoint},
  92. {"/services", nil, procPublishService},
  93. {"/services/" + epID + "/backend", nil, procAttachBackend},
  94. },
  95. "DELETE": {
  96. {"/networks/" + nwID, nil, procDeleteNetwork},
  97. {"/networks/" + nwID + "/endpoints/" + epID, nil, procDeleteEndpoint},
  98. {"/networks/" + nwID + "/endpoints/" + epID + "/containers/" + cnID, nil, procLeaveEndpoint},
  99. {"/services/" + epID, nil, procUnpublishService},
  100. {"/services/" + epID + "/backend/" + cnID, nil, procDetachBackend},
  101. },
  102. }
  103. h.r = mux.NewRouter()
  104. for method, routes := range m {
  105. for _, route := range routes {
  106. r := h.r.Path("/{.*}" + route.url).Methods(method).HandlerFunc(makeHandler(h.c, route.fct))
  107. if route.qrs != nil {
  108. r.Queries(route.qrs...)
  109. }
  110. r = h.r.Path(route.url).Methods(method).HandlerFunc(makeHandler(h.c, route.fct))
  111. if route.qrs != nil {
  112. r.Queries(route.qrs...)
  113. }
  114. }
  115. }
  116. }
  117. func makeHandler(ctrl libnetwork.NetworkController, fct processor) http.HandlerFunc {
  118. return func(w http.ResponseWriter, req *http.Request) {
  119. var (
  120. body []byte
  121. err error
  122. )
  123. if req.Body != nil {
  124. body, err = ioutil.ReadAll(req.Body)
  125. if err != nil {
  126. http.Error(w, "Invalid body: "+err.Error(), http.StatusBadRequest)
  127. return
  128. }
  129. }
  130. res, rsp := fct(ctrl, mux.Vars(req), body)
  131. if !rsp.isOK() {
  132. http.Error(w, rsp.Status, rsp.StatusCode)
  133. return
  134. }
  135. if res != nil {
  136. writeJSON(w, rsp.StatusCode, res)
  137. }
  138. }
  139. }
  140. /*****************
  141. Resource Builders
  142. ******************/
  143. func buildNetworkResource(nw libnetwork.Network) *networkResource {
  144. r := &networkResource{}
  145. if nw != nil {
  146. r.Name = nw.Name()
  147. r.ID = nw.ID()
  148. r.Type = nw.Type()
  149. epl := nw.Endpoints()
  150. r.Endpoints = make([]*endpointResource, 0, len(epl))
  151. for _, e := range epl {
  152. epr := buildEndpointResource(e)
  153. r.Endpoints = append(r.Endpoints, epr)
  154. }
  155. }
  156. return r
  157. }
  158. func buildEndpointResource(ep libnetwork.Endpoint) *endpointResource {
  159. r := &endpointResource{}
  160. if ep != nil {
  161. r.Name = ep.Name()
  162. r.ID = ep.ID()
  163. r.Network = ep.Network()
  164. }
  165. return r
  166. }
  167. func buildContainerResource(ci libnetwork.ContainerInfo) *containerResource {
  168. r := &containerResource{}
  169. if ci != nil {
  170. r.ID = ci.ID()
  171. }
  172. return r
  173. }
  174. /****************
  175. Options Parsers
  176. *****************/
  177. func (nc *networkCreate) parseOptions() []libnetwork.NetworkOption {
  178. var setFctList []libnetwork.NetworkOption
  179. if nc.Options != nil {
  180. setFctList = append(setFctList, libnetwork.NetworkOptionGeneric(nc.Options))
  181. }
  182. return setFctList
  183. }
  184. func (ej *endpointJoin) parseOptions() []libnetwork.EndpointOption {
  185. var setFctList []libnetwork.EndpointOption
  186. if ej.HostName != "" {
  187. setFctList = append(setFctList, libnetwork.JoinOptionHostname(ej.HostName))
  188. }
  189. if ej.DomainName != "" {
  190. setFctList = append(setFctList, libnetwork.JoinOptionDomainname(ej.DomainName))
  191. }
  192. if ej.HostsPath != "" {
  193. setFctList = append(setFctList, libnetwork.JoinOptionHostsPath(ej.HostsPath))
  194. }
  195. if ej.ResolvConfPath != "" {
  196. setFctList = append(setFctList, libnetwork.JoinOptionResolvConfPath(ej.ResolvConfPath))
  197. }
  198. if ej.UseDefaultSandbox {
  199. setFctList = append(setFctList, libnetwork.JoinOptionUseDefaultSandbox())
  200. }
  201. if ej.DNS != nil {
  202. for _, d := range ej.DNS {
  203. setFctList = append(setFctList, libnetwork.JoinOptionDNS(d))
  204. }
  205. }
  206. if ej.ExtraHosts != nil {
  207. for _, e := range ej.ExtraHosts {
  208. setFctList = append(setFctList, libnetwork.JoinOptionExtraHost(e.Name, e.Address))
  209. }
  210. }
  211. if ej.ParentUpdates != nil {
  212. for _, p := range ej.ParentUpdates {
  213. setFctList = append(setFctList, libnetwork.JoinOptionParentUpdate(p.EndpointID, p.Name, p.Address))
  214. }
  215. }
  216. return setFctList
  217. }
  218. /******************
  219. Process functions
  220. *******************/
  221. /***************************
  222. NetworkController interface
  223. ****************************/
  224. func procCreateNetwork(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  225. var create networkCreate
  226. err := json.Unmarshal(body, &create)
  227. if err != nil {
  228. return "", &responseStatus{Status: "Invalid body: " + err.Error(), StatusCode: http.StatusBadRequest}
  229. }
  230. nw, err := c.NewNetwork(create.NetworkType, create.Name, create.parseOptions()...)
  231. if err != nil {
  232. return "", convertNetworkError(err)
  233. }
  234. return nw.ID(), &createdResponse
  235. }
  236. func procGetNetwork(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  237. t, by := detectNetworkTarget(vars)
  238. nw, errRsp := findNetwork(c, t, by)
  239. if !errRsp.isOK() {
  240. return nil, errRsp
  241. }
  242. return buildNetworkResource(nw), &successResponse
  243. }
  244. func procGetNetworks(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  245. var list []*networkResource
  246. // Look for query filters and validate
  247. name, queryByName := vars[urlNwName]
  248. shortID, queryByPid := vars[urlNwPID]
  249. if queryByName && queryByPid {
  250. return nil, &badQueryResponse
  251. }
  252. if queryByName {
  253. if nw, errRsp := findNetwork(c, name, byName); errRsp.isOK() {
  254. list = append(list, buildNetworkResource(nw))
  255. }
  256. } else if queryByPid {
  257. // Return all the prefix-matching networks
  258. l := func(nw libnetwork.Network) bool {
  259. if strings.HasPrefix(nw.ID(), shortID) {
  260. list = append(list, buildNetworkResource(nw))
  261. }
  262. return false
  263. }
  264. c.WalkNetworks(l)
  265. } else {
  266. for _, nw := range c.Networks() {
  267. list = append(list, buildNetworkResource(nw))
  268. }
  269. }
  270. return list, &successResponse
  271. }
  272. /******************
  273. Network interface
  274. *******************/
  275. func procCreateEndpoint(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  276. var ec endpointCreate
  277. err := json.Unmarshal(body, &ec)
  278. if err != nil {
  279. return "", &responseStatus{Status: "Invalid body: " + err.Error(), StatusCode: http.StatusBadRequest}
  280. }
  281. nwT, nwBy := detectNetworkTarget(vars)
  282. n, errRsp := findNetwork(c, nwT, nwBy)
  283. if !errRsp.isOK() {
  284. return "", errRsp
  285. }
  286. var setFctList []libnetwork.EndpointOption
  287. if ec.ExposedPorts != nil {
  288. setFctList = append(setFctList, libnetwork.CreateOptionExposedPorts(ec.ExposedPorts))
  289. }
  290. if ec.PortMapping != nil {
  291. setFctList = append(setFctList, libnetwork.CreateOptionPortMapping(ec.PortMapping))
  292. }
  293. ep, err := n.CreateEndpoint(ec.Name, setFctList...)
  294. if err != nil {
  295. return "", convertNetworkError(err)
  296. }
  297. return ep.ID(), &createdResponse
  298. }
  299. func procGetEndpoint(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  300. nwT, nwBy := detectNetworkTarget(vars)
  301. epT, epBy := detectEndpointTarget(vars)
  302. ep, errRsp := findEndpoint(c, nwT, epT, nwBy, epBy)
  303. if !errRsp.isOK() {
  304. return nil, errRsp
  305. }
  306. return buildEndpointResource(ep), &successResponse
  307. }
  308. func procGetEndpoints(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  309. // Look for query filters and validate
  310. name, queryByName := vars[urlEpName]
  311. shortID, queryByPid := vars[urlEpPID]
  312. if queryByName && queryByPid {
  313. return nil, &badQueryResponse
  314. }
  315. nwT, nwBy := detectNetworkTarget(vars)
  316. nw, errRsp := findNetwork(c, nwT, nwBy)
  317. if !errRsp.isOK() {
  318. return nil, errRsp
  319. }
  320. var list []*endpointResource
  321. // If query parameter is specified, return a filtered collection
  322. if queryByName {
  323. if ep, errRsp := findEndpoint(c, nwT, name, nwBy, byName); errRsp.isOK() {
  324. list = append(list, buildEndpointResource(ep))
  325. }
  326. } else if queryByPid {
  327. // Return all the prefix-matching endpoints
  328. l := func(ep libnetwork.Endpoint) bool {
  329. if strings.HasPrefix(ep.ID(), shortID) {
  330. list = append(list, buildEndpointResource(ep))
  331. }
  332. return false
  333. }
  334. nw.WalkEndpoints(l)
  335. } else {
  336. for _, ep := range nw.Endpoints() {
  337. epr := buildEndpointResource(ep)
  338. list = append(list, epr)
  339. }
  340. }
  341. return list, &successResponse
  342. }
  343. func procDeleteNetwork(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  344. target, by := detectNetworkTarget(vars)
  345. nw, errRsp := findNetwork(c, target, by)
  346. if !errRsp.isOK() {
  347. return nil, errRsp
  348. }
  349. err := nw.Delete()
  350. if err != nil {
  351. return nil, convertNetworkError(err)
  352. }
  353. return nil, &successResponse
  354. }
  355. /******************
  356. Endpoint interface
  357. *******************/
  358. func procJoinEndpoint(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  359. var ej endpointJoin
  360. err := json.Unmarshal(body, &ej)
  361. if err != nil {
  362. return nil, &responseStatus{Status: "Invalid body: " + err.Error(), StatusCode: http.StatusBadRequest}
  363. }
  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.Join(ej.ContainerID, ej.parseOptions()...)
  371. if err != nil {
  372. return nil, convertNetworkError(err)
  373. }
  374. return ep.Info().SandboxKey(), &successResponse
  375. }
  376. func procLeaveEndpoint(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.Leave(vars[urlCnID])
  384. if err != nil {
  385. return nil, convertNetworkError(err)
  386. }
  387. return nil, &successResponse
  388. }
  389. func procDeleteEndpoint(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  390. nwT, nwBy := detectNetworkTarget(vars)
  391. epT, epBy := detectEndpointTarget(vars)
  392. ep, errRsp := findEndpoint(c, nwT, epT, nwBy, epBy)
  393. if !errRsp.isOK() {
  394. return nil, errRsp
  395. }
  396. err := ep.Delete()
  397. if err != nil {
  398. return nil, convertNetworkError(err)
  399. }
  400. return nil, &successResponse
  401. }
  402. /******************
  403. Service interface
  404. *******************/
  405. func procGetServices(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  406. // Look for query filters and validate
  407. nwName, filterByNwName := vars[urlNwName]
  408. svName, queryBySvName := vars[urlEpName]
  409. shortID, queryBySvPID := vars[urlEpPID]
  410. if filterByNwName && queryBySvName || filterByNwName && queryBySvPID || queryBySvName && queryBySvPID {
  411. return nil, &badQueryResponse
  412. }
  413. var list []*endpointResource
  414. switch {
  415. case filterByNwName:
  416. // return all service present on the specified network
  417. nw, errRsp := findNetwork(c, nwName, byName)
  418. if !errRsp.isOK() {
  419. return list, &successResponse
  420. }
  421. for _, ep := range nw.Endpoints() {
  422. epr := buildEndpointResource(ep)
  423. list = append(list, epr)
  424. }
  425. case queryBySvName:
  426. // Look in each network for the service with the specified name
  427. l := func(ep libnetwork.Endpoint) bool {
  428. if ep.Name() == svName {
  429. list = append(list, buildEndpointResource(ep))
  430. return true
  431. }
  432. return false
  433. }
  434. for _, nw := range c.Networks() {
  435. nw.WalkEndpoints(l)
  436. }
  437. case queryBySvPID:
  438. // Return all the prefix-matching services
  439. l := func(ep libnetwork.Endpoint) bool {
  440. if strings.HasPrefix(ep.ID(), shortID) {
  441. list = append(list, buildEndpointResource(ep))
  442. }
  443. return false
  444. }
  445. for _, nw := range c.Networks() {
  446. nw.WalkEndpoints(l)
  447. }
  448. default:
  449. for _, nw := range c.Networks() {
  450. for _, ep := range nw.Endpoints() {
  451. epr := buildEndpointResource(ep)
  452. list = append(list, epr)
  453. }
  454. }
  455. }
  456. return list, &successResponse
  457. }
  458. func procGetService(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  459. epT, epBy := detectEndpointTarget(vars)
  460. sv, errRsp := findService(c, epT, epBy)
  461. if !errRsp.isOK() {
  462. return nil, endpointToService(errRsp)
  463. }
  464. return buildEndpointResource(sv), &successResponse
  465. }
  466. func procGetContainers(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  467. epT, epBy := detectEndpointTarget(vars)
  468. sv, errRsp := findService(c, epT, epBy)
  469. if !errRsp.isOK() {
  470. return nil, endpointToService(errRsp)
  471. }
  472. var list []*containerResource
  473. if sv.ContainerInfo() != nil {
  474. list = append(list, buildContainerResource(sv.ContainerInfo()))
  475. }
  476. return list, &successResponse
  477. }
  478. func procPublishService(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  479. var sp servicePublish
  480. err := json.Unmarshal(body, &sp)
  481. if err != nil {
  482. return "", &responseStatus{Status: "Invalid body: " + err.Error(), StatusCode: http.StatusBadRequest}
  483. }
  484. n, errRsp := findNetwork(c, sp.Network, byName)
  485. if !errRsp.isOK() {
  486. return "", errRsp
  487. }
  488. var setFctList []libnetwork.EndpointOption
  489. if sp.ExposedPorts != nil {
  490. setFctList = append(setFctList, libnetwork.CreateOptionExposedPorts(sp.ExposedPorts))
  491. }
  492. if sp.PortMapping != nil {
  493. setFctList = append(setFctList, libnetwork.CreateOptionPortMapping(sp.PortMapping))
  494. }
  495. ep, err := n.CreateEndpoint(sp.Name, setFctList...)
  496. if err != nil {
  497. return "", endpointToService(convertNetworkError(err))
  498. }
  499. return ep.ID(), &createdResponse
  500. }
  501. func procUnpublishService(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  502. epT, epBy := detectEndpointTarget(vars)
  503. sv, errRsp := findService(c, epT, epBy)
  504. if !errRsp.isOK() {
  505. return nil, errRsp
  506. }
  507. err := sv.Delete()
  508. if err != nil {
  509. return nil, endpointToService(convertNetworkError(err))
  510. }
  511. return nil, &successResponse
  512. }
  513. func procAttachBackend(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  514. var bk endpointJoin
  515. err := json.Unmarshal(body, &bk)
  516. if err != nil {
  517. return nil, &responseStatus{Status: "Invalid body: " + err.Error(), StatusCode: http.StatusBadRequest}
  518. }
  519. epT, epBy := detectEndpointTarget(vars)
  520. sv, errRsp := findService(c, epT, epBy)
  521. if !errRsp.isOK() {
  522. return nil, errRsp
  523. }
  524. err = sv.Join(bk.ContainerID, bk.parseOptions()...)
  525. if err != nil {
  526. return nil, convertNetworkError(err)
  527. }
  528. return sv.Info().SandboxKey(), &successResponse
  529. }
  530. func procDetachBackend(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  531. epT, epBy := detectEndpointTarget(vars)
  532. sv, errRsp := findService(c, epT, epBy)
  533. if !errRsp.isOK() {
  534. return nil, errRsp
  535. }
  536. err := sv.Leave(vars[urlCnID])
  537. if err != nil {
  538. return nil, convertNetworkError(err)
  539. }
  540. return nil, &successResponse
  541. }
  542. /***********
  543. Utilities
  544. ************/
  545. const (
  546. byID = iota
  547. byName
  548. )
  549. func detectNetworkTarget(vars map[string]string) (string, int) {
  550. if target, ok := vars[urlNwName]; ok {
  551. return target, byName
  552. }
  553. if target, ok := vars[urlNwID]; ok {
  554. return target, byID
  555. }
  556. // vars are populated from the URL, following cannot happen
  557. panic("Missing URL variable parameter for network")
  558. }
  559. func detectEndpointTarget(vars map[string]string) (string, int) {
  560. if target, ok := vars[urlEpName]; ok {
  561. return target, byName
  562. }
  563. if target, ok := vars[urlEpID]; ok {
  564. return target, byID
  565. }
  566. // vars are populated from the URL, following cannot happen
  567. panic("Missing URL variable parameter for endpoint")
  568. }
  569. func findNetwork(c libnetwork.NetworkController, s string, by int) (libnetwork.Network, *responseStatus) {
  570. var (
  571. nw libnetwork.Network
  572. err error
  573. )
  574. switch by {
  575. case byID:
  576. nw, err = c.NetworkByID(s)
  577. case byName:
  578. nw, err = c.NetworkByName(s)
  579. default:
  580. panic(fmt.Sprintf("unexpected selector for network search: %d", by))
  581. }
  582. if err != nil {
  583. if _, ok := err.(types.NotFoundError); ok {
  584. return nil, &responseStatus{Status: "Resource not found: Network", StatusCode: http.StatusNotFound}
  585. }
  586. return nil, &responseStatus{Status: err.Error(), StatusCode: http.StatusBadRequest}
  587. }
  588. return nw, &successResponse
  589. }
  590. func findEndpoint(c libnetwork.NetworkController, ns, es string, nwBy, epBy int) (libnetwork.Endpoint, *responseStatus) {
  591. nw, errRsp := findNetwork(c, ns, nwBy)
  592. if !errRsp.isOK() {
  593. return nil, errRsp
  594. }
  595. var (
  596. err error
  597. ep libnetwork.Endpoint
  598. )
  599. switch epBy {
  600. case byID:
  601. ep, err = nw.EndpointByID(es)
  602. case byName:
  603. ep, err = nw.EndpointByName(es)
  604. default:
  605. panic(fmt.Sprintf("unexpected selector for endpoint search: %d", epBy))
  606. }
  607. if err != nil {
  608. if _, ok := err.(types.NotFoundError); ok {
  609. return nil, &responseStatus{Status: "Resource not found: Endpoint", StatusCode: http.StatusNotFound}
  610. }
  611. return nil, &responseStatus{Status: err.Error(), StatusCode: http.StatusBadRequest}
  612. }
  613. return ep, &successResponse
  614. }
  615. func findService(c libnetwork.NetworkController, svs string, svBy int) (libnetwork.Endpoint, *responseStatus) {
  616. for _, nw := range c.Networks() {
  617. var (
  618. ep libnetwork.Endpoint
  619. err error
  620. )
  621. switch svBy {
  622. case byID:
  623. ep, err = nw.EndpointByID(svs)
  624. case byName:
  625. ep, err = nw.EndpointByName(svs)
  626. default:
  627. panic(fmt.Sprintf("unexpected selector for service search: %d", svBy))
  628. }
  629. if err == nil {
  630. return ep, &successResponse
  631. } else if _, ok := err.(types.NotFoundError); !ok {
  632. return nil, convertNetworkError(err)
  633. }
  634. }
  635. return nil, &responseStatus{Status: "Service not found", StatusCode: http.StatusNotFound}
  636. }
  637. func endpointToService(rsp *responseStatus) *responseStatus {
  638. rsp.Status = strings.Replace(rsp.Status, "endpoint", "service", -1)
  639. return rsp
  640. }
  641. func convertNetworkError(err error) *responseStatus {
  642. var code int
  643. switch err.(type) {
  644. case types.BadRequestError:
  645. code = http.StatusBadRequest
  646. case types.ForbiddenError:
  647. code = http.StatusForbidden
  648. case types.NotFoundError:
  649. code = http.StatusNotFound
  650. case types.TimeoutError:
  651. code = http.StatusRequestTimeout
  652. case types.NotImplementedError:
  653. code = http.StatusNotImplemented
  654. case types.NoServiceError:
  655. code = http.StatusServiceUnavailable
  656. case types.InternalError:
  657. code = http.StatusInternalServerError
  658. default:
  659. code = http.StatusInternalServerError
  660. }
  661. return &responseStatus{Status: err.Error(), StatusCode: code}
  662. }
  663. func writeJSON(w http.ResponseWriter, code int, v interface{}) error {
  664. w.Header().Set("Content-Type", "application/json")
  665. w.WriteHeader(code)
  666. return json.NewEncoder(w).Encode(v)
  667. }