api.go 26 KB

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