create.go 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  1. package network
  2. import (
  3. "fmt"
  4. "net"
  5. "strings"
  6. "golang.org/x/net/context"
  7. "github.com/docker/docker/api/types"
  8. "github.com/docker/docker/api/types/network"
  9. "github.com/docker/docker/cli"
  10. "github.com/docker/docker/cli/command"
  11. "github.com/docker/docker/opts"
  12. runconfigopts "github.com/docker/docker/runconfig/opts"
  13. "github.com/spf13/cobra"
  14. )
  15. type createOptions struct {
  16. name string
  17. driver string
  18. driverOpts opts.MapOpts
  19. labels opts.ListOpts
  20. internal bool
  21. ipv6 bool
  22. attachable bool
  23. ipamDriver string
  24. ipamSubnet []string
  25. ipamIPRange []string
  26. ipamGateway []string
  27. ipamAux opts.MapOpts
  28. ipamOpt opts.MapOpts
  29. }
  30. func newCreateCommand(dockerCli *command.DockerCli) *cobra.Command {
  31. opts := createOptions{
  32. driverOpts: *opts.NewMapOpts(nil, nil),
  33. labels: opts.NewListOpts(opts.ValidateEnv),
  34. ipamAux: *opts.NewMapOpts(nil, nil),
  35. ipamOpt: *opts.NewMapOpts(nil, nil),
  36. }
  37. cmd := &cobra.Command{
  38. Use: "create [OPTIONS] NETWORK",
  39. Short: "Create a network",
  40. Args: cli.ExactArgs(1),
  41. RunE: func(cmd *cobra.Command, args []string) error {
  42. opts.name = args[0]
  43. return runCreate(dockerCli, opts)
  44. },
  45. }
  46. flags := cmd.Flags()
  47. flags.StringVarP(&opts.driver, "driver", "d", "bridge", "Driver to manage the Network")
  48. flags.VarP(&opts.driverOpts, "opt", "o", "Set driver specific options")
  49. flags.Var(&opts.labels, "label", "Set metadata on a network")
  50. flags.BoolVar(&opts.internal, "internal", false, "Restrict external access to the network")
  51. flags.BoolVar(&opts.ipv6, "ipv6", false, "Enable IPv6 networking")
  52. flags.BoolVar(&opts.attachable, "attachable", false, "Enable manual container attachment")
  53. flags.SetAnnotation("attachable", "version", []string{"1.25"})
  54. flags.StringVar(&opts.ipamDriver, "ipam-driver", "default", "IP Address Management Driver")
  55. flags.StringSliceVar(&opts.ipamSubnet, "subnet", []string{}, "Subnet in CIDR format that represents a network segment")
  56. flags.StringSliceVar(&opts.ipamIPRange, "ip-range", []string{}, "Allocate container ip from a sub-range")
  57. flags.StringSliceVar(&opts.ipamGateway, "gateway", []string{}, "IPv4 or IPv6 Gateway for the master subnet")
  58. flags.Var(&opts.ipamAux, "aux-address", "Auxiliary IPv4 or IPv6 addresses used by Network driver")
  59. flags.Var(&opts.ipamOpt, "ipam-opt", "Set IPAM driver specific options")
  60. return cmd
  61. }
  62. func runCreate(dockerCli *command.DockerCli, opts createOptions) error {
  63. client := dockerCli.Client()
  64. ipamCfg, err := consolidateIpam(opts.ipamSubnet, opts.ipamIPRange, opts.ipamGateway, opts.ipamAux.GetAll())
  65. if err != nil {
  66. return err
  67. }
  68. // Construct network create request body
  69. nc := types.NetworkCreate{
  70. Driver: opts.driver,
  71. Options: opts.driverOpts.GetAll(),
  72. IPAM: &network.IPAM{
  73. Driver: opts.ipamDriver,
  74. Config: ipamCfg,
  75. Options: opts.ipamOpt.GetAll(),
  76. },
  77. CheckDuplicate: true,
  78. Internal: opts.internal,
  79. EnableIPv6: opts.ipv6,
  80. Attachable: opts.attachable,
  81. Labels: runconfigopts.ConvertKVStringsToMap(opts.labels.GetAll()),
  82. }
  83. resp, err := client.NetworkCreate(context.Background(), opts.name, nc)
  84. if err != nil {
  85. return err
  86. }
  87. fmt.Fprintf(dockerCli.Out(), "%s\n", resp.ID)
  88. return nil
  89. }
  90. // Consolidates the ipam configuration as a group from different related configurations
  91. // user can configure network with multiple non-overlapping subnets and hence it is
  92. // possible to correlate the various related parameters and consolidate them.
  93. // consoidateIpam consolidates subnets, ip-ranges, gateways and auxiliary addresses into
  94. // structured ipam data.
  95. func consolidateIpam(subnets, ranges, gateways []string, auxaddrs map[string]string) ([]network.IPAMConfig, error) {
  96. if len(subnets) < len(ranges) || len(subnets) < len(gateways) {
  97. return nil, fmt.Errorf("every ip-range or gateway must have a corresponding subnet")
  98. }
  99. iData := map[string]*network.IPAMConfig{}
  100. // Populate non-overlapping subnets into consolidation map
  101. for _, s := range subnets {
  102. for k := range iData {
  103. ok1, err := subnetMatches(s, k)
  104. if err != nil {
  105. return nil, err
  106. }
  107. ok2, err := subnetMatches(k, s)
  108. if err != nil {
  109. return nil, err
  110. }
  111. if ok1 || ok2 {
  112. return nil, fmt.Errorf("multiple overlapping subnet configuration is not supported")
  113. }
  114. }
  115. iData[s] = &network.IPAMConfig{Subnet: s, AuxAddress: map[string]string{}}
  116. }
  117. // Validate and add valid ip ranges
  118. for _, r := range ranges {
  119. match := false
  120. for _, s := range subnets {
  121. ok, err := subnetMatches(s, r)
  122. if err != nil {
  123. return nil, err
  124. }
  125. if !ok {
  126. continue
  127. }
  128. if iData[s].IPRange != "" {
  129. return nil, fmt.Errorf("cannot configure multiple ranges (%s, %s) on the same subnet (%s)", r, iData[s].IPRange, s)
  130. }
  131. d := iData[s]
  132. d.IPRange = r
  133. match = true
  134. }
  135. if !match {
  136. return nil, fmt.Errorf("no matching subnet for range %s", r)
  137. }
  138. }
  139. // Validate and add valid gateways
  140. for _, g := range gateways {
  141. match := false
  142. for _, s := range subnets {
  143. ok, err := subnetMatches(s, g)
  144. if err != nil {
  145. return nil, err
  146. }
  147. if !ok {
  148. continue
  149. }
  150. if iData[s].Gateway != "" {
  151. return nil, fmt.Errorf("cannot configure multiple gateways (%s, %s) for the same subnet (%s)", g, iData[s].Gateway, s)
  152. }
  153. d := iData[s]
  154. d.Gateway = g
  155. match = true
  156. }
  157. if !match {
  158. return nil, fmt.Errorf("no matching subnet for gateway %s", g)
  159. }
  160. }
  161. // Validate and add aux-addresses
  162. for key, aa := range auxaddrs {
  163. match := false
  164. for _, s := range subnets {
  165. ok, err := subnetMatches(s, aa)
  166. if err != nil {
  167. return nil, err
  168. }
  169. if !ok {
  170. continue
  171. }
  172. iData[s].AuxAddress[key] = aa
  173. match = true
  174. }
  175. if !match {
  176. return nil, fmt.Errorf("no matching subnet for aux-address %s", aa)
  177. }
  178. }
  179. idl := []network.IPAMConfig{}
  180. for _, v := range iData {
  181. idl = append(idl, *v)
  182. }
  183. return idl, nil
  184. }
  185. func subnetMatches(subnet, data string) (bool, error) {
  186. var (
  187. ip net.IP
  188. )
  189. _, s, err := net.ParseCIDR(subnet)
  190. if err != nil {
  191. return false, fmt.Errorf("Invalid subnet %s : %v", s, err)
  192. }
  193. if strings.Contains(data, "/") {
  194. ip, _, err = net.ParseCIDR(data)
  195. if err != nil {
  196. return false, fmt.Errorf("Invalid cidr %s : %v", data, err)
  197. }
  198. } else {
  199. ip = net.ParseIP(data)
  200. }
  201. return s.Contains(ip), nil
  202. }