api.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952
  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/netlabel"
  10. "github.com/docker/libnetwork/types"
  11. "github.com/gorilla/mux"
  12. )
  13. var (
  14. successResponse = responseStatus{Status: "Success", StatusCode: http.StatusOK}
  15. createdResponse = responseStatus{Status: "Created", StatusCode: http.StatusCreated}
  16. mismatchResponse = responseStatus{Status: "Body/URI parameter mismatch", StatusCode: http.StatusBadRequest}
  17. badQueryResponse = responseStatus{Status: "Unsupported query", StatusCode: http.StatusBadRequest}
  18. )
  19. const (
  20. // Resource name regex
  21. // Gorilla mux encloses the passed pattern with '^' and '$'. So we need to do some tricks
  22. // to have mux eventually build a query regex which matches empty or word string (`^$|[\w]+`)
  23. regex = "[a-zA-Z_0-9-]+"
  24. qregx = "$|" + regex
  25. // Router URL variable definition
  26. nwName = "{" + urlNwName + ":" + regex + "}"
  27. nwNameQr = "{" + urlNwName + ":" + qregx + "}"
  28. nwID = "{" + urlNwID + ":" + regex + "}"
  29. nwPIDQr = "{" + urlNwPID + ":" + qregx + "}"
  30. epName = "{" + urlEpName + ":" + regex + "}"
  31. epNameQr = "{" + urlEpName + ":" + qregx + "}"
  32. epID = "{" + urlEpID + ":" + regex + "}"
  33. epPIDQr = "{" + urlEpPID + ":" + qregx + "}"
  34. sbID = "{" + urlSbID + ":" + regex + "}"
  35. sbPIDQr = "{" + urlSbPID + ":" + qregx + "}"
  36. cnIDQr = "{" + urlCnID + ":" + qregx + "}"
  37. cnPIDQr = "{" + urlCnPID + ":" + qregx + "}"
  38. // Internal URL variable name.They can be anything as
  39. // long as they do not collide with query fields.
  40. urlNwName = "network-name"
  41. urlNwID = "network-id"
  42. urlNwPID = "network-partial-id"
  43. urlEpName = "endpoint-name"
  44. urlEpID = "endpoint-id"
  45. urlEpPID = "endpoint-partial-id"
  46. urlSbID = "sandbox-id"
  47. urlSbPID = "sandbox-partial-id"
  48. urlCnID = "container-id"
  49. urlCnPID = "container-partial-id"
  50. // BridgeNetworkDriver is the built-in default for Network Driver
  51. BridgeNetworkDriver = "bridge"
  52. )
  53. // NewHTTPHandler creates and initialize the HTTP handler to serve the requests for libnetwork
  54. func NewHTTPHandler(c libnetwork.NetworkController) func(w http.ResponseWriter, req *http.Request) {
  55. h := &httpHandler{c: c}
  56. h.initRouter()
  57. return h.handleRequest
  58. }
  59. type responseStatus struct {
  60. Status string
  61. StatusCode int
  62. }
  63. func (r *responseStatus) isOK() bool {
  64. return r.StatusCode == http.StatusOK || r.StatusCode == http.StatusCreated
  65. }
  66. type processor func(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus)
  67. type httpHandler struct {
  68. c libnetwork.NetworkController
  69. r *mux.Router
  70. }
  71. func (h *httpHandler) handleRequest(w http.ResponseWriter, req *http.Request) {
  72. // Make sure the service is there
  73. if h.c == nil {
  74. http.Error(w, "NetworkController is not available", http.StatusServiceUnavailable)
  75. return
  76. }
  77. // Get handler from router and execute it
  78. h.r.ServeHTTP(w, req)
  79. }
  80. func (h *httpHandler) initRouter() {
  81. m := map[string][]struct {
  82. url string
  83. qrs []string
  84. fct processor
  85. }{
  86. "GET": {
  87. // Order matters
  88. {"/networks", []string{"name", nwNameQr}, procGetNetworks},
  89. {"/networks", []string{"partial-id", nwPIDQr}, procGetNetworks},
  90. {"/networks", nil, procGetNetworks},
  91. {"/networks/" + nwID, nil, procGetNetwork},
  92. {"/networks/" + nwID + "/endpoints", []string{"name", epNameQr}, procGetEndpoints},
  93. {"/networks/" + nwID + "/endpoints", []string{"partial-id", epPIDQr}, procGetEndpoints},
  94. {"/networks/" + nwID + "/endpoints", nil, procGetEndpoints},
  95. {"/networks/" + nwID + "/endpoints/" + epID, nil, procGetEndpoint},
  96. {"/services", []string{"network", nwNameQr}, procGetServices},
  97. {"/services", []string{"name", epNameQr}, procGetServices},
  98. {"/services", []string{"partial-id", epPIDQr}, procGetServices},
  99. {"/services", nil, procGetServices},
  100. {"/services/" + epID, nil, procGetService},
  101. {"/services/" + epID + "/backend", nil, procGetSandbox},
  102. {"/sandboxes", []string{"partial-container-id", cnPIDQr}, procGetSandboxes},
  103. {"/sandboxes", []string{"container-id", cnIDQr}, procGetSandboxes},
  104. {"/sandboxes", []string{"partial-id", sbPIDQr}, procGetSandboxes},
  105. {"/sandboxes", nil, procGetSandboxes},
  106. {"/sandboxes/" + sbID, nil, procGetSandbox},
  107. },
  108. "POST": {
  109. {"/networks", nil, procCreateNetwork},
  110. {"/networks/" + nwID + "/endpoints", nil, procCreateEndpoint},
  111. {"/networks/" + nwID + "/endpoints/" + epID + "/sandboxes", nil, procJoinEndpoint},
  112. {"/services", nil, procPublishService},
  113. {"/services/" + epID + "/backend", nil, procAttachBackend},
  114. {"/sandboxes", nil, procCreateSandbox},
  115. },
  116. "DELETE": {
  117. {"/networks/" + nwID, nil, procDeleteNetwork},
  118. {"/networks/" + nwID + "/endpoints/" + epID, nil, procDeleteEndpoint},
  119. {"/networks/" + nwID + "/endpoints/" + epID + "/sandboxes/" + sbID, nil, procLeaveEndpoint},
  120. {"/services/" + epID, nil, procUnpublishService},
  121. {"/services/" + epID + "/backend/" + sbID, nil, procDetachBackend},
  122. {"/sandboxes/" + sbID, nil, procDeleteSandbox},
  123. },
  124. }
  125. h.r = mux.NewRouter()
  126. for method, routes := range m {
  127. for _, route := range routes {
  128. r := h.r.Path("/{.*}" + route.url).Methods(method).HandlerFunc(makeHandler(h.c, route.fct))
  129. if route.qrs != nil {
  130. r.Queries(route.qrs...)
  131. }
  132. r = h.r.Path(route.url).Methods(method).HandlerFunc(makeHandler(h.c, route.fct))
  133. if route.qrs != nil {
  134. r.Queries(route.qrs...)
  135. }
  136. }
  137. }
  138. }
  139. func makeHandler(ctrl libnetwork.NetworkController, fct processor) http.HandlerFunc {
  140. return func(w http.ResponseWriter, req *http.Request) {
  141. var (
  142. body []byte
  143. err error
  144. )
  145. if req.Body != nil {
  146. body, err = ioutil.ReadAll(req.Body)
  147. if err != nil {
  148. http.Error(w, "Invalid body: "+err.Error(), http.StatusBadRequest)
  149. return
  150. }
  151. }
  152. res, rsp := fct(ctrl, mux.Vars(req), body)
  153. if !rsp.isOK() {
  154. http.Error(w, rsp.Status, rsp.StatusCode)
  155. return
  156. }
  157. if res != nil {
  158. writeJSON(w, rsp.StatusCode, res)
  159. }
  160. }
  161. }
  162. /*****************
  163. Resource Builders
  164. ******************/
  165. func buildNetworkResource(nw libnetwork.Network) *networkResource {
  166. r := &networkResource{}
  167. if nw != nil {
  168. r.Name = nw.Name()
  169. r.ID = nw.ID()
  170. r.Type = nw.Type()
  171. epl := nw.Endpoints()
  172. r.Endpoints = make([]*endpointResource, 0, len(epl))
  173. for _, e := range epl {
  174. epr := buildEndpointResource(e)
  175. r.Endpoints = append(r.Endpoints, epr)
  176. }
  177. }
  178. return r
  179. }
  180. func buildEndpointResource(ep libnetwork.Endpoint) *endpointResource {
  181. r := &endpointResource{}
  182. if ep != nil {
  183. r.Name = ep.Name()
  184. r.ID = ep.ID()
  185. r.Network = ep.Network()
  186. }
  187. return r
  188. }
  189. func buildSandboxResource(sb libnetwork.Sandbox) *sandboxResource {
  190. r := &sandboxResource{}
  191. if sb != nil {
  192. r.ID = sb.ID()
  193. r.Key = sb.Key()
  194. r.ContainerID = sb.ContainerID()
  195. }
  196. return r
  197. }
  198. /****************
  199. Options Parsers
  200. *****************/
  201. func (nc *networkCreate) parseOptions() []libnetwork.NetworkOption {
  202. var setFctList []libnetwork.NetworkOption
  203. if nc.Options != nil {
  204. setFctList = append(setFctList, libnetwork.NetworkOptionGeneric(nc.Options))
  205. }
  206. return setFctList
  207. }
  208. func (sc *sandboxCreate) parseOptions() []libnetwork.SandboxOption {
  209. var setFctList []libnetwork.SandboxOption
  210. if sc.HostName != "" {
  211. setFctList = append(setFctList, libnetwork.OptionHostname(sc.HostName))
  212. }
  213. if sc.DomainName != "" {
  214. setFctList = append(setFctList, libnetwork.OptionDomainname(sc.DomainName))
  215. }
  216. if sc.HostsPath != "" {
  217. setFctList = append(setFctList, libnetwork.OptionHostsPath(sc.HostsPath))
  218. }
  219. if sc.ResolvConfPath != "" {
  220. setFctList = append(setFctList, libnetwork.OptionResolvConfPath(sc.ResolvConfPath))
  221. }
  222. if sc.UseDefaultSandbox {
  223. setFctList = append(setFctList, libnetwork.OptionUseDefaultSandbox())
  224. }
  225. if sc.UseExternalKey {
  226. setFctList = append(setFctList, libnetwork.OptionUseExternalKey())
  227. }
  228. if sc.DNS != nil {
  229. for _, d := range sc.DNS {
  230. setFctList = append(setFctList, libnetwork.OptionDNS(d))
  231. }
  232. }
  233. if sc.ExtraHosts != nil {
  234. for _, e := range sc.ExtraHosts {
  235. setFctList = append(setFctList, libnetwork.OptionExtraHost(e.Name, e.Address))
  236. }
  237. }
  238. return setFctList
  239. }
  240. func (ej *endpointJoin) parseOptions() []libnetwork.EndpointOption {
  241. // priority will go here
  242. return []libnetwork.EndpointOption{}
  243. }
  244. /******************
  245. Process functions
  246. *******************/
  247. func processCreateDefaults(c libnetwork.NetworkController, nc *networkCreate) {
  248. if nc.NetworkType == "" {
  249. nc.NetworkType = c.Config().Daemon.DefaultDriver
  250. }
  251. if nc.NetworkType == BridgeNetworkDriver {
  252. if nc.Options == nil {
  253. nc.Options = make(map[string]interface{})
  254. }
  255. genericData, ok := nc.Options[netlabel.GenericData]
  256. if !ok {
  257. genericData = make(map[string]interface{})
  258. }
  259. gData := genericData.(map[string]interface{})
  260. if _, ok := gData["BridgeName"]; !ok {
  261. gData["BridgeName"] = nc.Name
  262. }
  263. if _, ok := gData["AllowNonDefaultBridge"]; !ok {
  264. gData["AllowNonDefaultBridge"] = "true"
  265. }
  266. nc.Options[netlabel.GenericData] = genericData
  267. }
  268. }
  269. /***************************
  270. NetworkController interface
  271. ****************************/
  272. func procCreateNetwork(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  273. var create networkCreate
  274. err := json.Unmarshal(body, &create)
  275. if err != nil {
  276. return "", &responseStatus{Status: "Invalid body: " + err.Error(), StatusCode: http.StatusBadRequest}
  277. }
  278. processCreateDefaults(c, &create)
  279. nw, err := c.NewNetwork(create.NetworkType, create.Name, create.parseOptions()...)
  280. if err != nil {
  281. return "", convertNetworkError(err)
  282. }
  283. return nw.ID(), &createdResponse
  284. }
  285. func procGetNetwork(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  286. t, by := detectNetworkTarget(vars)
  287. nw, errRsp := findNetwork(c, t, by)
  288. if !errRsp.isOK() {
  289. return nil, errRsp
  290. }
  291. return buildNetworkResource(nw), &successResponse
  292. }
  293. func procGetNetworks(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  294. var list []*networkResource
  295. // Look for query filters and validate
  296. name, queryByName := vars[urlNwName]
  297. shortID, queryByPid := vars[urlNwPID]
  298. if queryByName && queryByPid {
  299. return nil, &badQueryResponse
  300. }
  301. if queryByName {
  302. if nw, errRsp := findNetwork(c, name, byName); errRsp.isOK() {
  303. list = append(list, buildNetworkResource(nw))
  304. }
  305. } else if queryByPid {
  306. // Return all the prefix-matching networks
  307. l := func(nw libnetwork.Network) bool {
  308. if strings.HasPrefix(nw.ID(), shortID) {
  309. list = append(list, buildNetworkResource(nw))
  310. }
  311. return false
  312. }
  313. c.WalkNetworks(l)
  314. } else {
  315. for _, nw := range c.Networks() {
  316. list = append(list, buildNetworkResource(nw))
  317. }
  318. }
  319. return list, &successResponse
  320. }
  321. func procCreateSandbox(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  322. var create sandboxCreate
  323. err := json.Unmarshal(body, &create)
  324. if err != nil {
  325. return "", &responseStatus{Status: "Invalid body: " + err.Error(), StatusCode: http.StatusBadRequest}
  326. }
  327. sb, err := c.NewSandbox(create.ContainerID, create.parseOptions()...)
  328. if err != nil {
  329. return "", convertNetworkError(err)
  330. }
  331. return sb.ID(), &createdResponse
  332. }
  333. /******************
  334. Network interface
  335. *******************/
  336. func procCreateEndpoint(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  337. var ec endpointCreate
  338. err := json.Unmarshal(body, &ec)
  339. if err != nil {
  340. return "", &responseStatus{Status: "Invalid body: " + err.Error(), StatusCode: http.StatusBadRequest}
  341. }
  342. nwT, nwBy := detectNetworkTarget(vars)
  343. n, errRsp := findNetwork(c, nwT, nwBy)
  344. if !errRsp.isOK() {
  345. return "", errRsp
  346. }
  347. var setFctList []libnetwork.EndpointOption
  348. if ec.ExposedPorts != nil {
  349. setFctList = append(setFctList, libnetwork.CreateOptionExposedPorts(ec.ExposedPorts))
  350. }
  351. if ec.PortMapping != nil {
  352. setFctList = append(setFctList, libnetwork.CreateOptionPortMapping(ec.PortMapping))
  353. }
  354. ep, err := n.CreateEndpoint(ec.Name, setFctList...)
  355. if err != nil {
  356. return "", convertNetworkError(err)
  357. }
  358. return ep.ID(), &createdResponse
  359. }
  360. func procGetEndpoint(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. return buildEndpointResource(ep), &successResponse
  368. }
  369. func procGetEndpoints(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  370. // Look for query filters and validate
  371. name, queryByName := vars[urlEpName]
  372. shortID, queryByPid := vars[urlEpPID]
  373. if queryByName && queryByPid {
  374. return nil, &badQueryResponse
  375. }
  376. nwT, nwBy := detectNetworkTarget(vars)
  377. nw, errRsp := findNetwork(c, nwT, nwBy)
  378. if !errRsp.isOK() {
  379. return nil, errRsp
  380. }
  381. var list []*endpointResource
  382. // If query parameter is specified, return a filtered collection
  383. if queryByName {
  384. if ep, errRsp := findEndpoint(c, nwT, name, nwBy, byName); errRsp.isOK() {
  385. list = append(list, buildEndpointResource(ep))
  386. }
  387. } else if queryByPid {
  388. // Return all the prefix-matching endpoints
  389. l := func(ep libnetwork.Endpoint) bool {
  390. if strings.HasPrefix(ep.ID(), shortID) {
  391. list = append(list, buildEndpointResource(ep))
  392. }
  393. return false
  394. }
  395. nw.WalkEndpoints(l)
  396. } else {
  397. for _, ep := range nw.Endpoints() {
  398. epr := buildEndpointResource(ep)
  399. list = append(list, epr)
  400. }
  401. }
  402. return list, &successResponse
  403. }
  404. func procDeleteNetwork(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  405. target, by := detectNetworkTarget(vars)
  406. nw, errRsp := findNetwork(c, target, by)
  407. if !errRsp.isOK() {
  408. return nil, errRsp
  409. }
  410. err := nw.Delete()
  411. if err != nil {
  412. return nil, convertNetworkError(err)
  413. }
  414. return nil, &successResponse
  415. }
  416. /******************
  417. Endpoint interface
  418. *******************/
  419. func procJoinEndpoint(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  420. var ej endpointJoin
  421. err := json.Unmarshal(body, &ej)
  422. if err != nil {
  423. return nil, &responseStatus{Status: "Invalid body: " + err.Error(), StatusCode: http.StatusBadRequest}
  424. }
  425. nwT, nwBy := detectNetworkTarget(vars)
  426. epT, epBy := detectEndpointTarget(vars)
  427. ep, errRsp := findEndpoint(c, nwT, epT, nwBy, epBy)
  428. if !errRsp.isOK() {
  429. return nil, errRsp
  430. }
  431. sb, errRsp := findSandbox(c, ej.SandboxID, byID)
  432. if !errRsp.isOK() {
  433. return nil, errRsp
  434. }
  435. err = ep.Join(sb)
  436. if err != nil {
  437. return nil, convertNetworkError(err)
  438. }
  439. return sb.Key(), &successResponse
  440. }
  441. func procLeaveEndpoint(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  442. nwT, nwBy := detectNetworkTarget(vars)
  443. epT, epBy := detectEndpointTarget(vars)
  444. ep, errRsp := findEndpoint(c, nwT, epT, nwBy, epBy)
  445. if !errRsp.isOK() {
  446. return nil, errRsp
  447. }
  448. sb, errRsp := findSandbox(c, vars[urlSbID], byID)
  449. if !errRsp.isOK() {
  450. return nil, errRsp
  451. }
  452. err := ep.Leave(sb)
  453. if err != nil {
  454. return nil, convertNetworkError(err)
  455. }
  456. return nil, &successResponse
  457. }
  458. func procDeleteEndpoint(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  459. nwT, nwBy := detectNetworkTarget(vars)
  460. epT, epBy := detectEndpointTarget(vars)
  461. ep, errRsp := findEndpoint(c, nwT, epT, nwBy, epBy)
  462. if !errRsp.isOK() {
  463. return nil, errRsp
  464. }
  465. err := ep.Delete()
  466. if err != nil {
  467. return nil, convertNetworkError(err)
  468. }
  469. return nil, &successResponse
  470. }
  471. /******************
  472. Service interface
  473. *******************/
  474. func procGetServices(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  475. // Look for query filters and validate
  476. nwName, filterByNwName := vars[urlNwName]
  477. svName, queryBySvName := vars[urlEpName]
  478. shortID, queryBySvPID := vars[urlEpPID]
  479. if filterByNwName && queryBySvName || filterByNwName && queryBySvPID || queryBySvName && queryBySvPID {
  480. return nil, &badQueryResponse
  481. }
  482. var list []*endpointResource
  483. switch {
  484. case filterByNwName:
  485. // return all service present on the specified network
  486. nw, errRsp := findNetwork(c, nwName, byName)
  487. if !errRsp.isOK() {
  488. return list, &successResponse
  489. }
  490. for _, ep := range nw.Endpoints() {
  491. epr := buildEndpointResource(ep)
  492. list = append(list, epr)
  493. }
  494. case queryBySvName:
  495. // Look in each network for the service with the specified name
  496. l := func(ep libnetwork.Endpoint) bool {
  497. if ep.Name() == svName {
  498. list = append(list, buildEndpointResource(ep))
  499. return true
  500. }
  501. return false
  502. }
  503. for _, nw := range c.Networks() {
  504. nw.WalkEndpoints(l)
  505. }
  506. case queryBySvPID:
  507. // Return all the prefix-matching services
  508. l := func(ep libnetwork.Endpoint) bool {
  509. if strings.HasPrefix(ep.ID(), shortID) {
  510. list = append(list, buildEndpointResource(ep))
  511. }
  512. return false
  513. }
  514. for _, nw := range c.Networks() {
  515. nw.WalkEndpoints(l)
  516. }
  517. default:
  518. for _, nw := range c.Networks() {
  519. for _, ep := range nw.Endpoints() {
  520. epr := buildEndpointResource(ep)
  521. list = append(list, epr)
  522. }
  523. }
  524. }
  525. return list, &successResponse
  526. }
  527. func procGetService(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  528. epT, epBy := detectEndpointTarget(vars)
  529. sv, errRsp := findService(c, epT, epBy)
  530. if !errRsp.isOK() {
  531. return nil, endpointToService(errRsp)
  532. }
  533. return buildEndpointResource(sv), &successResponse
  534. }
  535. func procPublishService(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  536. var sp servicePublish
  537. err := json.Unmarshal(body, &sp)
  538. if err != nil {
  539. return "", &responseStatus{Status: "Invalid body: " + err.Error(), StatusCode: http.StatusBadRequest}
  540. }
  541. n, errRsp := findNetwork(c, sp.Network, byName)
  542. if !errRsp.isOK() {
  543. return "", errRsp
  544. }
  545. var setFctList []libnetwork.EndpointOption
  546. if sp.ExposedPorts != nil {
  547. setFctList = append(setFctList, libnetwork.CreateOptionExposedPorts(sp.ExposedPorts))
  548. }
  549. if sp.PortMapping != nil {
  550. setFctList = append(setFctList, libnetwork.CreateOptionPortMapping(sp.PortMapping))
  551. }
  552. ep, err := n.CreateEndpoint(sp.Name, setFctList...)
  553. if err != nil {
  554. return "", endpointToService(convertNetworkError(err))
  555. }
  556. return ep.ID(), &createdResponse
  557. }
  558. func procUnpublishService(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  559. epT, epBy := detectEndpointTarget(vars)
  560. sv, errRsp := findService(c, epT, epBy)
  561. if !errRsp.isOK() {
  562. return nil, errRsp
  563. }
  564. err := sv.Delete()
  565. if err != nil {
  566. return nil, endpointToService(convertNetworkError(err))
  567. }
  568. return nil, &successResponse
  569. }
  570. func procAttachBackend(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  571. var bk endpointJoin
  572. err := json.Unmarshal(body, &bk)
  573. if err != nil {
  574. return nil, &responseStatus{Status: "Invalid body: " + err.Error(), StatusCode: http.StatusBadRequest}
  575. }
  576. epT, epBy := detectEndpointTarget(vars)
  577. sv, errRsp := findService(c, epT, epBy)
  578. if !errRsp.isOK() {
  579. return nil, errRsp
  580. }
  581. sb, errRsp := findSandbox(c, bk.SandboxID, byID)
  582. if !errRsp.isOK() {
  583. return nil, errRsp
  584. }
  585. err = sv.Join(sb)
  586. if err != nil {
  587. return nil, convertNetworkError(err)
  588. }
  589. return sb.Key(), &successResponse
  590. }
  591. func procDetachBackend(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  592. epT, epBy := detectEndpointTarget(vars)
  593. sv, errRsp := findService(c, epT, epBy)
  594. if !errRsp.isOK() {
  595. return nil, errRsp
  596. }
  597. sb, errRsp := findSandbox(c, vars[urlSbID], byID)
  598. if !errRsp.isOK() {
  599. return nil, errRsp
  600. }
  601. err := sv.Leave(sb)
  602. if err != nil {
  603. return nil, convertNetworkError(err)
  604. }
  605. return nil, &successResponse
  606. }
  607. /******************
  608. Sandbox interface
  609. *******************/
  610. func procGetSandbox(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  611. if epT, ok := vars[urlEpID]; ok {
  612. sv, errRsp := findService(c, epT, byID)
  613. if !errRsp.isOK() {
  614. return nil, endpointToService(errRsp)
  615. }
  616. return buildSandboxResource(sv.Info().Sandbox()), &successResponse
  617. }
  618. sbT, by := detectSandboxTarget(vars)
  619. sb, errRsp := findSandbox(c, sbT, by)
  620. if !errRsp.isOK() {
  621. return nil, errRsp
  622. }
  623. return buildSandboxResource(sb), &successResponse
  624. }
  625. type cndFnMkr func(string) cndFn
  626. type cndFn func(libnetwork.Sandbox) bool
  627. // list of (query type, condition function makers) couples
  628. var cndMkrList = []struct {
  629. identifier string
  630. maker cndFnMkr
  631. }{
  632. {urlSbPID, func(id string) cndFn {
  633. return func(sb libnetwork.Sandbox) bool { return strings.HasPrefix(sb.ID(), id) }
  634. }},
  635. {urlCnID, func(id string) cndFn {
  636. return func(sb libnetwork.Sandbox) bool { return sb.ContainerID() == id }
  637. }},
  638. {urlCnPID, func(id string) cndFn {
  639. return func(sb libnetwork.Sandbox) bool { return strings.HasPrefix(sb.ContainerID(), id) }
  640. }},
  641. }
  642. func getQueryCondition(vars map[string]string) func(libnetwork.Sandbox) bool {
  643. for _, im := range cndMkrList {
  644. if val, ok := vars[im.identifier]; ok {
  645. return im.maker(val)
  646. }
  647. }
  648. return func(sb libnetwork.Sandbox) bool { return true }
  649. }
  650. func sandboxWalker(condition cndFn, list *[]*sandboxResource) libnetwork.SandboxWalker {
  651. return func(sb libnetwork.Sandbox) bool {
  652. if condition(sb) {
  653. *list = append(*list, buildSandboxResource(sb))
  654. }
  655. return false
  656. }
  657. }
  658. func procGetSandboxes(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  659. var list []*sandboxResource
  660. cnd := getQueryCondition(vars)
  661. c.WalkSandboxes(sandboxWalker(cnd, &list))
  662. return list, &successResponse
  663. }
  664. func procDeleteSandbox(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  665. sbT, by := detectSandboxTarget(vars)
  666. sb, errRsp := findSandbox(c, sbT, by)
  667. if !errRsp.isOK() {
  668. return nil, errRsp
  669. }
  670. err := sb.Delete()
  671. if err != nil {
  672. return nil, convertNetworkError(err)
  673. }
  674. return nil, &successResponse
  675. }
  676. /***********
  677. Utilities
  678. ************/
  679. const (
  680. byID = iota
  681. byName
  682. )
  683. func detectNetworkTarget(vars map[string]string) (string, int) {
  684. if target, ok := vars[urlNwName]; ok {
  685. return target, byName
  686. }
  687. if target, ok := vars[urlNwID]; ok {
  688. return target, byID
  689. }
  690. // vars are populated from the URL, following cannot happen
  691. panic("Missing URL variable parameter for network")
  692. }
  693. func detectSandboxTarget(vars map[string]string) (string, int) {
  694. if target, ok := vars[urlSbID]; ok {
  695. return target, byID
  696. }
  697. // vars are populated from the URL, following cannot happen
  698. panic("Missing URL variable parameter for sandbox")
  699. }
  700. func detectEndpointTarget(vars map[string]string) (string, int) {
  701. if target, ok := vars[urlEpName]; ok {
  702. return target, byName
  703. }
  704. if target, ok := vars[urlEpID]; ok {
  705. return target, byID
  706. }
  707. // vars are populated from the URL, following cannot happen
  708. panic("Missing URL variable parameter for endpoint")
  709. }
  710. func findNetwork(c libnetwork.NetworkController, s string, by int) (libnetwork.Network, *responseStatus) {
  711. var (
  712. nw libnetwork.Network
  713. err error
  714. )
  715. switch by {
  716. case byID:
  717. nw, err = c.NetworkByID(s)
  718. case byName:
  719. if s == "" {
  720. s = c.Config().Daemon.DefaultNetwork
  721. }
  722. nw, err = c.NetworkByName(s)
  723. default:
  724. panic(fmt.Sprintf("unexpected selector for network search: %d", by))
  725. }
  726. if err != nil {
  727. if _, ok := err.(types.NotFoundError); ok {
  728. return nil, &responseStatus{Status: "Resource not found: Network", StatusCode: http.StatusNotFound}
  729. }
  730. return nil, &responseStatus{Status: err.Error(), StatusCode: http.StatusBadRequest}
  731. }
  732. return nw, &successResponse
  733. }
  734. func findSandbox(c libnetwork.NetworkController, s string, by int) (libnetwork.Sandbox, *responseStatus) {
  735. var (
  736. sb libnetwork.Sandbox
  737. err error
  738. )
  739. switch by {
  740. case byID:
  741. sb, err = c.SandboxByID(s)
  742. default:
  743. panic(fmt.Sprintf("unexpected selector for sandbox search: %d", by))
  744. }
  745. if err != nil {
  746. if _, ok := err.(types.NotFoundError); ok {
  747. return nil, &responseStatus{Status: "Resource not found: Sandbox", StatusCode: http.StatusNotFound}
  748. }
  749. return nil, &responseStatus{Status: err.Error(), StatusCode: http.StatusBadRequest}
  750. }
  751. return sb, &successResponse
  752. }
  753. func findEndpoint(c libnetwork.NetworkController, ns, es string, nwBy, epBy int) (libnetwork.Endpoint, *responseStatus) {
  754. nw, errRsp := findNetwork(c, ns, nwBy)
  755. if !errRsp.isOK() {
  756. return nil, errRsp
  757. }
  758. var (
  759. err error
  760. ep libnetwork.Endpoint
  761. )
  762. switch epBy {
  763. case byID:
  764. ep, err = nw.EndpointByID(es)
  765. case byName:
  766. ep, err = nw.EndpointByName(es)
  767. default:
  768. panic(fmt.Sprintf("unexpected selector for endpoint search: %d", epBy))
  769. }
  770. if err != nil {
  771. if _, ok := err.(types.NotFoundError); ok {
  772. return nil, &responseStatus{Status: "Resource not found: Endpoint", StatusCode: http.StatusNotFound}
  773. }
  774. return nil, &responseStatus{Status: err.Error(), StatusCode: http.StatusBadRequest}
  775. }
  776. return ep, &successResponse
  777. }
  778. func findService(c libnetwork.NetworkController, svs string, svBy int) (libnetwork.Endpoint, *responseStatus) {
  779. for _, nw := range c.Networks() {
  780. var (
  781. ep libnetwork.Endpoint
  782. err error
  783. )
  784. switch svBy {
  785. case byID:
  786. ep, err = nw.EndpointByID(svs)
  787. case byName:
  788. ep, err = nw.EndpointByName(svs)
  789. default:
  790. panic(fmt.Sprintf("unexpected selector for service search: %d", svBy))
  791. }
  792. if err == nil {
  793. return ep, &successResponse
  794. } else if _, ok := err.(types.NotFoundError); !ok {
  795. return nil, convertNetworkError(err)
  796. }
  797. }
  798. return nil, &responseStatus{Status: "Service not found", StatusCode: http.StatusNotFound}
  799. }
  800. func endpointToService(rsp *responseStatus) *responseStatus {
  801. rsp.Status = strings.Replace(rsp.Status, "endpoint", "service", -1)
  802. return rsp
  803. }
  804. func convertNetworkError(err error) *responseStatus {
  805. var code int
  806. switch err.(type) {
  807. case types.BadRequestError:
  808. code = http.StatusBadRequest
  809. case types.ForbiddenError:
  810. code = http.StatusForbidden
  811. case types.NotFoundError:
  812. code = http.StatusNotFound
  813. case types.TimeoutError:
  814. code = http.StatusRequestTimeout
  815. case types.NotImplementedError:
  816. code = http.StatusNotImplemented
  817. case types.NoServiceError:
  818. code = http.StatusServiceUnavailable
  819. case types.InternalError:
  820. code = http.StatusInternalServerError
  821. default:
  822. code = http.StatusInternalServerError
  823. }
  824. return &responseStatus{Status: err.Error(), StatusCode: code}
  825. }
  826. func writeJSON(w http.ResponseWriter, code int, v interface{}) error {
  827. w.Header().Set("Content-Type", "application/json")
  828. w.WriteHeader(code)
  829. return json.NewEncoder(w).Encode(v)
  830. }