api.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948
  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 res != nil {
  154. writeJSON(w, rsp.StatusCode, res)
  155. }
  156. }
  157. }
  158. /*****************
  159. Resource Builders
  160. ******************/
  161. func buildNetworkResource(nw libnetwork.Network) *networkResource {
  162. r := &networkResource{}
  163. if nw != nil {
  164. r.Name = nw.Name()
  165. r.ID = nw.ID()
  166. r.Type = nw.Type()
  167. epl := nw.Endpoints()
  168. r.Endpoints = make([]*endpointResource, 0, len(epl))
  169. for _, e := range epl {
  170. epr := buildEndpointResource(e)
  171. r.Endpoints = append(r.Endpoints, epr)
  172. }
  173. }
  174. return r
  175. }
  176. func buildEndpointResource(ep libnetwork.Endpoint) *endpointResource {
  177. r := &endpointResource{}
  178. if ep != nil {
  179. r.Name = ep.Name()
  180. r.ID = ep.ID()
  181. r.Network = ep.Network()
  182. }
  183. return r
  184. }
  185. func buildSandboxResource(sb libnetwork.Sandbox) *sandboxResource {
  186. r := &sandboxResource{}
  187. if sb != nil {
  188. r.ID = sb.ID()
  189. r.Key = sb.Key()
  190. r.ContainerID = sb.ContainerID()
  191. }
  192. return r
  193. }
  194. /****************
  195. Options Parsers
  196. *****************/
  197. func (nc *networkCreate) parseOptions() []libnetwork.NetworkOption {
  198. var setFctList []libnetwork.NetworkOption
  199. if nc.Options != nil {
  200. setFctList = append(setFctList, libnetwork.NetworkOptionGeneric(nc.Options))
  201. }
  202. return setFctList
  203. }
  204. func (sc *sandboxCreate) parseOptions() []libnetwork.SandboxOption {
  205. var setFctList []libnetwork.SandboxOption
  206. if sc.HostName != "" {
  207. setFctList = append(setFctList, libnetwork.OptionHostname(sc.HostName))
  208. }
  209. if sc.DomainName != "" {
  210. setFctList = append(setFctList, libnetwork.OptionDomainname(sc.DomainName))
  211. }
  212. if sc.HostsPath != "" {
  213. setFctList = append(setFctList, libnetwork.OptionHostsPath(sc.HostsPath))
  214. }
  215. if sc.ResolvConfPath != "" {
  216. setFctList = append(setFctList, libnetwork.OptionResolvConfPath(sc.ResolvConfPath))
  217. }
  218. if sc.UseDefaultSandbox {
  219. setFctList = append(setFctList, libnetwork.OptionUseDefaultSandbox())
  220. }
  221. if sc.UseExternalKey {
  222. setFctList = append(setFctList, libnetwork.OptionUseExternalKey())
  223. }
  224. if sc.DNS != nil {
  225. for _, d := range sc.DNS {
  226. setFctList = append(setFctList, libnetwork.OptionDNS(d))
  227. }
  228. }
  229. if sc.ExtraHosts != nil {
  230. for _, e := range sc.ExtraHosts {
  231. setFctList = append(setFctList, libnetwork.OptionExtraHost(e.Name, e.Address))
  232. }
  233. }
  234. return setFctList
  235. }
  236. func (ej *endpointJoin) parseOptions() []libnetwork.EndpointOption {
  237. // priority will go here
  238. return []libnetwork.EndpointOption{}
  239. }
  240. /******************
  241. Process functions
  242. *******************/
  243. func processCreateDefaults(c libnetwork.NetworkController, nc *networkCreate) {
  244. if nc.NetworkType == "" {
  245. nc.NetworkType = c.Config().Daemon.DefaultDriver
  246. }
  247. if nc.NetworkType == BridgeNetworkDriver {
  248. if nc.Options == nil {
  249. nc.Options = make(map[string]interface{})
  250. }
  251. genericData, ok := nc.Options[netlabel.GenericData]
  252. if !ok {
  253. genericData = make(map[string]interface{})
  254. }
  255. gData := genericData.(map[string]interface{})
  256. if _, ok := gData["BridgeName"]; !ok {
  257. gData["BridgeName"] = nc.Name
  258. }
  259. if _, ok := gData["AllowNonDefaultBridge"]; !ok {
  260. gData["AllowNonDefaultBridge"] = "true"
  261. }
  262. nc.Options[netlabel.GenericData] = genericData
  263. }
  264. }
  265. /***************************
  266. NetworkController interface
  267. ****************************/
  268. func procCreateNetwork(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  269. var create networkCreate
  270. err := json.Unmarshal(body, &create)
  271. if err != nil {
  272. return "", &responseStatus{Status: "Invalid body: " + err.Error(), StatusCode: http.StatusBadRequest}
  273. }
  274. processCreateDefaults(c, &create)
  275. nw, err := c.NewNetwork(create.NetworkType, create.Name, create.parseOptions()...)
  276. if err != nil {
  277. return "", convertNetworkError(err)
  278. }
  279. return nw.ID(), &createdResponse
  280. }
  281. func procGetNetwork(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  282. t, by := detectNetworkTarget(vars)
  283. nw, errRsp := findNetwork(c, t, by)
  284. if !errRsp.isOK() {
  285. return nil, errRsp
  286. }
  287. return buildNetworkResource(nw), &successResponse
  288. }
  289. func procGetNetworks(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  290. var list []*networkResource
  291. // Look for query filters and validate
  292. name, queryByName := vars[urlNwName]
  293. shortID, queryByPid := vars[urlNwPID]
  294. if queryByName && queryByPid {
  295. return nil, &badQueryResponse
  296. }
  297. if queryByName {
  298. if nw, errRsp := findNetwork(c, name, byName); errRsp.isOK() {
  299. list = append(list, buildNetworkResource(nw))
  300. }
  301. } else if queryByPid {
  302. // Return all the prefix-matching networks
  303. l := func(nw libnetwork.Network) bool {
  304. if strings.HasPrefix(nw.ID(), shortID) {
  305. list = append(list, buildNetworkResource(nw))
  306. }
  307. return false
  308. }
  309. c.WalkNetworks(l)
  310. } else {
  311. for _, nw := range c.Networks() {
  312. list = append(list, buildNetworkResource(nw))
  313. }
  314. }
  315. return list, &successResponse
  316. }
  317. func procCreateSandbox(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  318. var create sandboxCreate
  319. err := json.Unmarshal(body, &create)
  320. if err != nil {
  321. return "", &responseStatus{Status: "Invalid body: " + err.Error(), StatusCode: http.StatusBadRequest}
  322. }
  323. sb, err := c.NewSandbox(create.ContainerID, create.parseOptions()...)
  324. if err != nil {
  325. return "", convertNetworkError(err)
  326. }
  327. return sb.ID(), &createdResponse
  328. }
  329. /******************
  330. Network interface
  331. *******************/
  332. func procCreateEndpoint(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  333. var ec endpointCreate
  334. err := json.Unmarshal(body, &ec)
  335. if err != nil {
  336. return "", &responseStatus{Status: "Invalid body: " + err.Error(), StatusCode: http.StatusBadRequest}
  337. }
  338. nwT, nwBy := detectNetworkTarget(vars)
  339. n, errRsp := findNetwork(c, nwT, nwBy)
  340. if !errRsp.isOK() {
  341. return "", errRsp
  342. }
  343. var setFctList []libnetwork.EndpointOption
  344. if ec.ExposedPorts != nil {
  345. setFctList = append(setFctList, libnetwork.CreateOptionExposedPorts(ec.ExposedPorts))
  346. }
  347. if ec.PortMapping != nil {
  348. setFctList = append(setFctList, libnetwork.CreateOptionPortMapping(ec.PortMapping))
  349. }
  350. ep, err := n.CreateEndpoint(ec.Name, setFctList...)
  351. if err != nil {
  352. return "", convertNetworkError(err)
  353. }
  354. return ep.ID(), &createdResponse
  355. }
  356. func procGetEndpoint(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  357. nwT, nwBy := detectNetworkTarget(vars)
  358. epT, epBy := detectEndpointTarget(vars)
  359. ep, errRsp := findEndpoint(c, nwT, epT, nwBy, epBy)
  360. if !errRsp.isOK() {
  361. return nil, errRsp
  362. }
  363. return buildEndpointResource(ep), &successResponse
  364. }
  365. func procGetEndpoints(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  366. // Look for query filters and validate
  367. name, queryByName := vars[urlEpName]
  368. shortID, queryByPid := vars[urlEpPID]
  369. if queryByName && queryByPid {
  370. return nil, &badQueryResponse
  371. }
  372. nwT, nwBy := detectNetworkTarget(vars)
  373. nw, errRsp := findNetwork(c, nwT, nwBy)
  374. if !errRsp.isOK() {
  375. return nil, errRsp
  376. }
  377. var list []*endpointResource
  378. // If query parameter is specified, return a filtered collection
  379. if queryByName {
  380. if ep, errRsp := findEndpoint(c, nwT, name, nwBy, byName); errRsp.isOK() {
  381. list = append(list, buildEndpointResource(ep))
  382. }
  383. } else if queryByPid {
  384. // Return all the prefix-matching endpoints
  385. l := func(ep libnetwork.Endpoint) bool {
  386. if strings.HasPrefix(ep.ID(), shortID) {
  387. list = append(list, buildEndpointResource(ep))
  388. }
  389. return false
  390. }
  391. nw.WalkEndpoints(l)
  392. } else {
  393. for _, ep := range nw.Endpoints() {
  394. epr := buildEndpointResource(ep)
  395. list = append(list, epr)
  396. }
  397. }
  398. return list, &successResponse
  399. }
  400. func procDeleteNetwork(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  401. target, by := detectNetworkTarget(vars)
  402. nw, errRsp := findNetwork(c, target, by)
  403. if !errRsp.isOK() {
  404. return nil, errRsp
  405. }
  406. err := nw.Delete()
  407. if err != nil {
  408. return nil, convertNetworkError(err)
  409. }
  410. return nil, &successResponse
  411. }
  412. /******************
  413. Endpoint interface
  414. *******************/
  415. func procJoinEndpoint(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  416. var ej endpointJoin
  417. err := json.Unmarshal(body, &ej)
  418. if err != nil {
  419. return nil, &responseStatus{Status: "Invalid body: " + err.Error(), StatusCode: http.StatusBadRequest}
  420. }
  421. nwT, nwBy := detectNetworkTarget(vars)
  422. epT, epBy := detectEndpointTarget(vars)
  423. ep, errRsp := findEndpoint(c, nwT, epT, nwBy, epBy)
  424. if !errRsp.isOK() {
  425. return nil, errRsp
  426. }
  427. sb, errRsp := findSandbox(c, ej.SandboxID, byID)
  428. if !errRsp.isOK() {
  429. return nil, errRsp
  430. }
  431. err = ep.Join(sb)
  432. if err != nil {
  433. return nil, convertNetworkError(err)
  434. }
  435. return sb.Key(), &successResponse
  436. }
  437. func procLeaveEndpoint(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  438. nwT, nwBy := detectNetworkTarget(vars)
  439. epT, epBy := detectEndpointTarget(vars)
  440. ep, errRsp := findEndpoint(c, nwT, epT, nwBy, epBy)
  441. if !errRsp.isOK() {
  442. return nil, errRsp
  443. }
  444. sb, errRsp := findSandbox(c, vars[urlSbID], byID)
  445. if !errRsp.isOK() {
  446. return nil, errRsp
  447. }
  448. err := ep.Leave(sb)
  449. if err != nil {
  450. return nil, convertNetworkError(err)
  451. }
  452. return nil, &successResponse
  453. }
  454. func procDeleteEndpoint(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  455. nwT, nwBy := detectNetworkTarget(vars)
  456. epT, epBy := detectEndpointTarget(vars)
  457. ep, errRsp := findEndpoint(c, nwT, epT, nwBy, epBy)
  458. if !errRsp.isOK() {
  459. return nil, errRsp
  460. }
  461. err := ep.Delete()
  462. if err != nil {
  463. return nil, convertNetworkError(err)
  464. }
  465. return nil, &successResponse
  466. }
  467. /******************
  468. Service interface
  469. *******************/
  470. func procGetServices(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  471. // Look for query filters and validate
  472. nwName, filterByNwName := vars[urlNwName]
  473. svName, queryBySvName := vars[urlEpName]
  474. shortID, queryBySvPID := vars[urlEpPID]
  475. if filterByNwName && queryBySvName || filterByNwName && queryBySvPID || queryBySvName && queryBySvPID {
  476. return nil, &badQueryResponse
  477. }
  478. var list []*endpointResource
  479. switch {
  480. case filterByNwName:
  481. // return all service present on the specified network
  482. nw, errRsp := findNetwork(c, nwName, byName)
  483. if !errRsp.isOK() {
  484. return list, &successResponse
  485. }
  486. for _, ep := range nw.Endpoints() {
  487. epr := buildEndpointResource(ep)
  488. list = append(list, epr)
  489. }
  490. case queryBySvName:
  491. // Look in each network for the service with the specified name
  492. l := func(ep libnetwork.Endpoint) bool {
  493. if ep.Name() == svName {
  494. list = append(list, buildEndpointResource(ep))
  495. return true
  496. }
  497. return false
  498. }
  499. for _, nw := range c.Networks() {
  500. nw.WalkEndpoints(l)
  501. }
  502. case queryBySvPID:
  503. // Return all the prefix-matching services
  504. l := func(ep libnetwork.Endpoint) bool {
  505. if strings.HasPrefix(ep.ID(), shortID) {
  506. list = append(list, buildEndpointResource(ep))
  507. }
  508. return false
  509. }
  510. for _, nw := range c.Networks() {
  511. nw.WalkEndpoints(l)
  512. }
  513. default:
  514. for _, nw := range c.Networks() {
  515. for _, ep := range nw.Endpoints() {
  516. epr := buildEndpointResource(ep)
  517. list = append(list, epr)
  518. }
  519. }
  520. }
  521. return list, &successResponse
  522. }
  523. func procGetService(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  524. epT, epBy := detectEndpointTarget(vars)
  525. sv, errRsp := findService(c, epT, epBy)
  526. if !errRsp.isOK() {
  527. return nil, endpointToService(errRsp)
  528. }
  529. return buildEndpointResource(sv), &successResponse
  530. }
  531. func procPublishService(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  532. var sp servicePublish
  533. err := json.Unmarshal(body, &sp)
  534. if err != nil {
  535. return "", &responseStatus{Status: "Invalid body: " + err.Error(), StatusCode: http.StatusBadRequest}
  536. }
  537. n, errRsp := findNetwork(c, sp.Network, byName)
  538. if !errRsp.isOK() {
  539. return "", errRsp
  540. }
  541. var setFctList []libnetwork.EndpointOption
  542. if sp.ExposedPorts != nil {
  543. setFctList = append(setFctList, libnetwork.CreateOptionExposedPorts(sp.ExposedPorts))
  544. }
  545. if sp.PortMapping != nil {
  546. setFctList = append(setFctList, libnetwork.CreateOptionPortMapping(sp.PortMapping))
  547. }
  548. ep, err := n.CreateEndpoint(sp.Name, setFctList...)
  549. if err != nil {
  550. return "", endpointToService(convertNetworkError(err))
  551. }
  552. return ep.ID(), &createdResponse
  553. }
  554. func procUnpublishService(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  555. epT, epBy := detectEndpointTarget(vars)
  556. sv, errRsp := findService(c, epT, epBy)
  557. if !errRsp.isOK() {
  558. return nil, errRsp
  559. }
  560. err := sv.Delete()
  561. if err != nil {
  562. return nil, endpointToService(convertNetworkError(err))
  563. }
  564. return nil, &successResponse
  565. }
  566. func procAttachBackend(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  567. var bk endpointJoin
  568. err := json.Unmarshal(body, &bk)
  569. if err != nil {
  570. return nil, &responseStatus{Status: "Invalid body: " + err.Error(), StatusCode: http.StatusBadRequest}
  571. }
  572. epT, epBy := detectEndpointTarget(vars)
  573. sv, errRsp := findService(c, epT, epBy)
  574. if !errRsp.isOK() {
  575. return nil, errRsp
  576. }
  577. sb, errRsp := findSandbox(c, bk.SandboxID, byID)
  578. if !errRsp.isOK() {
  579. return nil, errRsp
  580. }
  581. err = sv.Join(sb)
  582. if err != nil {
  583. return nil, convertNetworkError(err)
  584. }
  585. return sb.Key(), &successResponse
  586. }
  587. func procDetachBackend(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  588. epT, epBy := detectEndpointTarget(vars)
  589. sv, errRsp := findService(c, epT, epBy)
  590. if !errRsp.isOK() {
  591. return nil, errRsp
  592. }
  593. sb, errRsp := findSandbox(c, vars[urlSbID], byID)
  594. if !errRsp.isOK() {
  595. return nil, errRsp
  596. }
  597. err := sv.Leave(sb)
  598. if err != nil {
  599. return nil, convertNetworkError(err)
  600. }
  601. return nil, &successResponse
  602. }
  603. /******************
  604. Sandbox interface
  605. *******************/
  606. func procGetSandbox(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  607. if epT, ok := vars[urlEpID]; ok {
  608. sv, errRsp := findService(c, epT, byID)
  609. if !errRsp.isOK() {
  610. return nil, endpointToService(errRsp)
  611. }
  612. return buildSandboxResource(sv.Info().Sandbox()), &successResponse
  613. }
  614. sbT, by := detectSandboxTarget(vars)
  615. sb, errRsp := findSandbox(c, sbT, by)
  616. if !errRsp.isOK() {
  617. return nil, errRsp
  618. }
  619. return buildSandboxResource(sb), &successResponse
  620. }
  621. type cndFnMkr func(string) cndFn
  622. type cndFn func(libnetwork.Sandbox) bool
  623. // list of (query type, condition function makers) couples
  624. var cndMkrList = []struct {
  625. identifier string
  626. maker cndFnMkr
  627. }{
  628. {urlSbPID, func(id string) cndFn {
  629. return func(sb libnetwork.Sandbox) bool { return strings.HasPrefix(sb.ID(), id) }
  630. }},
  631. {urlCnID, func(id string) cndFn {
  632. return func(sb libnetwork.Sandbox) bool { return sb.ContainerID() == id }
  633. }},
  634. {urlCnPID, func(id string) cndFn {
  635. return func(sb libnetwork.Sandbox) bool { return strings.HasPrefix(sb.ContainerID(), id) }
  636. }},
  637. }
  638. func getQueryCondition(vars map[string]string) func(libnetwork.Sandbox) bool {
  639. for _, im := range cndMkrList {
  640. if val, ok := vars[im.identifier]; ok {
  641. return im.maker(val)
  642. }
  643. }
  644. return func(sb libnetwork.Sandbox) bool { return true }
  645. }
  646. func sandboxWalker(condition cndFn, list *[]*sandboxResource) libnetwork.SandboxWalker {
  647. return func(sb libnetwork.Sandbox) bool {
  648. if condition(sb) {
  649. *list = append(*list, buildSandboxResource(sb))
  650. }
  651. return false
  652. }
  653. }
  654. func procGetSandboxes(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  655. var list []*sandboxResource
  656. cnd := getQueryCondition(vars)
  657. c.WalkSandboxes(sandboxWalker(cnd, &list))
  658. return list, &successResponse
  659. }
  660. func procDeleteSandbox(c libnetwork.NetworkController, vars map[string]string, body []byte) (interface{}, *responseStatus) {
  661. sbT, by := detectSandboxTarget(vars)
  662. sb, errRsp := findSandbox(c, sbT, by)
  663. if !errRsp.isOK() {
  664. return nil, errRsp
  665. }
  666. err := sb.Delete()
  667. if err != nil {
  668. return nil, convertNetworkError(err)
  669. }
  670. return nil, &successResponse
  671. }
  672. /***********
  673. Utilities
  674. ************/
  675. const (
  676. byID = iota
  677. byName
  678. )
  679. func detectNetworkTarget(vars map[string]string) (string, int) {
  680. if target, ok := vars[urlNwName]; ok {
  681. return target, byName
  682. }
  683. if target, ok := vars[urlNwID]; ok {
  684. return target, byID
  685. }
  686. // vars are populated from the URL, following cannot happen
  687. panic("Missing URL variable parameter for network")
  688. }
  689. func detectSandboxTarget(vars map[string]string) (string, int) {
  690. if target, ok := vars[urlSbID]; ok {
  691. return target, byID
  692. }
  693. // vars are populated from the URL, following cannot happen
  694. panic("Missing URL variable parameter for sandbox")
  695. }
  696. func detectEndpointTarget(vars map[string]string) (string, int) {
  697. if target, ok := vars[urlEpName]; ok {
  698. return target, byName
  699. }
  700. if target, ok := vars[urlEpID]; ok {
  701. return target, byID
  702. }
  703. // vars are populated from the URL, following cannot happen
  704. panic("Missing URL variable parameter for endpoint")
  705. }
  706. func findNetwork(c libnetwork.NetworkController, s string, by int) (libnetwork.Network, *responseStatus) {
  707. var (
  708. nw libnetwork.Network
  709. err error
  710. )
  711. switch by {
  712. case byID:
  713. nw, err = c.NetworkByID(s)
  714. case byName:
  715. if s == "" {
  716. s = c.Config().Daemon.DefaultNetwork
  717. }
  718. nw, err = c.NetworkByName(s)
  719. default:
  720. panic(fmt.Sprintf("unexpected selector for network search: %d", by))
  721. }
  722. if err != nil {
  723. if _, ok := err.(types.NotFoundError); ok {
  724. return nil, &responseStatus{Status: "Resource not found: Network", StatusCode: http.StatusNotFound}
  725. }
  726. return nil, &responseStatus{Status: err.Error(), StatusCode: http.StatusBadRequest}
  727. }
  728. return nw, &successResponse
  729. }
  730. func findSandbox(c libnetwork.NetworkController, s string, by int) (libnetwork.Sandbox, *responseStatus) {
  731. var (
  732. sb libnetwork.Sandbox
  733. err error
  734. )
  735. switch by {
  736. case byID:
  737. sb, err = c.SandboxByID(s)
  738. default:
  739. panic(fmt.Sprintf("unexpected selector for sandbox search: %d", by))
  740. }
  741. if err != nil {
  742. if _, ok := err.(types.NotFoundError); ok {
  743. return nil, &responseStatus{Status: "Resource not found: Sandbox", StatusCode: http.StatusNotFound}
  744. }
  745. return nil, &responseStatus{Status: err.Error(), StatusCode: http.StatusBadRequest}
  746. }
  747. return sb, &successResponse
  748. }
  749. func findEndpoint(c libnetwork.NetworkController, ns, es string, nwBy, epBy int) (libnetwork.Endpoint, *responseStatus) {
  750. nw, errRsp := findNetwork(c, ns, nwBy)
  751. if !errRsp.isOK() {
  752. return nil, errRsp
  753. }
  754. var (
  755. err error
  756. ep libnetwork.Endpoint
  757. )
  758. switch epBy {
  759. case byID:
  760. ep, err = nw.EndpointByID(es)
  761. case byName:
  762. ep, err = nw.EndpointByName(es)
  763. default:
  764. panic(fmt.Sprintf("unexpected selector for endpoint search: %d", epBy))
  765. }
  766. if err != nil {
  767. if _, ok := err.(types.NotFoundError); ok {
  768. return nil, &responseStatus{Status: "Resource not found: Endpoint", StatusCode: http.StatusNotFound}
  769. }
  770. return nil, &responseStatus{Status: err.Error(), StatusCode: http.StatusBadRequest}
  771. }
  772. return ep, &successResponse
  773. }
  774. func findService(c libnetwork.NetworkController, svs string, svBy int) (libnetwork.Endpoint, *responseStatus) {
  775. for _, nw := range c.Networks() {
  776. var (
  777. ep libnetwork.Endpoint
  778. err error
  779. )
  780. switch svBy {
  781. case byID:
  782. ep, err = nw.EndpointByID(svs)
  783. case byName:
  784. ep, err = nw.EndpointByName(svs)
  785. default:
  786. panic(fmt.Sprintf("unexpected selector for service search: %d", svBy))
  787. }
  788. if err == nil {
  789. return ep, &successResponse
  790. } else if _, ok := err.(types.NotFoundError); !ok {
  791. return nil, convertNetworkError(err)
  792. }
  793. }
  794. return nil, &responseStatus{Status: "Service not found", StatusCode: http.StatusNotFound}
  795. }
  796. func endpointToService(rsp *responseStatus) *responseStatus {
  797. rsp.Status = strings.Replace(rsp.Status, "endpoint", "service", -1)
  798. return rsp
  799. }
  800. func convertNetworkError(err error) *responseStatus {
  801. var code int
  802. switch err.(type) {
  803. case types.BadRequestError:
  804. code = http.StatusBadRequest
  805. case types.ForbiddenError:
  806. code = http.StatusForbidden
  807. case types.NotFoundError:
  808. code = http.StatusNotFound
  809. case types.TimeoutError:
  810. code = http.StatusRequestTimeout
  811. case types.NotImplementedError:
  812. code = http.StatusNotImplemented
  813. case types.NoServiceError:
  814. code = http.StatusServiceUnavailable
  815. case types.InternalError:
  816. code = http.StatusInternalServerError
  817. default:
  818. code = http.StatusInternalServerError
  819. }
  820. return &responseStatus{Status: err.Error(), StatusCode: code}
  821. }
  822. func writeJSON(w http.ResponseWriter, code int, v interface{}) error {
  823. w.Header().Set("Content-Type", "application/json")
  824. w.WriteHeader(code)
  825. return json.NewEncoder(w).Encode(v)
  826. }