network_routes.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592
  1. package network
  2. import (
  3. "encoding/json"
  4. "net/http"
  5. "strconv"
  6. "strings"
  7. "golang.org/x/net/context"
  8. "github.com/docker/docker/api/server/httputils"
  9. "github.com/docker/docker/api/types"
  10. "github.com/docker/docker/api/types/filters"
  11. "github.com/docker/docker/api/types/network"
  12. "github.com/docker/docker/api/types/versions"
  13. "github.com/docker/docker/errdefs"
  14. "github.com/docker/libnetwork"
  15. netconst "github.com/docker/libnetwork/datastore"
  16. "github.com/docker/libnetwork/networkdb"
  17. "github.com/pkg/errors"
  18. )
  19. var (
  20. // acceptedNetworkFilters is a list of acceptable filters
  21. acceptedNetworkFilters = map[string]bool{
  22. "driver": true,
  23. "type": true,
  24. "name": true,
  25. "id": true,
  26. "label": true,
  27. "scope": true,
  28. }
  29. )
  30. func (n *networkRouter) getNetworksList(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  31. if err := httputils.ParseForm(r); err != nil {
  32. return err
  33. }
  34. filter := r.Form.Get("filters")
  35. netFilters, err := filters.FromJSON(filter)
  36. if err != nil {
  37. return err
  38. }
  39. if err := netFilters.Validate(acceptedNetworkFilters); err != nil {
  40. return err
  41. }
  42. list := []types.NetworkResource{}
  43. if nr, err := n.cluster.GetNetworks(); err == nil {
  44. list = append(list, nr...)
  45. }
  46. // Combine the network list returned by Docker daemon if it is not already
  47. // returned by the cluster manager
  48. SKIP:
  49. for _, nw := range n.backend.GetNetworks() {
  50. for _, nl := range list {
  51. if nl.ID == nw.ID() {
  52. continue SKIP
  53. }
  54. }
  55. var nr *types.NetworkResource
  56. // Versions < 1.28 fetches all the containers attached to a network
  57. // in a network list api call. It is a heavy weight operation when
  58. // run across all the networks. Starting API version 1.28, this detailed
  59. // info is available for network specific GET API (equivalent to inspect)
  60. if versions.LessThan(httputils.VersionFromContext(ctx), "1.28") {
  61. nr = n.buildDetailedNetworkResources(nw, false)
  62. } else {
  63. nr = n.buildNetworkResource(nw)
  64. }
  65. list = append(list, *nr)
  66. }
  67. list, err = filterNetworks(list, netFilters)
  68. if err != nil {
  69. return err
  70. }
  71. return httputils.WriteJSON(w, http.StatusOK, list)
  72. }
  73. type invalidRequestError struct {
  74. cause error
  75. }
  76. func (e invalidRequestError) Error() string {
  77. return e.cause.Error()
  78. }
  79. func (e invalidRequestError) InvalidParameter() {}
  80. type ambigousResultsError string
  81. func (e ambigousResultsError) Error() string {
  82. return "network " + string(e) + " is ambiguous"
  83. }
  84. func (ambigousResultsError) InvalidParameter() {}
  85. func nameConflict(name string) error {
  86. return errdefs.Conflict(libnetwork.NetworkNameError(name))
  87. }
  88. func (n *networkRouter) getNetwork(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  89. if err := httputils.ParseForm(r); err != nil {
  90. return err
  91. }
  92. term := vars["id"]
  93. var (
  94. verbose bool
  95. err error
  96. )
  97. if v := r.URL.Query().Get("verbose"); v != "" {
  98. if verbose, err = strconv.ParseBool(v); err != nil {
  99. return errors.Wrapf(invalidRequestError{err}, "invalid value for verbose: %s", v)
  100. }
  101. }
  102. scope := r.URL.Query().Get("scope")
  103. isMatchingScope := func(scope, term string) bool {
  104. if term != "" {
  105. return scope == term
  106. }
  107. return true
  108. }
  109. // In case multiple networks have duplicate names, return error.
  110. // TODO (yongtang): should we wrap with version here for backward compatibility?
  111. // First find based on full ID, return immediately once one is found.
  112. // If a network appears both in swarm and local, assume it is in local first
  113. // For full name and partial ID, save the result first, and process later
  114. // in case multiple records was found based on the same term
  115. listByFullName := map[string]types.NetworkResource{}
  116. listByPartialID := map[string]types.NetworkResource{}
  117. nw := n.backend.GetNetworks()
  118. for _, network := range nw {
  119. if network.ID() == term && isMatchingScope(network.Info().Scope(), scope) {
  120. return httputils.WriteJSON(w, http.StatusOK, *n.buildDetailedNetworkResources(network, verbose))
  121. }
  122. if network.Name() == term && isMatchingScope(network.Info().Scope(), scope) {
  123. // No need to check the ID collision here as we are still in
  124. // local scope and the network ID is unique in this scope.
  125. listByFullName[network.ID()] = *n.buildDetailedNetworkResources(network, verbose)
  126. }
  127. if strings.HasPrefix(network.ID(), term) && isMatchingScope(network.Info().Scope(), scope) {
  128. // No need to check the ID collision here as we are still in
  129. // local scope and the network ID is unique in this scope.
  130. listByPartialID[network.ID()] = *n.buildDetailedNetworkResources(network, verbose)
  131. }
  132. }
  133. nwk, err := n.cluster.GetNetwork(term)
  134. if err == nil {
  135. // If the get network is passed with a specific network ID / partial network ID
  136. // or if the get network was passed with a network name and scope as swarm
  137. // return the network. Skipped using isMatchingScope because it is true if the scope
  138. // is not set which would be case if the client API v1.30
  139. if strings.HasPrefix(nwk.ID, term) || (netconst.SwarmScope == scope) {
  140. return httputils.WriteJSON(w, http.StatusOK, nwk)
  141. }
  142. }
  143. nr, _ := n.cluster.GetNetworks()
  144. for _, network := range nr {
  145. if network.ID == term && isMatchingScope(network.Scope, scope) {
  146. return httputils.WriteJSON(w, http.StatusOK, network)
  147. }
  148. if network.Name == term && isMatchingScope(network.Scope, scope) {
  149. // Check the ID collision as we are in swarm scope here, and
  150. // the map (of the listByFullName) may have already had a
  151. // network with the same ID (from local scope previously)
  152. if _, ok := listByFullName[network.ID]; !ok {
  153. listByFullName[network.ID] = network
  154. }
  155. }
  156. if strings.HasPrefix(network.ID, term) && isMatchingScope(network.Scope, scope) {
  157. // Check the ID collision as we are in swarm scope here, and
  158. // the map (of the listByPartialID) may have already had a
  159. // network with the same ID (from local scope previously)
  160. if _, ok := listByPartialID[network.ID]; !ok {
  161. listByPartialID[network.ID] = network
  162. }
  163. }
  164. }
  165. // Find based on full name, returns true only if no duplicates
  166. if len(listByFullName) == 1 {
  167. for _, v := range listByFullName {
  168. return httputils.WriteJSON(w, http.StatusOK, v)
  169. }
  170. }
  171. if len(listByFullName) > 1 {
  172. return errors.Wrapf(ambigousResultsError(term), "%d matches found based on name", len(listByFullName))
  173. }
  174. // Find based on partial ID, returns true only if no duplicates
  175. if len(listByPartialID) == 1 {
  176. for _, v := range listByPartialID {
  177. return httputils.WriteJSON(w, http.StatusOK, v)
  178. }
  179. }
  180. if len(listByPartialID) > 1 {
  181. return errors.Wrapf(ambigousResultsError(term), "%d matches found based on ID prefix", len(listByPartialID))
  182. }
  183. return libnetwork.ErrNoSuchNetwork(term)
  184. }
  185. func (n *networkRouter) postNetworkCreate(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  186. var create types.NetworkCreateRequest
  187. if err := httputils.ParseForm(r); err != nil {
  188. return err
  189. }
  190. if err := httputils.CheckForJSON(r); err != nil {
  191. return err
  192. }
  193. if err := json.NewDecoder(r.Body).Decode(&create); err != nil {
  194. return err
  195. }
  196. if nws, err := n.cluster.GetNetworksByName(create.Name); err == nil && len(nws) > 0 {
  197. return nameConflict(create.Name)
  198. }
  199. nw, err := n.backend.CreateNetwork(create)
  200. if err != nil {
  201. var warning string
  202. if _, ok := err.(libnetwork.NetworkNameError); ok {
  203. // check if user defined CheckDuplicate, if set true, return err
  204. // otherwise prepare a warning message
  205. if create.CheckDuplicate {
  206. return nameConflict(create.Name)
  207. }
  208. warning = libnetwork.NetworkNameError(create.Name).Error()
  209. }
  210. if _, ok := err.(libnetwork.ManagerRedirectError); !ok {
  211. return err
  212. }
  213. id, err := n.cluster.CreateNetwork(create)
  214. if err != nil {
  215. return err
  216. }
  217. nw = &types.NetworkCreateResponse{
  218. ID: id,
  219. Warning: warning,
  220. }
  221. }
  222. return httputils.WriteJSON(w, http.StatusCreated, nw)
  223. }
  224. func (n *networkRouter) postNetworkConnect(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  225. var connect types.NetworkConnect
  226. if err := httputils.ParseForm(r); err != nil {
  227. return err
  228. }
  229. if err := httputils.CheckForJSON(r); err != nil {
  230. return err
  231. }
  232. if err := json.NewDecoder(r.Body).Decode(&connect); err != nil {
  233. return err
  234. }
  235. // Always make sure there is no ambiguity with respect to the network ID/name
  236. nw, err := n.backend.FindNetwork(vars["id"])
  237. if err != nil {
  238. return err
  239. }
  240. return n.backend.ConnectContainerToNetwork(connect.Container, nw.ID(), connect.EndpointConfig)
  241. }
  242. func (n *networkRouter) postNetworkDisconnect(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  243. var disconnect types.NetworkDisconnect
  244. if err := httputils.ParseForm(r); err != nil {
  245. return err
  246. }
  247. if err := httputils.CheckForJSON(r); err != nil {
  248. return err
  249. }
  250. if err := json.NewDecoder(r.Body).Decode(&disconnect); err != nil {
  251. return err
  252. }
  253. return n.backend.DisconnectContainerFromNetwork(disconnect.Container, vars["id"], disconnect.Force)
  254. }
  255. func (n *networkRouter) deleteNetwork(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  256. if err := httputils.ParseForm(r); err != nil {
  257. return err
  258. }
  259. nw, err := n.findUniqueNetwork(vars["id"])
  260. if err != nil {
  261. return err
  262. }
  263. if nw.Scope == "swarm" {
  264. if err = n.cluster.RemoveNetwork(nw.ID); err != nil {
  265. return err
  266. }
  267. } else {
  268. if err := n.backend.DeleteNetwork(nw.ID); err != nil {
  269. return err
  270. }
  271. }
  272. w.WriteHeader(http.StatusNoContent)
  273. return nil
  274. }
  275. func (n *networkRouter) buildNetworkResource(nw libnetwork.Network) *types.NetworkResource {
  276. r := &types.NetworkResource{}
  277. if nw == nil {
  278. return r
  279. }
  280. info := nw.Info()
  281. r.Name = nw.Name()
  282. r.ID = nw.ID()
  283. r.Created = info.Created()
  284. r.Scope = info.Scope()
  285. r.Driver = nw.Type()
  286. r.EnableIPv6 = info.IPv6Enabled()
  287. r.Internal = info.Internal()
  288. r.Attachable = info.Attachable()
  289. r.Ingress = info.Ingress()
  290. r.Options = info.DriverOptions()
  291. r.Containers = make(map[string]types.EndpointResource)
  292. buildIpamResources(r, info)
  293. r.Labels = info.Labels()
  294. r.ConfigOnly = info.ConfigOnly()
  295. if cn := info.ConfigFrom(); cn != "" {
  296. r.ConfigFrom = network.ConfigReference{Network: cn}
  297. }
  298. peers := info.Peers()
  299. if len(peers) != 0 {
  300. r.Peers = buildPeerInfoResources(peers)
  301. }
  302. return r
  303. }
  304. func (n *networkRouter) buildDetailedNetworkResources(nw libnetwork.Network, verbose bool) *types.NetworkResource {
  305. if nw == nil {
  306. return &types.NetworkResource{}
  307. }
  308. r := n.buildNetworkResource(nw)
  309. epl := nw.Endpoints()
  310. for _, e := range epl {
  311. ei := e.Info()
  312. if ei == nil {
  313. continue
  314. }
  315. sb := ei.Sandbox()
  316. tmpID := e.ID()
  317. key := "ep-" + tmpID
  318. if sb != nil {
  319. key = sb.ContainerID()
  320. }
  321. r.Containers[key] = buildEndpointResource(tmpID, e.Name(), ei)
  322. }
  323. if !verbose {
  324. return r
  325. }
  326. services := nw.Info().Services()
  327. r.Services = make(map[string]network.ServiceInfo)
  328. for name, service := range services {
  329. tasks := []network.Task{}
  330. for _, t := range service.Tasks {
  331. tasks = append(tasks, network.Task{
  332. Name: t.Name,
  333. EndpointID: t.EndpointID,
  334. EndpointIP: t.EndpointIP,
  335. Info: t.Info,
  336. })
  337. }
  338. r.Services[name] = network.ServiceInfo{
  339. VIP: service.VIP,
  340. Ports: service.Ports,
  341. Tasks: tasks,
  342. LocalLBIndex: service.LocalLBIndex,
  343. }
  344. }
  345. return r
  346. }
  347. func buildPeerInfoResources(peers []networkdb.PeerInfo) []network.PeerInfo {
  348. peerInfo := make([]network.PeerInfo, 0, len(peers))
  349. for _, peer := range peers {
  350. peerInfo = append(peerInfo, network.PeerInfo{
  351. Name: peer.Name,
  352. IP: peer.IP,
  353. })
  354. }
  355. return peerInfo
  356. }
  357. func buildIpamResources(r *types.NetworkResource, nwInfo libnetwork.NetworkInfo) {
  358. id, opts, ipv4conf, ipv6conf := nwInfo.IpamConfig()
  359. ipv4Info, ipv6Info := nwInfo.IpamInfo()
  360. r.IPAM.Driver = id
  361. r.IPAM.Options = opts
  362. r.IPAM.Config = []network.IPAMConfig{}
  363. for _, ip4 := range ipv4conf {
  364. if ip4.PreferredPool == "" {
  365. continue
  366. }
  367. iData := network.IPAMConfig{}
  368. iData.Subnet = ip4.PreferredPool
  369. iData.IPRange = ip4.SubPool
  370. iData.Gateway = ip4.Gateway
  371. iData.AuxAddress = ip4.AuxAddresses
  372. r.IPAM.Config = append(r.IPAM.Config, iData)
  373. }
  374. if len(r.IPAM.Config) == 0 {
  375. for _, ip4Info := range ipv4Info {
  376. iData := network.IPAMConfig{}
  377. iData.Subnet = ip4Info.IPAMData.Pool.String()
  378. if ip4Info.IPAMData.Gateway != nil {
  379. iData.Gateway = ip4Info.IPAMData.Gateway.IP.String()
  380. }
  381. r.IPAM.Config = append(r.IPAM.Config, iData)
  382. }
  383. }
  384. hasIpv6Conf := false
  385. for _, ip6 := range ipv6conf {
  386. if ip6.PreferredPool == "" {
  387. continue
  388. }
  389. hasIpv6Conf = true
  390. iData := network.IPAMConfig{}
  391. iData.Subnet = ip6.PreferredPool
  392. iData.IPRange = ip6.SubPool
  393. iData.Gateway = ip6.Gateway
  394. iData.AuxAddress = ip6.AuxAddresses
  395. r.IPAM.Config = append(r.IPAM.Config, iData)
  396. }
  397. if !hasIpv6Conf {
  398. for _, ip6Info := range ipv6Info {
  399. if ip6Info.IPAMData.Pool == nil {
  400. continue
  401. }
  402. iData := network.IPAMConfig{}
  403. iData.Subnet = ip6Info.IPAMData.Pool.String()
  404. iData.Gateway = ip6Info.IPAMData.Gateway.String()
  405. r.IPAM.Config = append(r.IPAM.Config, iData)
  406. }
  407. }
  408. }
  409. func buildEndpointResource(id string, name string, info libnetwork.EndpointInfo) types.EndpointResource {
  410. er := types.EndpointResource{}
  411. er.EndpointID = id
  412. er.Name = name
  413. ei := info
  414. if ei == nil {
  415. return er
  416. }
  417. if iface := ei.Iface(); iface != nil {
  418. if mac := iface.MacAddress(); mac != nil {
  419. er.MacAddress = mac.String()
  420. }
  421. if ip := iface.Address(); ip != nil && len(ip.IP) > 0 {
  422. er.IPv4Address = ip.String()
  423. }
  424. if ipv6 := iface.AddressIPv6(); ipv6 != nil && len(ipv6.IP) > 0 {
  425. er.IPv6Address = ipv6.String()
  426. }
  427. }
  428. return er
  429. }
  430. func (n *networkRouter) postNetworksPrune(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  431. if err := httputils.ParseForm(r); err != nil {
  432. return err
  433. }
  434. pruneFilters, err := filters.FromJSON(r.Form.Get("filters"))
  435. if err != nil {
  436. return err
  437. }
  438. pruneReport, err := n.backend.NetworksPrune(ctx, pruneFilters)
  439. if err != nil {
  440. return err
  441. }
  442. return httputils.WriteJSON(w, http.StatusOK, pruneReport)
  443. }
  444. // findUniqueNetwork will search network across different scopes (both local and swarm).
  445. // NOTE: This findUniqueNetwork is different from FindNetwork in the daemon.
  446. // In case multiple networks have duplicate names, return error.
  447. // First find based on full ID, return immediately once one is found.
  448. // If a network appears both in swarm and local, assume it is in local first
  449. // For full name and partial ID, save the result first, and process later
  450. // in case multiple records was found based on the same term
  451. // TODO (yongtang): should we wrap with version here for backward compatibility?
  452. func (n *networkRouter) findUniqueNetwork(term string) (types.NetworkResource, error) {
  453. listByFullName := map[string]types.NetworkResource{}
  454. listByPartialID := map[string]types.NetworkResource{}
  455. nw := n.backend.GetNetworks()
  456. for _, network := range nw {
  457. if network.ID() == term {
  458. return *n.buildDetailedNetworkResources(network, false), nil
  459. }
  460. if network.Name() == term && !network.Info().Ingress() {
  461. // No need to check the ID collision here as we are still in
  462. // local scope and the network ID is unique in this scope.
  463. listByFullName[network.ID()] = *n.buildDetailedNetworkResources(network, false)
  464. }
  465. if strings.HasPrefix(network.ID(), term) {
  466. // No need to check the ID collision here as we are still in
  467. // local scope and the network ID is unique in this scope.
  468. listByPartialID[network.ID()] = *n.buildDetailedNetworkResources(network, false)
  469. }
  470. }
  471. nr, _ := n.cluster.GetNetworks()
  472. for _, network := range nr {
  473. if network.ID == term {
  474. return network, nil
  475. }
  476. if network.Name == term {
  477. // Check the ID collision as we are in swarm scope here, and
  478. // the map (of the listByFullName) may have already had a
  479. // network with the same ID (from local scope previously)
  480. if _, ok := listByFullName[network.ID]; !ok {
  481. listByFullName[network.ID] = network
  482. }
  483. }
  484. if strings.HasPrefix(network.ID, term) {
  485. // Check the ID collision as we are in swarm scope here, and
  486. // the map (of the listByPartialID) may have already had a
  487. // network with the same ID (from local scope previously)
  488. if _, ok := listByPartialID[network.ID]; !ok {
  489. listByPartialID[network.ID] = network
  490. }
  491. }
  492. }
  493. // Find based on full name, returns true only if no duplicates
  494. if len(listByFullName) == 1 {
  495. for _, v := range listByFullName {
  496. return v, nil
  497. }
  498. }
  499. if len(listByFullName) > 1 {
  500. return types.NetworkResource{}, errdefs.InvalidParameter(errors.Errorf("network %s is ambiguous (%d matches found based on name)", term, len(listByFullName)))
  501. }
  502. // Find based on partial ID, returns true only if no duplicates
  503. if len(listByPartialID) == 1 {
  504. for _, v := range listByPartialID {
  505. return v, nil
  506. }
  507. }
  508. if len(listByPartialID) > 1 {
  509. return types.NetworkResource{}, errdefs.InvalidParameter(errors.Errorf("network %s is ambiguous (%d matches found based on ID prefix)", term, len(listByPartialID)))
  510. }
  511. return types.NetworkResource{}, errdefs.NotFound(libnetwork.ErrNoSuchNetwork(term))
  512. }