api.go 26 KB

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