network_routes.go 13 KB

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