api.go 25 KB

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