api.go 25 KB

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