api.go 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978
  1. package api
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "io/ioutil"
  6. "net/http"
  7. "strconv"
  8. "strings"
  9. "github.com/docker/libnetwork"
  10. "github.com/docker/libnetwork/netlabel"
  11. "github.com/docker/libnetwork/netutils"
  12. "github.com/docker/libnetwork/types"
  13. "github.com/gorilla/mux"
  14. )
  15. var (
  16. successResponse = responseStatus{Status: "Success", StatusCode: http.StatusOK}
  17. createdResponse = responseStatus{Status: "Created", StatusCode: http.StatusCreated}
  18. mismatchResponse = responseStatus{Status: "Body/URI parameter mismatch", StatusCode: http.StatusBadRequest}
  19. badQueryResponse = responseStatus{Status: "Unsupported query", StatusCode: http.StatusBadRequest}
  20. )
  21. const (
  22. // Resource name regex
  23. // Gorilla mux encloses the passed pattern with '^' and '$'. So we need to do some tricks
  24. // to have mux eventually build a query regex which matches empty or word string (`^$|[\w]+`)
  25. regex = "[a-zA-Z_0-9-]+"
  26. qregx = "$|" + regex
  27. // Router URL variable definition
  28. nwName = "{" + urlNwName + ":" + regex + "}"
  29. nwNameQr = "{" + urlNwName + ":" + qregx + "}"
  30. nwID = "{" + urlNwID + ":" + regex + "}"
  31. nwPIDQr = "{" + urlNwPID + ":" + qregx + "}"
  32. epName = "{" + urlEpName + ":" + regex + "}"
  33. epNameQr = "{" + urlEpName + ":" + qregx + "}"
  34. epID = "{" + urlEpID + ":" + regex + "}"
  35. epPIDQr = "{" + urlEpPID + ":" + qregx + "}"
  36. sbID = "{" + urlSbID + ":" + regex + "}"
  37. sbPIDQr = "{" + urlSbPID + ":" + qregx + "}"
  38. cnIDQr = "{" + urlCnID + ":" + qregx + "}"
  39. cnPIDQr = "{" + urlCnPID + ":" + qregx + "}"
  40. // Internal URL variable name.They can be anything as
  41. // long as they do not collide with query fields.
  42. urlNwName = "network-name"
  43. urlNwID = "network-id"
  44. urlNwPID = "network-partial-id"
  45. urlEpName = "endpoint-name"
  46. urlEpID = "endpoint-id"
  47. urlEpPID = "endpoint-partial-id"
  48. urlSbID = "sandbox-id"
  49. urlSbPID = "sandbox-partial-id"
  50. urlCnID = "container-id"
  51. urlCnPID = "container-partial-id"
  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 (sc *sandboxCreate) parseOptions() []libnetwork.SandboxOption {
  202. var setFctList []libnetwork.SandboxOption
  203. if sc.HostName != "" {
  204. setFctList = append(setFctList, libnetwork.OptionHostname(sc.HostName))
  205. }
  206. if sc.DomainName != "" {
  207. setFctList = append(setFctList, libnetwork.OptionDomainname(sc.DomainName))
  208. }
  209. if sc.HostsPath != "" {
  210. setFctList = append(setFctList, libnetwork.OptionHostsPath(sc.HostsPath))
  211. }
  212. if sc.ResolvConfPath != "" {
  213. setFctList = append(setFctList, libnetwork.OptionResolvConfPath(sc.ResolvConfPath))
  214. }
  215. if sc.UseDefaultSandbox {
  216. setFctList = append(setFctList, libnetwork.OptionUseDefaultSandbox())
  217. }
  218. if sc.UseExternalKey {
  219. setFctList = append(setFctList, libnetwork.OptionUseExternalKey())
  220. }
  221. if sc.DNS != nil {
  222. for _, d := range sc.DNS {
  223. setFctList = append(setFctList, libnetwork.OptionDNS(d))
  224. }
  225. }
  226. if sc.ExtraHosts != nil {
  227. for _, e := range sc.ExtraHosts {
  228. setFctList = append(setFctList, libnetwork.OptionExtraHost(e.Name, e.Address))
  229. }
  230. }
  231. return setFctList
  232. }
  233. func (ej *endpointJoin) parseOptions() []libnetwork.EndpointOption {
  234. // priority will go here
  235. return []libnetwork.EndpointOption{}
  236. }
  237. /******************
  238. Process functions
  239. *******************/
  240. func processCreateDefaults(c libnetwork.NetworkController, nc *networkCreate) {
  241. if nc.NetworkType == "" {
  242. nc.NetworkType = c.Config().Daemon.DefaultDriver
  243. }
  244. }
  245. /***************************
  246. NetworkController interface
  247. ****************************/
  248. func procCreateNetwork(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  249. var create networkCreate
  250. err := json.Unmarshal(body, &create)
  251. if err != nil {
  252. return nil, &responseStatus{Status: "Invalid body: " + err.Error(), StatusCode: http.StatusBadRequest}
  253. }
  254. processCreateDefaults(c, &create)
  255. options := []libnetwork.NetworkOption{}
  256. if val, ok := create.NetworkOpts[netlabel.Internal]; ok {
  257. internal, err := strconv.ParseBool(val)
  258. if err != nil {
  259. return nil, &responseStatus{Status: err.Error(), StatusCode: http.StatusBadRequest}
  260. }
  261. if internal {
  262. options = append(options, libnetwork.NetworkOptionInternalNetwork())
  263. }
  264. }
  265. if val, ok := create.NetworkOpts[netlabel.EnableIPv6]; ok {
  266. enableIPv6, err := strconv.ParseBool(val)
  267. if err != nil {
  268. return nil, &responseStatus{Status: err.Error(), StatusCode: http.StatusBadRequest}
  269. }
  270. options = append(options, libnetwork.NetworkOptionEnableIPv6(enableIPv6))
  271. }
  272. if len(create.DriverOpts) > 0 {
  273. options = append(options, libnetwork.NetworkOptionDriverOpts(create.DriverOpts))
  274. }
  275. nw, err := c.NewNetwork(create.NetworkType, create.Name, options...)
  276. if err != nil {
  277. return nil, convertNetworkError(err)
  278. }
  279. return nw.ID(), &createdResponse
  280. }
  281. func procGetNetwork(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  282. t, by := detectNetworkTarget(vars)
  283. nw, errRsp := findNetwork(c, t, by)
  284. if !errRsp.isOK() {
  285. return nil, errRsp
  286. }
  287. return buildNetworkResource(nw), &successResponse
  288. }
  289. func procGetNetworks(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  290. var list []*networkResource
  291. // Look for query filters and validate
  292. name, queryByName := vars[urlNwName]
  293. shortID, queryByPid := vars[urlNwPID]
  294. if queryByName && queryByPid {
  295. return nil, &badQueryResponse
  296. }
  297. if queryByName {
  298. if nw, errRsp := findNetwork(c, name, byName); errRsp.isOK() {
  299. list = append(list, buildNetworkResource(nw))
  300. }
  301. } else if queryByPid {
  302. // Return all the prefix-matching networks
  303. l := func(nw libnetwork.Network) bool {
  304. if strings.HasPrefix(nw.ID(), shortID) {
  305. list = append(list, buildNetworkResource(nw))
  306. }
  307. return false
  308. }
  309. c.WalkNetworks(l)
  310. } else {
  311. for _, nw := range c.Networks() {
  312. list = append(list, buildNetworkResource(nw))
  313. }
  314. }
  315. return list, &successResponse
  316. }
  317. func procCreateSandbox(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  318. var create sandboxCreate
  319. err := json.Unmarshal(body, &create)
  320. if err != nil {
  321. return "", &responseStatus{Status: "Invalid body: " + err.Error(), StatusCode: http.StatusBadRequest}
  322. }
  323. sb, err := c.NewSandbox(create.ContainerID, create.parseOptions()...)
  324. if err != nil {
  325. return "", convertNetworkError(err)
  326. }
  327. return sb.ID(), &createdResponse
  328. }
  329. /******************
  330. Network interface
  331. *******************/
  332. func procCreateEndpoint(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  333. var ec endpointCreate
  334. err := json.Unmarshal(body, &ec)
  335. if err != nil {
  336. return "", &responseStatus{Status: "Invalid body: " + err.Error(), StatusCode: http.StatusBadRequest}
  337. }
  338. nwT, nwBy := detectNetworkTarget(vars)
  339. n, errRsp := findNetwork(c, nwT, nwBy)
  340. if !errRsp.isOK() {
  341. return "", errRsp
  342. }
  343. var setFctList []libnetwork.EndpointOption
  344. if ec.ExposedPorts != nil {
  345. setFctList = append(setFctList, libnetwork.CreateOptionExposedPorts(ec.ExposedPorts))
  346. }
  347. if ec.PortMapping != nil {
  348. setFctList = append(setFctList, libnetwork.CreateOptionPortMapping(ec.PortMapping))
  349. }
  350. for _, str := range ec.MyAliases {
  351. setFctList = append(setFctList, libnetwork.CreateOptionMyAlias(str))
  352. }
  353. ep, err := n.CreateEndpoint(ec.Name, setFctList...)
  354. if err != nil {
  355. return "", convertNetworkError(err)
  356. }
  357. return ep.ID(), &createdResponse
  358. }
  359. func procGetEndpoint(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  360. nwT, nwBy := detectNetworkTarget(vars)
  361. epT, epBy := detectEndpointTarget(vars)
  362. ep, errRsp := findEndpoint(c, nwT, epT, nwBy, epBy)
  363. if !errRsp.isOK() {
  364. return nil, errRsp
  365. }
  366. return buildEndpointResource(ep), &successResponse
  367. }
  368. func procGetEndpoints(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  369. // Look for query filters and validate
  370. name, queryByName := vars[urlEpName]
  371. shortID, queryByPid := vars[urlEpPID]
  372. if queryByName && queryByPid {
  373. return nil, &badQueryResponse
  374. }
  375. nwT, nwBy := detectNetworkTarget(vars)
  376. nw, errRsp := findNetwork(c, nwT, nwBy)
  377. if !errRsp.isOK() {
  378. return nil, errRsp
  379. }
  380. var list []*endpointResource
  381. // If query parameter is specified, return a filtered collection
  382. if queryByName {
  383. if ep, errRsp := findEndpoint(c, nwT, name, nwBy, byName); errRsp.isOK() {
  384. list = append(list, buildEndpointResource(ep))
  385. }
  386. } else if queryByPid {
  387. // Return all the prefix-matching endpoints
  388. l := func(ep libnetwork.Endpoint) bool {
  389. if strings.HasPrefix(ep.ID(), shortID) {
  390. list = append(list, buildEndpointResource(ep))
  391. }
  392. return false
  393. }
  394. nw.WalkEndpoints(l)
  395. } else {
  396. for _, ep := range nw.Endpoints() {
  397. epr := buildEndpointResource(ep)
  398. list = append(list, epr)
  399. }
  400. }
  401. return list, &successResponse
  402. }
  403. func procDeleteNetwork(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  404. target, by := detectNetworkTarget(vars)
  405. nw, errRsp := findNetwork(c, target, by)
  406. if !errRsp.isOK() {
  407. return nil, errRsp
  408. }
  409. err := nw.Delete()
  410. if err != nil {
  411. return nil, convertNetworkError(err)
  412. }
  413. return nil, &successResponse
  414. }
  415. /******************
  416. Endpoint interface
  417. *******************/
  418. func procJoinEndpoint(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  419. var ej endpointJoin
  420. var setFctList []libnetwork.EndpointOption
  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. for _, str := range ej.Aliases {
  436. name, alias, err := netutils.ParseAlias(str)
  437. if err != nil {
  438. return "", convertNetworkError(err)
  439. }
  440. setFctList = append(setFctList, libnetwork.CreateOptionAlias(name, alias))
  441. }
  442. err = ep.Join(sb, setFctList...)
  443. if err != nil {
  444. return nil, convertNetworkError(err)
  445. }
  446. return sb.Key(), &successResponse
  447. }
  448. func procLeaveEndpoint(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  449. nwT, nwBy := detectNetworkTarget(vars)
  450. epT, epBy := detectEndpointTarget(vars)
  451. ep, errRsp := findEndpoint(c, nwT, epT, nwBy, epBy)
  452. if !errRsp.isOK() {
  453. return nil, errRsp
  454. }
  455. sb, errRsp := findSandbox(c, vars[urlSbID], byID)
  456. if !errRsp.isOK() {
  457. return nil, errRsp
  458. }
  459. err := ep.Leave(sb)
  460. if err != nil {
  461. return nil, convertNetworkError(err)
  462. }
  463. return nil, &successResponse
  464. }
  465. func procDeleteEndpoint(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  466. nwT, nwBy := detectNetworkTarget(vars)
  467. epT, epBy := detectEndpointTarget(vars)
  468. ep, errRsp := findEndpoint(c, nwT, epT, nwBy, epBy)
  469. if !errRsp.isOK() {
  470. return nil, errRsp
  471. }
  472. err := ep.Delete(false)
  473. if err != nil {
  474. return nil, convertNetworkError(err)
  475. }
  476. return nil, &successResponse
  477. }
  478. /******************
  479. Service interface
  480. *******************/
  481. func procGetServices(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  482. // Look for query filters and validate
  483. nwName, filterByNwName := vars[urlNwName]
  484. svName, queryBySvName := vars[urlEpName]
  485. shortID, queryBySvPID := vars[urlEpPID]
  486. if filterByNwName && queryBySvName || filterByNwName && queryBySvPID || queryBySvName && queryBySvPID {
  487. return nil, &badQueryResponse
  488. }
  489. var list []*endpointResource
  490. switch {
  491. case filterByNwName:
  492. // return all service present on the specified network
  493. nw, errRsp := findNetwork(c, nwName, byName)
  494. if !errRsp.isOK() {
  495. return list, &successResponse
  496. }
  497. for _, ep := range nw.Endpoints() {
  498. epr := buildEndpointResource(ep)
  499. list = append(list, epr)
  500. }
  501. case queryBySvName:
  502. // Look in each network for the service with the specified name
  503. l := func(ep libnetwork.Endpoint) bool {
  504. if ep.Name() == svName {
  505. list = append(list, buildEndpointResource(ep))
  506. return true
  507. }
  508. return false
  509. }
  510. for _, nw := range c.Networks() {
  511. nw.WalkEndpoints(l)
  512. }
  513. case queryBySvPID:
  514. // Return all the prefix-matching services
  515. l := func(ep libnetwork.Endpoint) bool {
  516. if strings.HasPrefix(ep.ID(), shortID) {
  517. list = append(list, buildEndpointResource(ep))
  518. }
  519. return false
  520. }
  521. for _, nw := range c.Networks() {
  522. nw.WalkEndpoints(l)
  523. }
  524. default:
  525. for _, nw := range c.Networks() {
  526. for _, ep := range nw.Endpoints() {
  527. epr := buildEndpointResource(ep)
  528. list = append(list, epr)
  529. }
  530. }
  531. }
  532. return list, &successResponse
  533. }
  534. func procGetService(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  535. epT, epBy := detectEndpointTarget(vars)
  536. sv, errRsp := findService(c, epT, epBy)
  537. if !errRsp.isOK() {
  538. return nil, endpointToService(errRsp)
  539. }
  540. return buildEndpointResource(sv), &successResponse
  541. }
  542. func procPublishService(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  543. var sp servicePublish
  544. err := json.Unmarshal(body, &sp)
  545. if err != nil {
  546. return "", &responseStatus{Status: "Invalid body: " + err.Error(), StatusCode: http.StatusBadRequest}
  547. }
  548. n, errRsp := findNetwork(c, sp.Network, byName)
  549. if !errRsp.isOK() {
  550. return "", errRsp
  551. }
  552. var setFctList []libnetwork.EndpointOption
  553. if sp.ExposedPorts != nil {
  554. setFctList = append(setFctList, libnetwork.CreateOptionExposedPorts(sp.ExposedPorts))
  555. }
  556. if sp.PortMapping != nil {
  557. setFctList = append(setFctList, libnetwork.CreateOptionPortMapping(sp.PortMapping))
  558. }
  559. for _, str := range sp.MyAliases {
  560. setFctList = append(setFctList, libnetwork.CreateOptionMyAlias(str))
  561. }
  562. ep, err := n.CreateEndpoint(sp.Name, setFctList...)
  563. if err != nil {
  564. return "", endpointToService(convertNetworkError(err))
  565. }
  566. return ep.ID(), &createdResponse
  567. }
  568. func procUnpublishService(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  569. var sd serviceDelete
  570. if body != nil {
  571. err := json.Unmarshal(body, &sd)
  572. if err != nil {
  573. return "", &responseStatus{Status: "Invalid body: " + err.Error(), StatusCode: http.StatusBadRequest}
  574. }
  575. }
  576. epT, epBy := detectEndpointTarget(vars)
  577. sv, errRsp := findService(c, epT, epBy)
  578. if !errRsp.isOK() {
  579. return nil, errRsp
  580. }
  581. if err := sv.Delete(sd.Force); err != nil {
  582. return nil, endpointToService(convertNetworkError(err))
  583. }
  584. return nil, &successResponse
  585. }
  586. func procAttachBackend(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  587. var bk endpointJoin
  588. var setFctList []libnetwork.EndpointOption
  589. err := json.Unmarshal(body, &bk)
  590. if err != nil {
  591. return nil, &responseStatus{Status: "Invalid body: " + err.Error(), StatusCode: http.StatusBadRequest}
  592. }
  593. epT, epBy := detectEndpointTarget(vars)
  594. sv, errRsp := findService(c, epT, epBy)
  595. if !errRsp.isOK() {
  596. return nil, errRsp
  597. }
  598. sb, errRsp := findSandbox(c, bk.SandboxID, byID)
  599. if !errRsp.isOK() {
  600. return nil, errRsp
  601. }
  602. for _, str := range bk.Aliases {
  603. name, alias, err := netutils.ParseAlias(str)
  604. if err != nil {
  605. return "", convertNetworkError(err)
  606. }
  607. setFctList = append(setFctList, libnetwork.CreateOptionAlias(name, alias))
  608. }
  609. err = sv.Join(sb, setFctList...)
  610. if err != nil {
  611. return nil, convertNetworkError(err)
  612. }
  613. return sb.Key(), &successResponse
  614. }
  615. func procDetachBackend(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  616. epT, epBy := detectEndpointTarget(vars)
  617. sv, errRsp := findService(c, epT, epBy)
  618. if !errRsp.isOK() {
  619. return nil, errRsp
  620. }
  621. sb, errRsp := findSandbox(c, vars[urlSbID], byID)
  622. if !errRsp.isOK() {
  623. return nil, errRsp
  624. }
  625. err := sv.Leave(sb)
  626. if err != nil {
  627. return nil, convertNetworkError(err)
  628. }
  629. return nil, &successResponse
  630. }
  631. /******************
  632. Sandbox interface
  633. *******************/
  634. func procGetSandbox(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  635. if epT, ok := vars[urlEpID]; ok {
  636. sv, errRsp := findService(c, epT, byID)
  637. if !errRsp.isOK() {
  638. return nil, endpointToService(errRsp)
  639. }
  640. return buildSandboxResource(sv.Info().Sandbox()), &successResponse
  641. }
  642. sbT, by := detectSandboxTarget(vars)
  643. sb, errRsp := findSandbox(c, sbT, by)
  644. if !errRsp.isOK() {
  645. return nil, errRsp
  646. }
  647. return buildSandboxResource(sb), &successResponse
  648. }
  649. type cndFnMkr func(string) cndFn
  650. type cndFn func(libnetwork.Sandbox) bool
  651. // list of (query type, condition function makers) couples
  652. var cndMkrList = []struct {
  653. identifier string
  654. maker cndFnMkr
  655. }{
  656. {urlSbPID, func(id string) cndFn {
  657. return func(sb libnetwork.Sandbox) bool { return strings.HasPrefix(sb.ID(), id) }
  658. }},
  659. {urlCnID, func(id string) cndFn {
  660. return func(sb libnetwork.Sandbox) bool { return sb.ContainerID() == id }
  661. }},
  662. {urlCnPID, func(id string) cndFn {
  663. return func(sb libnetwork.Sandbox) bool { return strings.HasPrefix(sb.ContainerID(), id) }
  664. }},
  665. }
  666. func getQueryCondition(vars map[string]string) func(libnetwork.Sandbox) bool {
  667. for _, im := range cndMkrList {
  668. if val, ok := vars[im.identifier]; ok {
  669. return im.maker(val)
  670. }
  671. }
  672. return func(sb libnetwork.Sandbox) bool { return true }
  673. }
  674. func sandboxWalker(condition cndFn, list *[]*sandboxResource) libnetwork.SandboxWalker {
  675. return func(sb libnetwork.Sandbox) bool {
  676. if condition(sb) {
  677. *list = append(*list, buildSandboxResource(sb))
  678. }
  679. return false
  680. }
  681. }
  682. func procGetSandboxes(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  683. var list []*sandboxResource
  684. cnd := getQueryCondition(vars)
  685. c.WalkSandboxes(sandboxWalker(cnd, &list))
  686. return list, &successResponse
  687. }
  688. func procDeleteSandbox(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  689. sbT, by := detectSandboxTarget(vars)
  690. sb, errRsp := findSandbox(c, sbT, by)
  691. if !errRsp.isOK() {
  692. return nil, errRsp
  693. }
  694. err := sb.Delete()
  695. if err != nil {
  696. return nil, convertNetworkError(err)
  697. }
  698. return nil, &successResponse
  699. }
  700. /***********
  701. Utilities
  702. ************/
  703. const (
  704. byID = iota
  705. byName
  706. )
  707. func detectNetworkTarget(vars map[string]string) (string, int) {
  708. if target, ok := vars[urlNwName]; ok {
  709. return target, byName
  710. }
  711. if target, ok := vars[urlNwID]; ok {
  712. return target, byID
  713. }
  714. // vars are populated from the URL, following cannot happen
  715. panic("Missing URL variable parameter for network")
  716. }
  717. func detectSandboxTarget(vars map[string]string) (string, int) {
  718. if target, ok := vars[urlSbID]; ok {
  719. return target, byID
  720. }
  721. // vars are populated from the URL, following cannot happen
  722. panic("Missing URL variable parameter for sandbox")
  723. }
  724. func detectEndpointTarget(vars map[string]string) (string, int) {
  725. if target, ok := vars[urlEpName]; ok {
  726. return target, byName
  727. }
  728. if target, ok := vars[urlEpID]; ok {
  729. return target, byID
  730. }
  731. // vars are populated from the URL, following cannot happen
  732. panic("Missing URL variable parameter for endpoint")
  733. }
  734. func findNetwork(c libnetwork.NetworkController, s string, by int) (libnetwork.Network, *responseStatus) {
  735. var (
  736. nw libnetwork.Network
  737. err error
  738. )
  739. switch by {
  740. case byID:
  741. nw, err = c.NetworkByID(s)
  742. case byName:
  743. if s == "" {
  744. s = c.Config().Daemon.DefaultNetwork
  745. }
  746. nw, err = c.NetworkByName(s)
  747. default:
  748. panic(fmt.Sprintf("unexpected selector for network search: %d", by))
  749. }
  750. if err != nil {
  751. if _, ok := err.(types.NotFoundError); ok {
  752. return nil, &responseStatus{Status: "Resource not found: Network", StatusCode: http.StatusNotFound}
  753. }
  754. return nil, &responseStatus{Status: err.Error(), StatusCode: http.StatusBadRequest}
  755. }
  756. return nw, &successResponse
  757. }
  758. func findSandbox(c libnetwork.NetworkController, s string, by int) (libnetwork.Sandbox, *responseStatus) {
  759. var (
  760. sb libnetwork.Sandbox
  761. err error
  762. )
  763. switch by {
  764. case byID:
  765. sb, err = c.SandboxByID(s)
  766. default:
  767. panic(fmt.Sprintf("unexpected selector for sandbox search: %d", by))
  768. }
  769. if err != nil {
  770. if _, ok := err.(types.NotFoundError); ok {
  771. return nil, &responseStatus{Status: "Resource not found: Sandbox", StatusCode: http.StatusNotFound}
  772. }
  773. return nil, &responseStatus{Status: err.Error(), StatusCode: http.StatusBadRequest}
  774. }
  775. return sb, &successResponse
  776. }
  777. func findEndpoint(c libnetwork.NetworkController, ns, es string, nwBy, epBy int) (libnetwork.Endpoint, *responseStatus) {
  778. nw, errRsp := findNetwork(c, ns, nwBy)
  779. if !errRsp.isOK() {
  780. return nil, errRsp
  781. }
  782. var (
  783. err error
  784. ep libnetwork.Endpoint
  785. )
  786. switch epBy {
  787. case byID:
  788. ep, err = nw.EndpointByID(es)
  789. case byName:
  790. ep, err = nw.EndpointByName(es)
  791. default:
  792. panic(fmt.Sprintf("unexpected selector for endpoint search: %d", epBy))
  793. }
  794. if err != nil {
  795. if _, ok := err.(types.NotFoundError); ok {
  796. return nil, &responseStatus{Status: "Resource not found: Endpoint", StatusCode: http.StatusNotFound}
  797. }
  798. return nil, &responseStatus{Status: err.Error(), StatusCode: http.StatusBadRequest}
  799. }
  800. return ep, &successResponse
  801. }
  802. func findService(c libnetwork.NetworkController, svs string, svBy int) (libnetwork.Endpoint, *responseStatus) {
  803. for _, nw := range c.Networks() {
  804. var (
  805. ep libnetwork.Endpoint
  806. err error
  807. )
  808. switch svBy {
  809. case byID:
  810. ep, err = nw.EndpointByID(svs)
  811. case byName:
  812. ep, err = nw.EndpointByName(svs)
  813. default:
  814. panic(fmt.Sprintf("unexpected selector for service search: %d", svBy))
  815. }
  816. if err == nil {
  817. return ep, &successResponse
  818. } else if _, ok := err.(types.NotFoundError); !ok {
  819. return nil, convertNetworkError(err)
  820. }
  821. }
  822. return nil, &responseStatus{Status: "Service not found", StatusCode: http.StatusNotFound}
  823. }
  824. func endpointToService(rsp *responseStatus) *responseStatus {
  825. rsp.Status = strings.Replace(rsp.Status, "endpoint", "service", -1)
  826. return rsp
  827. }
  828. func convertNetworkError(err error) *responseStatus {
  829. var code int
  830. switch err.(type) {
  831. case types.BadRequestError:
  832. code = http.StatusBadRequest
  833. case types.ForbiddenError:
  834. code = http.StatusForbidden
  835. case types.NotFoundError:
  836. code = http.StatusNotFound
  837. case types.TimeoutError:
  838. code = http.StatusRequestTimeout
  839. case types.NotImplementedError:
  840. code = http.StatusNotImplemented
  841. case types.NoServiceError:
  842. code = http.StatusServiceUnavailable
  843. case types.InternalError:
  844. code = http.StatusInternalServerError
  845. default:
  846. code = http.StatusInternalServerError
  847. }
  848. return &responseStatus{Status: err.Error(), StatusCode: code}
  849. }
  850. func writeJSON(w http.ResponseWriter, code int, v interface{}) error {
  851. w.Header().Set("Content-Type", "application/json")
  852. w.WriteHeader(code)
  853. return json.NewEncoder(w).Encode(v)
  854. }