api.go 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981
  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. if len(create.IPv4Conf) > 0 {
  282. ipamV4Conf := &libnetwork.IpamConf{
  283. PreferredPool: create.IPv4Conf[0].PreferredPool,
  284. SubPool: create.IPv4Conf[0].SubPool,
  285. }
  286. options = append(options, libnetwork.NetworkOptionIpam("default", "", []*libnetwork.IpamConf{ipamV4Conf}, nil, nil))
  287. }
  288. nw, err := c.NewNetwork(create.NetworkType, create.Name, create.ID, options...)
  289. if err != nil {
  290. return nil, convertNetworkError(err)
  291. }
  292. return nw.ID(), &createdResponse
  293. }
  294. func procGetNetwork(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  295. t, by := detectNetworkTarget(vars)
  296. nw, errRsp := findNetwork(c, t, by)
  297. if !errRsp.isOK() {
  298. return nil, errRsp
  299. }
  300. return buildNetworkResource(nw), &successResponse
  301. }
  302. func procGetNetworks(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  303. var list []*networkResource
  304. // Look for query filters and validate
  305. name, queryByName := vars[urlNwName]
  306. shortID, queryByPid := vars[urlNwPID]
  307. if queryByName && queryByPid {
  308. return nil, &badQueryResponse
  309. }
  310. if queryByName {
  311. if nw, errRsp := findNetwork(c, name, byName); errRsp.isOK() {
  312. list = append(list, buildNetworkResource(nw))
  313. }
  314. } else if queryByPid {
  315. // Return all the prefix-matching networks
  316. l := func(nw libnetwork.Network) bool {
  317. if strings.HasPrefix(nw.ID(), shortID) {
  318. list = append(list, buildNetworkResource(nw))
  319. }
  320. return false
  321. }
  322. c.WalkNetworks(l)
  323. } else {
  324. for _, nw := range c.Networks() {
  325. list = append(list, buildNetworkResource(nw))
  326. }
  327. }
  328. return list, &successResponse
  329. }
  330. func procCreateSandbox(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  331. var create sandboxCreate
  332. err := json.Unmarshal(body, &create)
  333. if err != nil {
  334. return "", &responseStatus{Status: "Invalid body: " + err.Error(), StatusCode: http.StatusBadRequest}
  335. }
  336. sb, err := c.NewSandbox(create.ContainerID, create.parseOptions()...)
  337. if err != nil {
  338. return "", convertNetworkError(err)
  339. }
  340. return sb.ID(), &createdResponse
  341. }
  342. /******************
  343. Network interface
  344. *******************/
  345. func procCreateEndpoint(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  346. var ec endpointCreate
  347. err := json.Unmarshal(body, &ec)
  348. if err != nil {
  349. return "", &responseStatus{Status: "Invalid body: " + err.Error(), StatusCode: http.StatusBadRequest}
  350. }
  351. nwT, nwBy := detectNetworkTarget(vars)
  352. n, errRsp := findNetwork(c, nwT, nwBy)
  353. if !errRsp.isOK() {
  354. return "", errRsp
  355. }
  356. var setFctList []libnetwork.EndpointOption
  357. for _, str := range ec.MyAliases {
  358. setFctList = append(setFctList, libnetwork.CreateOptionMyAlias(str))
  359. }
  360. ep, err := n.CreateEndpoint(ec.Name, setFctList...)
  361. if err != nil {
  362. return "", convertNetworkError(err)
  363. }
  364. return ep.ID(), &createdResponse
  365. }
  366. func procGetEndpoint(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  367. nwT, nwBy := detectNetworkTarget(vars)
  368. epT, epBy := detectEndpointTarget(vars)
  369. ep, errRsp := findEndpoint(c, nwT, epT, nwBy, epBy)
  370. if !errRsp.isOK() {
  371. return nil, errRsp
  372. }
  373. return buildEndpointResource(ep), &successResponse
  374. }
  375. func procGetEndpoints(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  376. // Look for query filters and validate
  377. name, queryByName := vars[urlEpName]
  378. shortID, queryByPid := vars[urlEpPID]
  379. if queryByName && queryByPid {
  380. return nil, &badQueryResponse
  381. }
  382. nwT, nwBy := detectNetworkTarget(vars)
  383. nw, errRsp := findNetwork(c, nwT, nwBy)
  384. if !errRsp.isOK() {
  385. return nil, errRsp
  386. }
  387. var list []*endpointResource
  388. // If query parameter is specified, return a filtered collection
  389. if queryByName {
  390. if ep, errRsp := findEndpoint(c, nwT, name, nwBy, byName); errRsp.isOK() {
  391. list = append(list, buildEndpointResource(ep))
  392. }
  393. } else if queryByPid {
  394. // Return all the prefix-matching endpoints
  395. l := func(ep libnetwork.Endpoint) bool {
  396. if strings.HasPrefix(ep.ID(), shortID) {
  397. list = append(list, buildEndpointResource(ep))
  398. }
  399. return false
  400. }
  401. nw.WalkEndpoints(l)
  402. } else {
  403. for _, ep := range nw.Endpoints() {
  404. epr := buildEndpointResource(ep)
  405. list = append(list, epr)
  406. }
  407. }
  408. return list, &successResponse
  409. }
  410. func procDeleteNetwork(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  411. target, by := detectNetworkTarget(vars)
  412. nw, errRsp := findNetwork(c, target, by)
  413. if !errRsp.isOK() {
  414. return nil, errRsp
  415. }
  416. err := nw.Delete()
  417. if err != nil {
  418. return nil, convertNetworkError(err)
  419. }
  420. return nil, &successResponse
  421. }
  422. /******************
  423. Endpoint interface
  424. *******************/
  425. func procJoinEndpoint(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  426. var ej endpointJoin
  427. var setFctList []libnetwork.EndpointOption
  428. err := json.Unmarshal(body, &ej)
  429. if err != nil {
  430. return nil, &responseStatus{Status: "Invalid body: " + err.Error(), StatusCode: http.StatusBadRequest}
  431. }
  432. nwT, nwBy := detectNetworkTarget(vars)
  433. epT, epBy := detectEndpointTarget(vars)
  434. ep, errRsp := findEndpoint(c, nwT, epT, nwBy, epBy)
  435. if !errRsp.isOK() {
  436. return nil, errRsp
  437. }
  438. sb, errRsp := findSandbox(c, ej.SandboxID, byID)
  439. if !errRsp.isOK() {
  440. return nil, errRsp
  441. }
  442. for _, str := range ej.Aliases {
  443. name, alias, err := netutils.ParseAlias(str)
  444. if err != nil {
  445. return "", convertNetworkError(err)
  446. }
  447. setFctList = append(setFctList, libnetwork.CreateOptionAlias(name, alias))
  448. }
  449. err = ep.Join(sb, setFctList...)
  450. if err != nil {
  451. return nil, convertNetworkError(err)
  452. }
  453. return sb.Key(), &successResponse
  454. }
  455. func procLeaveEndpoint(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  456. nwT, nwBy := detectNetworkTarget(vars)
  457. epT, epBy := detectEndpointTarget(vars)
  458. ep, errRsp := findEndpoint(c, nwT, epT, nwBy, epBy)
  459. if !errRsp.isOK() {
  460. return nil, errRsp
  461. }
  462. sb, errRsp := findSandbox(c, vars[urlSbID], byID)
  463. if !errRsp.isOK() {
  464. return nil, errRsp
  465. }
  466. err := ep.Leave(sb)
  467. if err != nil {
  468. return nil, convertNetworkError(err)
  469. }
  470. return nil, &successResponse
  471. }
  472. func procDeleteEndpoint(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  473. nwT, nwBy := detectNetworkTarget(vars)
  474. epT, epBy := detectEndpointTarget(vars)
  475. ep, errRsp := findEndpoint(c, nwT, epT, nwBy, epBy)
  476. if !errRsp.isOK() {
  477. return nil, errRsp
  478. }
  479. err := ep.Delete(false)
  480. if err != nil {
  481. return nil, convertNetworkError(err)
  482. }
  483. return nil, &successResponse
  484. }
  485. /******************
  486. Service interface
  487. *******************/
  488. func procGetServices(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  489. // Look for query filters and validate
  490. nwName, filterByNwName := vars[urlNwName]
  491. svName, queryBySvName := vars[urlEpName]
  492. shortID, queryBySvPID := vars[urlEpPID]
  493. if filterByNwName && queryBySvName || filterByNwName && queryBySvPID || queryBySvName && queryBySvPID {
  494. return nil, &badQueryResponse
  495. }
  496. var list []*endpointResource
  497. switch {
  498. case filterByNwName:
  499. // return all service present on the specified network
  500. nw, errRsp := findNetwork(c, nwName, byName)
  501. if !errRsp.isOK() {
  502. return list, &successResponse
  503. }
  504. for _, ep := range nw.Endpoints() {
  505. epr := buildEndpointResource(ep)
  506. list = append(list, epr)
  507. }
  508. case queryBySvName:
  509. // Look in each network for the service with the specified name
  510. l := func(ep libnetwork.Endpoint) bool {
  511. if ep.Name() == svName {
  512. list = append(list, buildEndpointResource(ep))
  513. return true
  514. }
  515. return false
  516. }
  517. for _, nw := range c.Networks() {
  518. nw.WalkEndpoints(l)
  519. }
  520. case queryBySvPID:
  521. // Return all the prefix-matching services
  522. l := func(ep libnetwork.Endpoint) bool {
  523. if strings.HasPrefix(ep.ID(), shortID) {
  524. list = append(list, buildEndpointResource(ep))
  525. }
  526. return false
  527. }
  528. for _, nw := range c.Networks() {
  529. nw.WalkEndpoints(l)
  530. }
  531. default:
  532. for _, nw := range c.Networks() {
  533. for _, ep := range nw.Endpoints() {
  534. epr := buildEndpointResource(ep)
  535. list = append(list, epr)
  536. }
  537. }
  538. }
  539. return list, &successResponse
  540. }
  541. func procGetService(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  542. epT, epBy := detectEndpointTarget(vars)
  543. sv, errRsp := findService(c, epT, epBy)
  544. if !errRsp.isOK() {
  545. return nil, endpointToService(errRsp)
  546. }
  547. return buildEndpointResource(sv), &successResponse
  548. }
  549. func procPublishService(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  550. var sp servicePublish
  551. err := json.Unmarshal(body, &sp)
  552. if err != nil {
  553. return "", &responseStatus{Status: "Invalid body: " + err.Error(), StatusCode: http.StatusBadRequest}
  554. }
  555. n, errRsp := findNetwork(c, sp.Network, byName)
  556. if !errRsp.isOK() {
  557. return "", errRsp
  558. }
  559. var setFctList []libnetwork.EndpointOption
  560. for _, str := range sp.MyAliases {
  561. setFctList = append(setFctList, libnetwork.CreateOptionMyAlias(str))
  562. }
  563. ep, err := n.CreateEndpoint(sp.Name, setFctList...)
  564. if err != nil {
  565. return "", endpointToService(convertNetworkError(err))
  566. }
  567. return ep.ID(), &createdResponse
  568. }
  569. func procUnpublishService(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  570. var sd serviceDelete
  571. if body != nil {
  572. err := json.Unmarshal(body, &sd)
  573. if err != nil {
  574. return "", &responseStatus{Status: "Invalid body: " + err.Error(), StatusCode: http.StatusBadRequest}
  575. }
  576. }
  577. epT, epBy := detectEndpointTarget(vars)
  578. sv, errRsp := findService(c, epT, epBy)
  579. if !errRsp.isOK() {
  580. return nil, errRsp
  581. }
  582. if err := sv.Delete(sd.Force); err != nil {
  583. return nil, endpointToService(convertNetworkError(err))
  584. }
  585. return nil, &successResponse
  586. }
  587. func procAttachBackend(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  588. var bk endpointJoin
  589. var setFctList []libnetwork.EndpointOption
  590. err := json.Unmarshal(body, &bk)
  591. if err != nil {
  592. return nil, &responseStatus{Status: "Invalid body: " + err.Error(), StatusCode: http.StatusBadRequest}
  593. }
  594. epT, epBy := detectEndpointTarget(vars)
  595. sv, errRsp := findService(c, epT, epBy)
  596. if !errRsp.isOK() {
  597. return nil, errRsp
  598. }
  599. sb, errRsp := findSandbox(c, bk.SandboxID, byID)
  600. if !errRsp.isOK() {
  601. return nil, errRsp
  602. }
  603. for _, str := range bk.Aliases {
  604. name, alias, err := netutils.ParseAlias(str)
  605. if err != nil {
  606. return "", convertNetworkError(err)
  607. }
  608. setFctList = append(setFctList, libnetwork.CreateOptionAlias(name, alias))
  609. }
  610. err = sv.Join(sb, setFctList...)
  611. if err != nil {
  612. return nil, convertNetworkError(err)
  613. }
  614. return sb.Key(), &successResponse
  615. }
  616. func procDetachBackend(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  617. epT, epBy := detectEndpointTarget(vars)
  618. sv, errRsp := findService(c, epT, epBy)
  619. if !errRsp.isOK() {
  620. return nil, errRsp
  621. }
  622. sb, errRsp := findSandbox(c, vars[urlSbID], byID)
  623. if !errRsp.isOK() {
  624. return nil, errRsp
  625. }
  626. err := sv.Leave(sb)
  627. if err != nil {
  628. return nil, convertNetworkError(err)
  629. }
  630. return nil, &successResponse
  631. }
  632. /******************
  633. Sandbox interface
  634. *******************/
  635. func procGetSandbox(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  636. if epT, ok := vars[urlEpID]; ok {
  637. sv, errRsp := findService(c, epT, byID)
  638. if !errRsp.isOK() {
  639. return nil, endpointToService(errRsp)
  640. }
  641. return buildSandboxResource(sv.Info().Sandbox()), &successResponse
  642. }
  643. sbT, by := detectSandboxTarget(vars)
  644. sb, errRsp := findSandbox(c, sbT, by)
  645. if !errRsp.isOK() {
  646. return nil, errRsp
  647. }
  648. return buildSandboxResource(sb), &successResponse
  649. }
  650. type cndFnMkr func(string) cndFn
  651. type cndFn func(libnetwork.Sandbox) bool
  652. // list of (query type, condition function makers) couples
  653. var cndMkrList = []struct {
  654. identifier string
  655. maker cndFnMkr
  656. }{
  657. {urlSbPID, func(id string) cndFn {
  658. return func(sb libnetwork.Sandbox) bool { return strings.HasPrefix(sb.ID(), id) }
  659. }},
  660. {urlCnID, func(id string) cndFn {
  661. return func(sb libnetwork.Sandbox) bool { return sb.ContainerID() == id }
  662. }},
  663. {urlCnPID, func(id string) cndFn {
  664. return func(sb libnetwork.Sandbox) bool { return strings.HasPrefix(sb.ContainerID(), id) }
  665. }},
  666. }
  667. func getQueryCondition(vars map[string]string) func(libnetwork.Sandbox) bool {
  668. for _, im := range cndMkrList {
  669. if val, ok := vars[im.identifier]; ok {
  670. return im.maker(val)
  671. }
  672. }
  673. return func(sb libnetwork.Sandbox) bool { return true }
  674. }
  675. func sandboxWalker(condition cndFn, list *[]*sandboxResource) libnetwork.SandboxWalker {
  676. return func(sb libnetwork.Sandbox) bool {
  677. if condition(sb) {
  678. *list = append(*list, buildSandboxResource(sb))
  679. }
  680. return false
  681. }
  682. }
  683. func procGetSandboxes(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  684. var list []*sandboxResource
  685. cnd := getQueryCondition(vars)
  686. c.WalkSandboxes(sandboxWalker(cnd, &list))
  687. return list, &successResponse
  688. }
  689. func procDeleteSandbox(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  690. sbT, by := detectSandboxTarget(vars)
  691. sb, errRsp := findSandbox(c, sbT, by)
  692. if !errRsp.isOK() {
  693. return nil, errRsp
  694. }
  695. err := sb.Delete()
  696. if err != nil {
  697. return nil, convertNetworkError(err)
  698. }
  699. return nil, &successResponse
  700. }
  701. /***********
  702. Utilities
  703. ************/
  704. const (
  705. byID = iota
  706. byName
  707. )
  708. func detectNetworkTarget(vars map[string]string) (string, int) {
  709. if target, ok := vars[urlNwName]; ok {
  710. return target, byName
  711. }
  712. if target, ok := vars[urlNwID]; ok {
  713. return target, byID
  714. }
  715. // vars are populated from the URL, following cannot happen
  716. panic("Missing URL variable parameter for network")
  717. }
  718. func detectSandboxTarget(vars map[string]string) (string, int) {
  719. if target, ok := vars[urlSbID]; ok {
  720. return target, byID
  721. }
  722. // vars are populated from the URL, following cannot happen
  723. panic("Missing URL variable parameter for sandbox")
  724. }
  725. func detectEndpointTarget(vars map[string]string) (string, int) {
  726. if target, ok := vars[urlEpName]; ok {
  727. return target, byName
  728. }
  729. if target, ok := vars[urlEpID]; ok {
  730. return target, byID
  731. }
  732. // vars are populated from the URL, following cannot happen
  733. panic("Missing URL variable parameter for endpoint")
  734. }
  735. func findNetwork(c libnetwork.NetworkController, s string, by int) (libnetwork.Network, *responseStatus) {
  736. var (
  737. nw libnetwork.Network
  738. err error
  739. )
  740. switch by {
  741. case byID:
  742. nw, err = c.NetworkByID(s)
  743. case byName:
  744. if s == "" {
  745. s = c.Config().Daemon.DefaultNetwork
  746. }
  747. nw, err = c.NetworkByName(s)
  748. default:
  749. panic(fmt.Sprintf("unexpected selector for network search: %d", by))
  750. }
  751. if err != nil {
  752. if _, ok := err.(types.NotFoundError); ok {
  753. return nil, &responseStatus{Status: "Resource not found: Network", StatusCode: http.StatusNotFound}
  754. }
  755. return nil, &responseStatus{Status: err.Error(), StatusCode: http.StatusBadRequest}
  756. }
  757. return nw, &successResponse
  758. }
  759. func findSandbox(c libnetwork.NetworkController, s string, by int) (libnetwork.Sandbox, *responseStatus) {
  760. var (
  761. sb libnetwork.Sandbox
  762. err error
  763. )
  764. switch by {
  765. case byID:
  766. sb, err = c.SandboxByID(s)
  767. default:
  768. panic(fmt.Sprintf("unexpected selector for sandbox search: %d", by))
  769. }
  770. if err != nil {
  771. if _, ok := err.(types.NotFoundError); ok {
  772. return nil, &responseStatus{Status: "Resource not found: Sandbox", StatusCode: http.StatusNotFound}
  773. }
  774. return nil, &responseStatus{Status: err.Error(), StatusCode: http.StatusBadRequest}
  775. }
  776. return sb, &successResponse
  777. }
  778. func findEndpoint(c libnetwork.NetworkController, ns, es string, nwBy, epBy int) (libnetwork.Endpoint, *responseStatus) {
  779. nw, errRsp := findNetwork(c, ns, nwBy)
  780. if !errRsp.isOK() {
  781. return nil, errRsp
  782. }
  783. var (
  784. err error
  785. ep libnetwork.Endpoint
  786. )
  787. switch epBy {
  788. case byID:
  789. ep, err = nw.EndpointByID(es)
  790. case byName:
  791. ep, err = nw.EndpointByName(es)
  792. default:
  793. panic(fmt.Sprintf("unexpected selector for endpoint search: %d", epBy))
  794. }
  795. if err != nil {
  796. if _, ok := err.(types.NotFoundError); ok {
  797. return nil, &responseStatus{Status: "Resource not found: Endpoint", StatusCode: http.StatusNotFound}
  798. }
  799. return nil, &responseStatus{Status: err.Error(), StatusCode: http.StatusBadRequest}
  800. }
  801. return ep, &successResponse
  802. }
  803. func findService(c libnetwork.NetworkController, svs string, svBy int) (libnetwork.Endpoint, *responseStatus) {
  804. for _, nw := range c.Networks() {
  805. var (
  806. ep libnetwork.Endpoint
  807. err error
  808. )
  809. switch svBy {
  810. case byID:
  811. ep, err = nw.EndpointByID(svs)
  812. case byName:
  813. ep, err = nw.EndpointByName(svs)
  814. default:
  815. panic(fmt.Sprintf("unexpected selector for service search: %d", svBy))
  816. }
  817. if err == nil {
  818. return ep, &successResponse
  819. } else if _, ok := err.(types.NotFoundError); !ok {
  820. return nil, convertNetworkError(err)
  821. }
  822. }
  823. return nil, &responseStatus{Status: "Service not found", StatusCode: http.StatusNotFound}
  824. }
  825. func endpointToService(rsp *responseStatus) *responseStatus {
  826. rsp.Status = strings.Replace(rsp.Status, "endpoint", "service", -1)
  827. return rsp
  828. }
  829. func convertNetworkError(err error) *responseStatus {
  830. var code int
  831. switch err.(type) {
  832. case types.BadRequestError:
  833. code = http.StatusBadRequest
  834. case types.ForbiddenError:
  835. code = http.StatusForbidden
  836. case types.NotFoundError:
  837. code = http.StatusNotFound
  838. case types.TimeoutError:
  839. code = http.StatusRequestTimeout
  840. case types.NotImplementedError:
  841. code = http.StatusNotImplemented
  842. case types.NoServiceError:
  843. code = http.StatusServiceUnavailable
  844. case types.InternalError:
  845. code = http.StatusInternalServerError
  846. default:
  847. code = http.StatusInternalServerError
  848. }
  849. return &responseStatus{Status: err.Error(), StatusCode: code}
  850. }
  851. func writeJSON(w http.ResponseWriter, code int, v interface{}) error {
  852. w.Header().Set("Content-Type", "application/json")
  853. w.WriteHeader(code)
  854. return json.NewEncoder(w).Encode(v)
  855. }