api.go 26 KB

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