network_routes.go 12 KB

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