api.go 27 KB

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