network_routes.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  1. package network // import "github.com/docker/docker/api/server/router/network"
  2. import (
  3. "context"
  4. "net/http"
  5. "strconv"
  6. "strings"
  7. "github.com/docker/docker/api/server/httputils"
  8. "github.com/docker/docker/api/types"
  9. "github.com/docker/docker/api/types/backend"
  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/docker/libnetwork"
  15. "github.com/docker/docker/libnetwork/scope"
  16. "github.com/pkg/errors"
  17. )
  18. func (n *networkRouter) getNetworksList(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  19. if err := httputils.ParseForm(r); err != nil {
  20. return err
  21. }
  22. filter, err := filters.FromJSON(r.Form.Get("filters"))
  23. if err != nil {
  24. return err
  25. }
  26. if err := network.ValidateFilters(filter); err != nil {
  27. return err
  28. }
  29. var list []types.NetworkResource
  30. nr, err := n.cluster.GetNetworks(filter)
  31. if err == nil {
  32. list = nr
  33. }
  34. // Combine the network list returned by Docker daemon if it is not already
  35. // returned by the cluster manager
  36. localNetworks, err := n.backend.GetNetworks(filter, backend.NetworkListConfig{Detailed: versions.LessThan(httputils.VersionFromContext(ctx), "1.28")})
  37. if err != nil {
  38. return err
  39. }
  40. var idx map[string]bool
  41. if len(list) > 0 {
  42. idx = make(map[string]bool, len(list))
  43. for _, n := range list {
  44. idx[n.ID] = true
  45. }
  46. }
  47. for _, n := range localNetworks {
  48. if idx[n.ID] {
  49. continue
  50. }
  51. list = append(list, n)
  52. }
  53. if list == nil {
  54. list = []types.NetworkResource{}
  55. }
  56. return httputils.WriteJSON(w, http.StatusOK, list)
  57. }
  58. type invalidRequestError struct {
  59. cause error
  60. }
  61. func (e invalidRequestError) Error() string {
  62. return e.cause.Error()
  63. }
  64. func (e invalidRequestError) InvalidParameter() {}
  65. type ambigousResultsError string
  66. func (e ambigousResultsError) Error() string {
  67. return "network " + string(e) + " is ambiguous"
  68. }
  69. func (ambigousResultsError) InvalidParameter() {}
  70. func (n *networkRouter) getNetwork(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  71. if err := httputils.ParseForm(r); err != nil {
  72. return err
  73. }
  74. term := vars["id"]
  75. var (
  76. verbose bool
  77. err error
  78. )
  79. if v := r.URL.Query().Get("verbose"); v != "" {
  80. if verbose, err = strconv.ParseBool(v); err != nil {
  81. return errors.Wrapf(invalidRequestError{err}, "invalid value for verbose: %s", v)
  82. }
  83. }
  84. networkScope := r.URL.Query().Get("scope")
  85. // In case multiple networks have duplicate names, return error.
  86. // TODO (yongtang): should we wrap with version here for backward compatibility?
  87. // First find based on full ID, return immediately once one is found.
  88. // If a network appears both in swarm and local, assume it is in local first
  89. // For full name and partial ID, save the result first, and process later
  90. // in case multiple records was found based on the same term
  91. listByFullName := map[string]types.NetworkResource{}
  92. listByPartialID := map[string]types.NetworkResource{}
  93. // TODO(@cpuguy83): All this logic for figuring out which network to return does not belong here
  94. // Instead there should be a backend function to just get one network.
  95. filter := filters.NewArgs(filters.Arg("idOrName", term))
  96. if networkScope != "" {
  97. filter.Add("scope", networkScope)
  98. }
  99. networks, _ := n.backend.GetNetworks(filter, backend.NetworkListConfig{Detailed: true, Verbose: verbose})
  100. for _, nw := range networks {
  101. if nw.ID == term {
  102. return httputils.WriteJSON(w, http.StatusOK, nw)
  103. }
  104. if nw.Name == term {
  105. // No need to check the ID collision here as we are still in
  106. // local scope and the network ID is unique in this scope.
  107. listByFullName[nw.ID] = nw
  108. }
  109. if strings.HasPrefix(nw.ID, term) {
  110. // No need to check the ID collision here as we are still in
  111. // local scope and the network ID is unique in this scope.
  112. listByPartialID[nw.ID] = nw
  113. }
  114. }
  115. nwk, err := n.cluster.GetNetwork(term)
  116. if err == nil {
  117. // If the get network is passed with a specific network ID / partial network ID
  118. // or if the get network was passed with a network name and scope as swarm
  119. // return the network. Skipped using isMatchingScope because it is true if the scope
  120. // is not set which would be case if the client API v1.30
  121. if strings.HasPrefix(nwk.ID, term) || networkScope == scope.Swarm {
  122. // If we have a previous match "backend", return it, we need verbose when enabled
  123. // ex: overlay/partial_ID or name/swarm_scope
  124. if nwv, ok := listByPartialID[nwk.ID]; ok {
  125. nwk = nwv
  126. } else if nwv, ok := listByFullName[nwk.ID]; ok {
  127. nwk = nwv
  128. }
  129. return httputils.WriteJSON(w, http.StatusOK, nwk)
  130. }
  131. }
  132. networks, _ = n.cluster.GetNetworks(filter)
  133. for _, nw := range networks {
  134. if nw.ID == term {
  135. return httputils.WriteJSON(w, http.StatusOK, nw)
  136. }
  137. if nw.Name == term {
  138. // Check the ID collision as we are in swarm scope here, and
  139. // the map (of the listByFullName) may have already had a
  140. // network with the same ID (from local scope previously)
  141. if _, ok := listByFullName[nw.ID]; !ok {
  142. listByFullName[nw.ID] = nw
  143. }
  144. }
  145. if strings.HasPrefix(nw.ID, term) {
  146. // Check the ID collision as we are in swarm scope here, and
  147. // the map (of the listByPartialID) may have already had a
  148. // network with the same ID (from local scope previously)
  149. if _, ok := listByPartialID[nw.ID]; !ok {
  150. listByPartialID[nw.ID] = nw
  151. }
  152. }
  153. }
  154. // Find based on full name, returns true only if no duplicates
  155. if len(listByFullName) == 1 {
  156. for _, v := range listByFullName {
  157. return httputils.WriteJSON(w, http.StatusOK, v)
  158. }
  159. }
  160. if len(listByFullName) > 1 {
  161. return errors.Wrapf(ambigousResultsError(term), "%d matches found based on name", len(listByFullName))
  162. }
  163. // Find based on partial ID, returns true only if no duplicates
  164. if len(listByPartialID) == 1 {
  165. for _, v := range listByPartialID {
  166. return httputils.WriteJSON(w, http.StatusOK, v)
  167. }
  168. }
  169. if len(listByPartialID) > 1 {
  170. return errors.Wrapf(ambigousResultsError(term), "%d matches found based on ID prefix", len(listByPartialID))
  171. }
  172. return libnetwork.ErrNoSuchNetwork(term)
  173. }
  174. func (n *networkRouter) postNetworkCreate(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  175. if err := httputils.ParseForm(r); err != nil {
  176. return err
  177. }
  178. var create types.NetworkCreateRequest
  179. if err := httputils.ReadJSON(r, &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. // For a Swarm-scoped network, this call to backend.CreateNetwork is used to
  186. // validate the configuration. The network will not be created but, if the
  187. // configuration is valid, ManagerRedirectError will be returned and handled
  188. // below.
  189. nw, err := n.backend.CreateNetwork(create)
  190. if err != nil {
  191. if _, ok := err.(libnetwork.ManagerRedirectError); !ok {
  192. return err
  193. }
  194. id, err := n.cluster.CreateNetwork(create)
  195. if err != nil {
  196. return err
  197. }
  198. nw = &types.NetworkCreateResponse{
  199. ID: id,
  200. }
  201. }
  202. return httputils.WriteJSON(w, http.StatusCreated, nw)
  203. }
  204. func (n *networkRouter) postNetworkConnect(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  205. if err := httputils.ParseForm(r); err != nil {
  206. return err
  207. }
  208. var connect types.NetworkConnect
  209. if err := httputils.ReadJSON(r, &connect); err != nil {
  210. return err
  211. }
  212. // Unlike other operations, we does not check ambiguity of the name/ID here.
  213. // The reason is that, In case of attachable network in swarm scope, the actual local network
  214. // may not be available at the time. At the same time, inside daemon `ConnectContainerToNetwork`
  215. // does the ambiguity check anyway. Therefore, passing the name to daemon would be enough.
  216. return n.backend.ConnectContainerToNetwork(connect.Container, vars["id"], connect.EndpointConfig)
  217. }
  218. func (n *networkRouter) postNetworkDisconnect(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  219. if err := httputils.ParseForm(r); err != nil {
  220. return err
  221. }
  222. var disconnect types.NetworkDisconnect
  223. if err := httputils.ReadJSON(r, &disconnect); err != nil {
  224. return err
  225. }
  226. return n.backend.DisconnectContainerFromNetwork(disconnect.Container, vars["id"], disconnect.Force)
  227. }
  228. func (n *networkRouter) deleteNetwork(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  229. if err := httputils.ParseForm(r); err != nil {
  230. return err
  231. }
  232. nw, err := n.findUniqueNetwork(vars["id"])
  233. if err != nil {
  234. return err
  235. }
  236. if nw.Scope == "swarm" {
  237. if err = n.cluster.RemoveNetwork(nw.ID); err != nil {
  238. return err
  239. }
  240. } else {
  241. if err := n.backend.DeleteNetwork(nw.ID); err != nil {
  242. return err
  243. }
  244. }
  245. w.WriteHeader(http.StatusNoContent)
  246. return nil
  247. }
  248. func (n *networkRouter) postNetworksPrune(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  249. if err := httputils.ParseForm(r); err != nil {
  250. return err
  251. }
  252. pruneFilters, err := filters.FromJSON(r.Form.Get("filters"))
  253. if err != nil {
  254. return err
  255. }
  256. pruneReport, err := n.backend.NetworksPrune(ctx, pruneFilters)
  257. if err != nil {
  258. return err
  259. }
  260. return httputils.WriteJSON(w, http.StatusOK, pruneReport)
  261. }
  262. // findUniqueNetwork will search network across different scopes (both local and swarm).
  263. // NOTE: This findUniqueNetwork is different from FindNetwork in the daemon.
  264. // In case multiple networks have duplicate names, return error.
  265. // First find based on full ID, return immediately once one is found.
  266. // If a network appears both in swarm and local, assume it is in local first
  267. // For full name and partial ID, save the result first, and process later
  268. // in case multiple records was found based on the same term
  269. // TODO (yongtang): should we wrap with version here for backward compatibility?
  270. func (n *networkRouter) findUniqueNetwork(term string) (types.NetworkResource, error) {
  271. listByFullName := map[string]types.NetworkResource{}
  272. listByPartialID := map[string]types.NetworkResource{}
  273. filter := filters.NewArgs(filters.Arg("idOrName", term))
  274. networks, _ := n.backend.GetNetworks(filter, backend.NetworkListConfig{Detailed: true})
  275. for _, nw := range networks {
  276. if nw.ID == term {
  277. return nw, nil
  278. }
  279. if nw.Name == term && !nw.Ingress {
  280. // No need to check the ID collision here as we are still in
  281. // local scope and the network ID is unique in this scope.
  282. listByFullName[nw.ID] = nw
  283. }
  284. if strings.HasPrefix(nw.ID, term) {
  285. // No need to check the ID collision here as we are still in
  286. // local scope and the network ID is unique in this scope.
  287. listByPartialID[nw.ID] = nw
  288. }
  289. }
  290. networks, _ = n.cluster.GetNetworks(filter)
  291. for _, nw := range networks {
  292. if nw.ID == term {
  293. return nw, nil
  294. }
  295. if nw.Name == term {
  296. // Check the ID collision as we are in swarm scope here, and
  297. // the map (of the listByFullName) may have already had a
  298. // network with the same ID (from local scope previously)
  299. if _, ok := listByFullName[nw.ID]; !ok {
  300. listByFullName[nw.ID] = nw
  301. }
  302. }
  303. if strings.HasPrefix(nw.ID, term) {
  304. // Check the ID collision as we are in swarm scope here, and
  305. // the map (of the listByPartialID) may have already had a
  306. // network with the same ID (from local scope previously)
  307. if _, ok := listByPartialID[nw.ID]; !ok {
  308. listByPartialID[nw.ID] = nw
  309. }
  310. }
  311. }
  312. // Find based on full name, returns true only if no duplicates
  313. if len(listByFullName) == 1 {
  314. for _, v := range listByFullName {
  315. return v, nil
  316. }
  317. }
  318. if len(listByFullName) > 1 {
  319. return types.NetworkResource{}, errdefs.InvalidParameter(errors.Errorf("network %s is ambiguous (%d matches found based on name)", term, len(listByFullName)))
  320. }
  321. // Find based on partial ID, returns true only if no duplicates
  322. if len(listByPartialID) == 1 {
  323. for _, v := range listByPartialID {
  324. return v, nil
  325. }
  326. }
  327. if len(listByPartialID) > 1 {
  328. return types.NetworkResource{}, errdefs.InvalidParameter(errors.Errorf("network %s is ambiguous (%d matches found based on ID prefix)", term, len(listByPartialID)))
  329. }
  330. return types.NetworkResource{}, errdefs.NotFound(libnetwork.ErrNoSuchNetwork(term))
  331. }