api.go 26 KB

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