api.go 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970
  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. if sc.ExposedPorts != nil {
  232. setFctList = append(setFctList, libnetwork.OptionExposedPorts(sc.ExposedPorts))
  233. }
  234. if sc.PortMapping != nil {
  235. setFctList = append(setFctList, libnetwork.OptionPortMapping(sc.PortMapping))
  236. }
  237. return setFctList
  238. }
  239. func (ej *endpointJoin) parseOptions() []libnetwork.EndpointOption {
  240. // priority will go here
  241. return []libnetwork.EndpointOption{}
  242. }
  243. /******************
  244. Process functions
  245. *******************/
  246. func processCreateDefaults(c libnetwork.NetworkController, nc *networkCreate) {
  247. if nc.NetworkType == "" {
  248. nc.NetworkType = c.Config().Daemon.DefaultDriver
  249. }
  250. }
  251. /***************************
  252. NetworkController interface
  253. ****************************/
  254. func procCreateNetwork(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  255. var create networkCreate
  256. err := json.Unmarshal(body, &create)
  257. if err != nil {
  258. return nil, &responseStatus{Status: "Invalid body: " + err.Error(), StatusCode: http.StatusBadRequest}
  259. }
  260. processCreateDefaults(c, &create)
  261. options := []libnetwork.NetworkOption{}
  262. if val, ok := create.NetworkOpts[netlabel.Internal]; ok {
  263. internal, err := strconv.ParseBool(val)
  264. if err != nil {
  265. return nil, &responseStatus{Status: err.Error(), StatusCode: http.StatusBadRequest}
  266. }
  267. if internal {
  268. options = append(options, libnetwork.NetworkOptionInternalNetwork())
  269. }
  270. }
  271. if val, ok := create.NetworkOpts[netlabel.EnableIPv6]; ok {
  272. enableIPv6, err := strconv.ParseBool(val)
  273. if err != nil {
  274. return nil, &responseStatus{Status: err.Error(), StatusCode: http.StatusBadRequest}
  275. }
  276. options = append(options, libnetwork.NetworkOptionEnableIPv6(enableIPv6))
  277. }
  278. if len(create.DriverOpts) > 0 {
  279. options = append(options, libnetwork.NetworkOptionDriverOpts(create.DriverOpts))
  280. }
  281. nw, err := c.NewNetwork(create.NetworkType, create.Name, "", options...)
  282. if err != nil {
  283. return nil, convertNetworkError(err)
  284. }
  285. return nw.ID(), &createdResponse
  286. }
  287. func procGetNetwork(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  288. t, by := detectNetworkTarget(vars)
  289. nw, errRsp := findNetwork(c, t, by)
  290. if !errRsp.isOK() {
  291. return nil, errRsp
  292. }
  293. return buildNetworkResource(nw), &successResponse
  294. }
  295. func procGetNetworks(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  296. var list []*networkResource
  297. // Look for query filters and validate
  298. name, queryByName := vars[urlNwName]
  299. shortID, queryByPid := vars[urlNwPID]
  300. if queryByName && queryByPid {
  301. return nil, &badQueryResponse
  302. }
  303. if queryByName {
  304. if nw, errRsp := findNetwork(c, name, byName); errRsp.isOK() {
  305. list = append(list, buildNetworkResource(nw))
  306. }
  307. } else if queryByPid {
  308. // Return all the prefix-matching networks
  309. l := func(nw libnetwork.Network) bool {
  310. if strings.HasPrefix(nw.ID(), shortID) {
  311. list = append(list, buildNetworkResource(nw))
  312. }
  313. return false
  314. }
  315. c.WalkNetworks(l)
  316. } else {
  317. for _, nw := range c.Networks() {
  318. list = append(list, buildNetworkResource(nw))
  319. }
  320. }
  321. return list, &successResponse
  322. }
  323. func procCreateSandbox(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  324. var create sandboxCreate
  325. err := json.Unmarshal(body, &create)
  326. if err != nil {
  327. return "", &responseStatus{Status: "Invalid body: " + err.Error(), StatusCode: http.StatusBadRequest}
  328. }
  329. sb, err := c.NewSandbox(create.ContainerID, create.parseOptions()...)
  330. if err != nil {
  331. return "", convertNetworkError(err)
  332. }
  333. return sb.ID(), &createdResponse
  334. }
  335. /******************
  336. Network interface
  337. *******************/
  338. func procCreateEndpoint(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  339. var ec endpointCreate
  340. err := json.Unmarshal(body, &ec)
  341. if err != nil {
  342. return "", &responseStatus{Status: "Invalid body: " + err.Error(), StatusCode: http.StatusBadRequest}
  343. }
  344. nwT, nwBy := detectNetworkTarget(vars)
  345. n, errRsp := findNetwork(c, nwT, nwBy)
  346. if !errRsp.isOK() {
  347. return "", errRsp
  348. }
  349. var setFctList []libnetwork.EndpointOption
  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. for _, str := range sp.MyAliases {
  554. setFctList = append(setFctList, libnetwork.CreateOptionMyAlias(str))
  555. }
  556. ep, err := n.CreateEndpoint(sp.Name, setFctList...)
  557. if err != nil {
  558. return "", endpointToService(convertNetworkError(err))
  559. }
  560. return ep.ID(), &createdResponse
  561. }
  562. func procUnpublishService(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  563. var sd serviceDelete
  564. if body != nil {
  565. err := json.Unmarshal(body, &sd)
  566. if err != nil {
  567. return "", &responseStatus{Status: "Invalid body: " + err.Error(), StatusCode: http.StatusBadRequest}
  568. }
  569. }
  570. epT, epBy := detectEndpointTarget(vars)
  571. sv, errRsp := findService(c, epT, epBy)
  572. if !errRsp.isOK() {
  573. return nil, errRsp
  574. }
  575. if err := sv.Delete(sd.Force); err != nil {
  576. return nil, endpointToService(convertNetworkError(err))
  577. }
  578. return nil, &successResponse
  579. }
  580. func procAttachBackend(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  581. var bk endpointJoin
  582. var setFctList []libnetwork.EndpointOption
  583. err := json.Unmarshal(body, &bk)
  584. if err != nil {
  585. return nil, &responseStatus{Status: "Invalid body: " + err.Error(), StatusCode: http.StatusBadRequest}
  586. }
  587. epT, epBy := detectEndpointTarget(vars)
  588. sv, errRsp := findService(c, epT, epBy)
  589. if !errRsp.isOK() {
  590. return nil, errRsp
  591. }
  592. sb, errRsp := findSandbox(c, bk.SandboxID, byID)
  593. if !errRsp.isOK() {
  594. return nil, errRsp
  595. }
  596. for _, str := range bk.Aliases {
  597. name, alias, err := netutils.ParseAlias(str)
  598. if err != nil {
  599. return "", convertNetworkError(err)
  600. }
  601. setFctList = append(setFctList, libnetwork.CreateOptionAlias(name, alias))
  602. }
  603. err = sv.Join(sb, setFctList...)
  604. if err != nil {
  605. return nil, convertNetworkError(err)
  606. }
  607. return sb.Key(), &successResponse
  608. }
  609. func procDetachBackend(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  610. epT, epBy := detectEndpointTarget(vars)
  611. sv, errRsp := findService(c, epT, epBy)
  612. if !errRsp.isOK() {
  613. return nil, errRsp
  614. }
  615. sb, errRsp := findSandbox(c, vars[urlSbID], byID)
  616. if !errRsp.isOK() {
  617. return nil, errRsp
  618. }
  619. err := sv.Leave(sb)
  620. if err != nil {
  621. return nil, convertNetworkError(err)
  622. }
  623. return nil, &successResponse
  624. }
  625. /******************
  626. Sandbox interface
  627. *******************/
  628. func procGetSandbox(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  629. if epT, ok := vars[urlEpID]; ok {
  630. sv, errRsp := findService(c, epT, byID)
  631. if !errRsp.isOK() {
  632. return nil, endpointToService(errRsp)
  633. }
  634. return buildSandboxResource(sv.Info().Sandbox()), &successResponse
  635. }
  636. sbT, by := detectSandboxTarget(vars)
  637. sb, errRsp := findSandbox(c, sbT, by)
  638. if !errRsp.isOK() {
  639. return nil, errRsp
  640. }
  641. return buildSandboxResource(sb), &successResponse
  642. }
  643. type cndFnMkr func(string) cndFn
  644. type cndFn func(libnetwork.Sandbox) bool
  645. // list of (query type, condition function makers) couples
  646. var cndMkrList = []struct {
  647. identifier string
  648. maker cndFnMkr
  649. }{
  650. {urlSbPID, func(id string) cndFn {
  651. return func(sb libnetwork.Sandbox) bool { return strings.HasPrefix(sb.ID(), id) }
  652. }},
  653. {urlCnID, func(id string) cndFn {
  654. return func(sb libnetwork.Sandbox) bool { return sb.ContainerID() == id }
  655. }},
  656. {urlCnPID, func(id string) cndFn {
  657. return func(sb libnetwork.Sandbox) bool { return strings.HasPrefix(sb.ContainerID(), id) }
  658. }},
  659. }
  660. func getQueryCondition(vars map[string]string) func(libnetwork.Sandbox) bool {
  661. for _, im := range cndMkrList {
  662. if val, ok := vars[im.identifier]; ok {
  663. return im.maker(val)
  664. }
  665. }
  666. return func(sb libnetwork.Sandbox) bool { return true }
  667. }
  668. func sandboxWalker(condition cndFn, list *[]*sandboxResource) libnetwork.SandboxWalker {
  669. return func(sb libnetwork.Sandbox) bool {
  670. if condition(sb) {
  671. *list = append(*list, buildSandboxResource(sb))
  672. }
  673. return false
  674. }
  675. }
  676. func procGetSandboxes(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  677. var list []*sandboxResource
  678. cnd := getQueryCondition(vars)
  679. c.WalkSandboxes(sandboxWalker(cnd, &list))
  680. return list, &successResponse
  681. }
  682. func procDeleteSandbox(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  683. sbT, by := detectSandboxTarget(vars)
  684. sb, errRsp := findSandbox(c, sbT, by)
  685. if !errRsp.isOK() {
  686. return nil, errRsp
  687. }
  688. err := sb.Delete()
  689. if err != nil {
  690. return nil, convertNetworkError(err)
  691. }
  692. return nil, &successResponse
  693. }
  694. /***********
  695. Utilities
  696. ************/
  697. const (
  698. byID = iota
  699. byName
  700. )
  701. func detectNetworkTarget(vars map[string]string) (string, int) {
  702. if target, ok := vars[urlNwName]; ok {
  703. return target, byName
  704. }
  705. if target, ok := vars[urlNwID]; ok {
  706. return target, byID
  707. }
  708. // vars are populated from the URL, following cannot happen
  709. panic("Missing URL variable parameter for network")
  710. }
  711. func detectSandboxTarget(vars map[string]string) (string, int) {
  712. if target, ok := vars[urlSbID]; ok {
  713. return target, byID
  714. }
  715. // vars are populated from the URL, following cannot happen
  716. panic("Missing URL variable parameter for sandbox")
  717. }
  718. func detectEndpointTarget(vars map[string]string) (string, int) {
  719. if target, ok := vars[urlEpName]; ok {
  720. return target, byName
  721. }
  722. if target, ok := vars[urlEpID]; ok {
  723. return target, byID
  724. }
  725. // vars are populated from the URL, following cannot happen
  726. panic("Missing URL variable parameter for endpoint")
  727. }
  728. func findNetwork(c libnetwork.NetworkController, s string, by int) (libnetwork.Network, *responseStatus) {
  729. var (
  730. nw libnetwork.Network
  731. err error
  732. )
  733. switch by {
  734. case byID:
  735. nw, err = c.NetworkByID(s)
  736. case byName:
  737. if s == "" {
  738. s = c.Config().Daemon.DefaultNetwork
  739. }
  740. nw, err = c.NetworkByName(s)
  741. default:
  742. panic(fmt.Sprintf("unexpected selector for network search: %d", by))
  743. }
  744. if err != nil {
  745. if _, ok := err.(types.NotFoundError); ok {
  746. return nil, &responseStatus{Status: "Resource not found: Network", StatusCode: http.StatusNotFound}
  747. }
  748. return nil, &responseStatus{Status: err.Error(), StatusCode: http.StatusBadRequest}
  749. }
  750. return nw, &successResponse
  751. }
  752. func findSandbox(c libnetwork.NetworkController, s string, by int) (libnetwork.Sandbox, *responseStatus) {
  753. var (
  754. sb libnetwork.Sandbox
  755. err error
  756. )
  757. switch by {
  758. case byID:
  759. sb, err = c.SandboxByID(s)
  760. default:
  761. panic(fmt.Sprintf("unexpected selector for sandbox search: %d", by))
  762. }
  763. if err != nil {
  764. if _, ok := err.(types.NotFoundError); ok {
  765. return nil, &responseStatus{Status: "Resource not found: Sandbox", StatusCode: http.StatusNotFound}
  766. }
  767. return nil, &responseStatus{Status: err.Error(), StatusCode: http.StatusBadRequest}
  768. }
  769. return sb, &successResponse
  770. }
  771. func findEndpoint(c libnetwork.NetworkController, ns, es string, nwBy, epBy int) (libnetwork.Endpoint, *responseStatus) {
  772. nw, errRsp := findNetwork(c, ns, nwBy)
  773. if !errRsp.isOK() {
  774. return nil, errRsp
  775. }
  776. var (
  777. err error
  778. ep libnetwork.Endpoint
  779. )
  780. switch epBy {
  781. case byID:
  782. ep, err = nw.EndpointByID(es)
  783. case byName:
  784. ep, err = nw.EndpointByName(es)
  785. default:
  786. panic(fmt.Sprintf("unexpected selector for endpoint search: %d", epBy))
  787. }
  788. if err != nil {
  789. if _, ok := err.(types.NotFoundError); ok {
  790. return nil, &responseStatus{Status: "Resource not found: Endpoint", StatusCode: http.StatusNotFound}
  791. }
  792. return nil, &responseStatus{Status: err.Error(), StatusCode: http.StatusBadRequest}
  793. }
  794. return ep, &successResponse
  795. }
  796. func findService(c libnetwork.NetworkController, svs string, svBy int) (libnetwork.Endpoint, *responseStatus) {
  797. for _, nw := range c.Networks() {
  798. var (
  799. ep libnetwork.Endpoint
  800. err error
  801. )
  802. switch svBy {
  803. case byID:
  804. ep, err = nw.EndpointByID(svs)
  805. case byName:
  806. ep, err = nw.EndpointByName(svs)
  807. default:
  808. panic(fmt.Sprintf("unexpected selector for service search: %d", svBy))
  809. }
  810. if err == nil {
  811. return ep, &successResponse
  812. } else if _, ok := err.(types.NotFoundError); !ok {
  813. return nil, convertNetworkError(err)
  814. }
  815. }
  816. return nil, &responseStatus{Status: "Service not found", StatusCode: http.StatusNotFound}
  817. }
  818. func endpointToService(rsp *responseStatus) *responseStatus {
  819. rsp.Status = strings.Replace(rsp.Status, "endpoint", "service", -1)
  820. return rsp
  821. }
  822. func convertNetworkError(err error) *responseStatus {
  823. var code int
  824. switch err.(type) {
  825. case types.BadRequestError:
  826. code = http.StatusBadRequest
  827. case types.ForbiddenError:
  828. code = http.StatusForbidden
  829. case types.NotFoundError:
  830. code = http.StatusNotFound
  831. case types.TimeoutError:
  832. code = http.StatusRequestTimeout
  833. case types.NotImplementedError:
  834. code = http.StatusNotImplemented
  835. case types.NoServiceError:
  836. code = http.StatusServiceUnavailable
  837. case types.InternalError:
  838. code = http.StatusInternalServerError
  839. default:
  840. code = http.StatusInternalServerError
  841. }
  842. return &responseStatus{Status: err.Error(), StatusCode: code}
  843. }
  844. func writeJSON(w http.ResponseWriter, code int, v interface{}) error {
  845. w.Header().Set("Content-Type", "application/json")
  846. w.WriteHeader(code)
  847. return json.NewEncoder(w).Encode(v)
  848. }