network_routes.go 12 KB

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