bridge.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package bridge
  2. import (
  3. "net"
  4. "github.com/docker/libnetwork"
  5. )
  6. const (
  7. NetworkType = "simplebridge"
  8. VethPrefix = "veth"
  9. )
  10. type Configuration struct {
  11. BridgeName string
  12. AddressIPv4 *net.IPNet
  13. FixedCIDR *net.IPNet
  14. FixedCIDRv6 *net.IPNet
  15. EnableIPv6 bool
  16. EnableIPTables bool
  17. EnableIPForwarding bool
  18. }
  19. func init() {
  20. libnetwork.RegisterNetworkType(NetworkType, Create, &Configuration{})
  21. }
  22. func Create(name string, config *Configuration) (libnetwork.Network, error) {
  23. bridgeIntfc := NewInterface(config)
  24. bridgeSetup := NewBridgeSetup(bridgeIntfc)
  25. // If the bridge interface doesn't exist, we need to start the setup steps
  26. // by creating a new device and assigning it an IPv4 address.
  27. bridgeAlreadyExists := bridgeIntfc.Exists()
  28. if !bridgeAlreadyExists {
  29. bridgeSetup.QueueStep(SetupDevice)
  30. bridgeSetup.QueueStep(SetupBridgeIPv4)
  31. }
  32. // Conditionnally queue setup steps depending on configuration values.
  33. for _, step := range []struct {
  34. Condition bool
  35. Fn SetupStep
  36. }{
  37. // Enable IPv6 on the bridge if required. We do this even for a
  38. // previously existing bridge, as it may be here from a previous
  39. // installation where IPv6 wasn't supported yet and needs to be
  40. // assigned an IPv6 link-local address.
  41. {config.EnableIPv6, SetupBridgeIPv6},
  42. // We ensure that the bridge has the expectedIPv4 and IPv6 addresses in
  43. // the case of a previously existing device.
  44. {bridgeAlreadyExists, SetupVerifyConfiguredAddresses},
  45. // Setup the bridge to allocate containers IPv4 addresses in the
  46. // specified subnet.
  47. {config.FixedCIDR != nil, SetupFixedCIDRv4},
  48. // Setup the bridge to allocate containers global IPv6 addresses in the
  49. // specified subnet.
  50. {config.FixedCIDRv6 != nil, SetupFixedCIDRv6},
  51. // Setup IPTables.
  52. {config.EnableIPTables, SetupIPTables},
  53. // Setup IP forwarding.
  54. {config.EnableIPForwarding, SetupIPForwarding},
  55. } {
  56. if step.Condition {
  57. bridgeSetup.QueueStep(step.Fn)
  58. }
  59. }
  60. // Apply the prepared list of steps, and abort at the first error.
  61. bridgeSetup.QueueStep(SetupDeviceUp)
  62. if err := bridgeSetup.Apply(); err != nil {
  63. return nil, err
  64. }
  65. return &bridgeNetwork{NetworkName: name, Config: *config}, nil
  66. }