network_routes.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  1. package network
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "net/http"
  6. "strconv"
  7. "strings"
  8. "golang.org/x/net/context"
  9. "github.com/docker/docker/api/errors"
  10. "github.com/docker/docker/api/server/httputils"
  11. "github.com/docker/docker/api/types"
  12. "github.com/docker/docker/api/types/filters"
  13. "github.com/docker/docker/api/types/network"
  14. "github.com/docker/docker/api/types/versions"
  15. "github.com/docker/libnetwork"
  16. netconst "github.com/docker/libnetwork/datastore"
  17. "github.com/docker/libnetwork/networkdb"
  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.FromParam(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. func (n *networkRouter) getNetwork(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  74. if err := httputils.ParseForm(r); err != nil {
  75. return err
  76. }
  77. term := vars["id"]
  78. var (
  79. verbose bool
  80. err error
  81. )
  82. if v := r.URL.Query().Get("verbose"); v != "" {
  83. if verbose, err = strconv.ParseBool(v); err != nil {
  84. err = fmt.Errorf("invalid value for verbose: %s", v)
  85. return errors.NewBadRequestError(err)
  86. }
  87. }
  88. scope := r.URL.Query().Get("scope")
  89. isMatchingScope := func(scope, term string) bool {
  90. if term != "" {
  91. return scope == term
  92. }
  93. return true
  94. }
  95. // In case multiple networks have duplicate names, return error.
  96. // TODO (yongtang): should we wrap with version here for backward compatibility?
  97. // First find based on full ID, return immediately once one is found.
  98. // If a network appears both in swarm and local, assume it is in local first
  99. // For full name and partial ID, save the result first, and process later
  100. // in case multiple records was found based on the same term
  101. listByFullName := map[string]types.NetworkResource{}
  102. listByPartialID := map[string]types.NetworkResource{}
  103. nw := n.backend.GetNetworks()
  104. for _, network := range nw {
  105. if network.ID() == term && isMatchingScope(network.Info().Scope(), scope) {
  106. return httputils.WriteJSON(w, http.StatusOK, *n.buildDetailedNetworkResources(network, verbose))
  107. }
  108. if network.Name() == term && isMatchingScope(network.Info().Scope(), scope) {
  109. // No need to check the ID collision here as we are still in
  110. // local scope and the network ID is unique in this scope.
  111. listByFullName[network.ID()] = *n.buildDetailedNetworkResources(network, verbose)
  112. }
  113. if strings.HasPrefix(network.ID(), term) && isMatchingScope(network.Info().Scope(), scope) {
  114. // No need to check the ID collision here as we are still in
  115. // local scope and the network ID is unique in this scope.
  116. listByPartialID[network.ID()] = *n.buildDetailedNetworkResources(network, verbose)
  117. }
  118. }
  119. nwk, err := n.cluster.GetNetwork(term)
  120. if err == nil {
  121. // If the get network is passed with a specific network ID / partial network ID
  122. // or if the get network was passed with a network name and scope as swarm
  123. // return the network. Skipped using isMatchingScope because it is true if the scope
  124. // is not set which would be case if the client API v1.30
  125. if strings.HasPrefix(nwk.ID, term) || (netconst.SwarmScope == scope) {
  126. return httputils.WriteJSON(w, http.StatusOK, nwk)
  127. }
  128. }
  129. nr, _ := n.cluster.GetNetworks()
  130. for _, network := range nr {
  131. if network.ID == term && isMatchingScope(network.Scope, scope) {
  132. return httputils.WriteJSON(w, http.StatusOK, network)
  133. }
  134. if network.Name == term && isMatchingScope(network.Scope, scope) {
  135. // Check the ID collision as we are in swarm scope here, and
  136. // the map (of the listByFullName) may have already had a
  137. // network with the same ID (from local scope previously)
  138. if _, ok := listByFullName[network.ID]; !ok {
  139. listByFullName[network.ID] = network
  140. }
  141. }
  142. if strings.HasPrefix(network.ID, term) && isMatchingScope(network.Scope, scope) {
  143. // Check the ID collision as we are in swarm scope here, and
  144. // the map (of the listByPartialID) may have already had a
  145. // network with the same ID (from local scope previously)
  146. if _, ok := listByPartialID[network.ID]; !ok {
  147. listByPartialID[network.ID] = network
  148. }
  149. }
  150. }
  151. // Find based on full name, returns true only if no duplicates
  152. if len(listByFullName) == 1 {
  153. for _, v := range listByFullName {
  154. return httputils.WriteJSON(w, http.StatusOK, v)
  155. }
  156. }
  157. if len(listByFullName) > 1 {
  158. return fmt.Errorf("network %s is ambiguous (%d matches found based on name)", term, len(listByFullName))
  159. }
  160. // Find based on partial ID, returns true only if no duplicates
  161. if len(listByPartialID) == 1 {
  162. for _, v := range listByPartialID {
  163. return httputils.WriteJSON(w, http.StatusOK, v)
  164. }
  165. }
  166. if len(listByPartialID) > 1 {
  167. return fmt.Errorf("network %s is ambiguous (%d matches found based on ID prefix)", term, len(listByPartialID))
  168. }
  169. return libnetwork.ErrNoSuchNetwork(term)
  170. }
  171. func (n *networkRouter) postNetworkCreate(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  172. var create types.NetworkCreateRequest
  173. if err := httputils.ParseForm(r); err != nil {
  174. return err
  175. }
  176. if err := httputils.CheckForJSON(r); err != nil {
  177. return err
  178. }
  179. if err := json.NewDecoder(r.Body).Decode(&create); err != nil {
  180. return err
  181. }
  182. if nws, err := n.cluster.GetNetworksByName(create.Name); err == nil && len(nws) > 0 {
  183. return libnetwork.NetworkNameError(create.Name)
  184. }
  185. nw, err := n.backend.CreateNetwork(create)
  186. if err != nil {
  187. var warning string
  188. if _, ok := err.(libnetwork.NetworkNameError); ok {
  189. // check if user defined CheckDuplicate, if set true, return err
  190. // otherwise prepare a warning message
  191. if create.CheckDuplicate {
  192. return libnetwork.NetworkNameError(create.Name)
  193. }
  194. warning = libnetwork.NetworkNameError(create.Name).Error()
  195. }
  196. if _, ok := err.(libnetwork.ManagerRedirectError); !ok {
  197. return err
  198. }
  199. id, err := n.cluster.CreateNetwork(create)
  200. if err != nil {
  201. return err
  202. }
  203. nw = &types.NetworkCreateResponse{
  204. ID: id,
  205. Warning: warning,
  206. }
  207. }
  208. return httputils.WriteJSON(w, http.StatusCreated, nw)
  209. }
  210. func (n *networkRouter) postNetworkConnect(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  211. var connect types.NetworkConnect
  212. if err := httputils.ParseForm(r); err != nil {
  213. return err
  214. }
  215. if err := httputils.CheckForJSON(r); err != nil {
  216. return err
  217. }
  218. if err := json.NewDecoder(r.Body).Decode(&connect); err != nil {
  219. return err
  220. }
  221. return n.backend.ConnectContainerToNetwork(connect.Container, vars["id"], connect.EndpointConfig)
  222. }
  223. func (n *networkRouter) postNetworkDisconnect(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  224. var disconnect types.NetworkDisconnect
  225. if err := httputils.ParseForm(r); err != nil {
  226. return err
  227. }
  228. if err := httputils.CheckForJSON(r); err != nil {
  229. return err
  230. }
  231. if err := json.NewDecoder(r.Body).Decode(&disconnect); err != nil {
  232. return err
  233. }
  234. return n.backend.DisconnectContainerFromNetwork(disconnect.Container, vars["id"], disconnect.Force)
  235. }
  236. func (n *networkRouter) deleteNetwork(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  237. if err := httputils.ParseForm(r); err != nil {
  238. return err
  239. }
  240. if _, err := n.cluster.GetNetwork(vars["id"]); err == nil {
  241. if err = n.cluster.RemoveNetwork(vars["id"]); err != nil {
  242. return err
  243. }
  244. w.WriteHeader(http.StatusNoContent)
  245. return nil
  246. }
  247. if err := n.backend.DeleteNetwork(vars["id"]); err != nil {
  248. return err
  249. }
  250. w.WriteHeader(http.StatusNoContent)
  251. return nil
  252. }
  253. func (n *networkRouter) buildNetworkResource(nw libnetwork.Network) *types.NetworkResource {
  254. r := &types.NetworkResource{}
  255. if nw == nil {
  256. return r
  257. }
  258. info := nw.Info()
  259. r.Name = nw.Name()
  260. r.ID = nw.ID()
  261. r.Created = info.Created()
  262. r.Scope = info.Scope()
  263. r.Driver = nw.Type()
  264. r.EnableIPv6 = info.IPv6Enabled()
  265. r.Internal = info.Internal()
  266. r.Attachable = info.Attachable()
  267. r.Ingress = info.Ingress()
  268. r.Options = info.DriverOptions()
  269. r.Containers = make(map[string]types.EndpointResource)
  270. buildIpamResources(r, info)
  271. r.Labels = info.Labels()
  272. r.ConfigOnly = info.ConfigOnly()
  273. if cn := info.ConfigFrom(); cn != "" {
  274. r.ConfigFrom = network.ConfigReference{Network: cn}
  275. }
  276. peers := info.Peers()
  277. if len(peers) != 0 {
  278. r.Peers = buildPeerInfoResources(peers)
  279. }
  280. return r
  281. }
  282. func (n *networkRouter) buildDetailedNetworkResources(nw libnetwork.Network, verbose bool) *types.NetworkResource {
  283. if nw == nil {
  284. return &types.NetworkResource{}
  285. }
  286. r := n.buildNetworkResource(nw)
  287. epl := nw.Endpoints()
  288. for _, e := range epl {
  289. ei := e.Info()
  290. if ei == nil {
  291. continue
  292. }
  293. sb := ei.Sandbox()
  294. tmpID := e.ID()
  295. key := "ep-" + tmpID
  296. if sb != nil {
  297. key = sb.ContainerID()
  298. }
  299. r.Containers[key] = buildEndpointResource(tmpID, e.Name(), ei)
  300. }
  301. if !verbose {
  302. return r
  303. }
  304. services := nw.Info().Services()
  305. r.Services = make(map[string]network.ServiceInfo)
  306. for name, service := range services {
  307. tasks := []network.Task{}
  308. for _, t := range service.Tasks {
  309. tasks = append(tasks, network.Task{
  310. Name: t.Name,
  311. EndpointID: t.EndpointID,
  312. EndpointIP: t.EndpointIP,
  313. Info: t.Info,
  314. })
  315. }
  316. r.Services[name] = network.ServiceInfo{
  317. VIP: service.VIP,
  318. Ports: service.Ports,
  319. Tasks: tasks,
  320. LocalLBIndex: service.LocalLBIndex,
  321. }
  322. }
  323. return r
  324. }
  325. func buildPeerInfoResources(peers []networkdb.PeerInfo) []network.PeerInfo {
  326. peerInfo := make([]network.PeerInfo, 0, len(peers))
  327. for _, peer := range peers {
  328. peerInfo = append(peerInfo, network.PeerInfo{
  329. Name: peer.Name,
  330. IP: peer.IP,
  331. })
  332. }
  333. return peerInfo
  334. }
  335. func buildIpamResources(r *types.NetworkResource, nwInfo libnetwork.NetworkInfo) {
  336. id, opts, ipv4conf, ipv6conf := nwInfo.IpamConfig()
  337. ipv4Info, ipv6Info := nwInfo.IpamInfo()
  338. r.IPAM.Driver = id
  339. r.IPAM.Options = opts
  340. r.IPAM.Config = []network.IPAMConfig{}
  341. for _, ip4 := range ipv4conf {
  342. if ip4.PreferredPool == "" {
  343. continue
  344. }
  345. iData := network.IPAMConfig{}
  346. iData.Subnet = ip4.PreferredPool
  347. iData.IPRange = ip4.SubPool
  348. iData.Gateway = ip4.Gateway
  349. iData.AuxAddress = ip4.AuxAddresses
  350. r.IPAM.Config = append(r.IPAM.Config, iData)
  351. }
  352. if len(r.IPAM.Config) == 0 {
  353. for _, ip4Info := range ipv4Info {
  354. iData := network.IPAMConfig{}
  355. iData.Subnet = ip4Info.IPAMData.Pool.String()
  356. iData.Gateway = ip4Info.IPAMData.Gateway.IP.String()
  357. r.IPAM.Config = append(r.IPAM.Config, iData)
  358. }
  359. }
  360. hasIpv6Conf := false
  361. for _, ip6 := range ipv6conf {
  362. if ip6.PreferredPool == "" {
  363. continue
  364. }
  365. hasIpv6Conf = true
  366. iData := network.IPAMConfig{}
  367. iData.Subnet = ip6.PreferredPool
  368. iData.IPRange = ip6.SubPool
  369. iData.Gateway = ip6.Gateway
  370. iData.AuxAddress = ip6.AuxAddresses
  371. r.IPAM.Config = append(r.IPAM.Config, iData)
  372. }
  373. if !hasIpv6Conf {
  374. for _, ip6Info := range ipv6Info {
  375. if ip6Info.IPAMData.Pool == nil {
  376. continue
  377. }
  378. iData := network.IPAMConfig{}
  379. iData.Subnet = ip6Info.IPAMData.Pool.String()
  380. iData.Gateway = ip6Info.IPAMData.Gateway.String()
  381. r.IPAM.Config = append(r.IPAM.Config, iData)
  382. }
  383. }
  384. }
  385. func buildEndpointResource(id string, name string, info libnetwork.EndpointInfo) types.EndpointResource {
  386. er := types.EndpointResource{}
  387. er.EndpointID = id
  388. er.Name = name
  389. ei := info
  390. if ei == nil {
  391. return er
  392. }
  393. if iface := ei.Iface(); iface != nil {
  394. if mac := iface.MacAddress(); mac != nil {
  395. er.MacAddress = mac.String()
  396. }
  397. if ip := iface.Address(); ip != nil && len(ip.IP) > 0 {
  398. er.IPv4Address = ip.String()
  399. }
  400. if ipv6 := iface.AddressIPv6(); ipv6 != nil && len(ipv6.IP) > 0 {
  401. er.IPv6Address = ipv6.String()
  402. }
  403. }
  404. return er
  405. }
  406. func (n *networkRouter) postNetworksPrune(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  407. if err := httputils.ParseForm(r); err != nil {
  408. return err
  409. }
  410. pruneFilters, err := filters.FromParam(r.Form.Get("filters"))
  411. if err != nil {
  412. return err
  413. }
  414. pruneReport, err := n.backend.NetworksPrune(ctx, pruneFilters)
  415. if err != nil {
  416. return err
  417. }
  418. return httputils.WriteJSON(w, http.StatusOK, pruneReport)
  419. }