bridge.go 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254
  1. // +build solaris
  2. package bridge
  3. import (
  4. "bufio"
  5. "errors"
  6. "fmt"
  7. "net"
  8. "os"
  9. "os/exec"
  10. "strconv"
  11. "strings"
  12. "sync"
  13. "github.com/Sirupsen/logrus"
  14. "github.com/docker/libnetwork/datastore"
  15. "github.com/docker/libnetwork/discoverapi"
  16. "github.com/docker/libnetwork/driverapi"
  17. "github.com/docker/libnetwork/iptables"
  18. "github.com/docker/libnetwork/netlabel"
  19. "github.com/docker/libnetwork/netutils"
  20. "github.com/docker/libnetwork/options"
  21. "github.com/docker/libnetwork/portmapper"
  22. "github.com/docker/libnetwork/types"
  23. )
  24. const (
  25. networkType = "bridge"
  26. // DefaultBridgeName is the default name for the bridge interface managed
  27. // by the driver when unspecified by the caller.
  28. DefaultBridgeName = "docker0"
  29. // BridgeName label for bridge driver
  30. BridgeName = "com.docker.network.bridge.name"
  31. // EnableIPMasquerade label for bridge driver
  32. EnableIPMasquerade = "com.docker.network.bridge.enable_ip_masquerade"
  33. // EnableICC label
  34. EnableICC = "com.docker.network.bridge.enable_icc"
  35. // DefaultBindingIP label
  36. DefaultBindingIP = "com.docker.network.bridge.host_binding_ipv4"
  37. // DefaultBridge label
  38. DefaultBridge = "com.docker.network.bridge.default_bridge"
  39. // DefaultGatewayV4AuxKey represents the default-gateway configured by the user
  40. DefaultGatewayV4AuxKey = "DefaultGatewayIPv4"
  41. // DefaultGatewayV6AuxKey represents the ipv6 default-gateway configured by the user
  42. DefaultGatewayV6AuxKey = "DefaultGatewayIPv6"
  43. )
  44. // configuration info for the "bridge" driver.
  45. type configuration struct {
  46. EnableIPForwarding bool
  47. EnableIPTables bool
  48. EnableUserlandProxy bool
  49. }
  50. // networkConfiguration for network specific configuration
  51. type networkConfiguration struct {
  52. ID string
  53. BridgeName string
  54. BridgeNameInternal string
  55. EnableIPv6 bool
  56. EnableIPMasquerade bool
  57. EnableICC bool
  58. Mtu int
  59. DefaultBindingIntf string
  60. DefaultBindingIP net.IP
  61. DefaultBridge bool
  62. // Internal fields set after ipam data parsing
  63. AddressIPv4 *net.IPNet
  64. AddressIPv6 *net.IPNet
  65. DefaultGatewayIPv4 net.IP
  66. DefaultGatewayIPv6 net.IP
  67. dbIndex uint64
  68. dbExists bool
  69. Internal bool
  70. }
  71. // endpointConfiguration represents the user specified configuration for the sandbox endpoint
  72. type endpointConfiguration struct {
  73. MacAddress net.HardwareAddr
  74. PortBindings []types.PortBinding
  75. ExposedPorts []types.TransportPort
  76. }
  77. // containerConfiguration represents the user specified configuration for a container
  78. type containerConfiguration struct {
  79. ParentEndpoints []string
  80. ChildEndpoints []string
  81. }
  82. // cnnectivityConfiguration represents the user specified configuration regarding the external connectivity
  83. type connectivityConfiguration struct {
  84. PortBindings []types.PortBinding
  85. ExposedPorts []types.TransportPort
  86. }
  87. type bridgeEndpoint struct {
  88. id string
  89. nid string
  90. srcName string
  91. addr *net.IPNet
  92. addrv6 *net.IPNet
  93. macAddress net.HardwareAddr
  94. config *endpointConfiguration // User specified parameters
  95. containerConfig *containerConfiguration
  96. extConnConfig *connectivityConfiguration
  97. portMapping []types.PortBinding // Operation port bindings
  98. dbIndex uint64
  99. dbExists bool
  100. }
  101. type bridgeInterface struct {
  102. bridgeIPv4 *net.IPNet
  103. bridgeIPv6 *net.IPNet
  104. gatewayIPv4 net.IP
  105. gatewayIPv6 net.IP
  106. }
  107. type bridgeNetwork struct {
  108. id string
  109. bridge *bridgeInterface
  110. config *networkConfiguration
  111. endpoints map[string]*bridgeEndpoint // key: endpoint id
  112. portMapper *portmapper.PortMapper
  113. driver *driver // The network's driver
  114. sync.Mutex
  115. }
  116. type driver struct {
  117. config *configuration
  118. network *bridgeNetwork
  119. natChain *iptables.ChainInfo
  120. filterChain *iptables.ChainInfo
  121. isolationChain *iptables.ChainInfo
  122. networks map[string]*bridgeNetwork
  123. store datastore.DataStore
  124. sync.Mutex
  125. defrouteIP net.IP
  126. }
  127. // New constructs a new bridge driver
  128. func newDriver() *driver {
  129. return &driver{networks: map[string]*bridgeNetwork{}}
  130. }
  131. // Init registers a new instance of bridge driver
  132. func Init(dc driverapi.DriverCallback, config map[string]interface{}) error {
  133. d := newDriver()
  134. if err := d.configure(config); err != nil {
  135. return err
  136. }
  137. c := driverapi.Capability{
  138. DataScope: datastore.LocalScope,
  139. }
  140. return dc.RegisterDriver(networkType, d, c)
  141. }
  142. func (d *driver) NetworkAllocate(id string, option map[string]string, ipV4Data, ipV6Data []driverapi.IPAMData) (map[string]string, error) {
  143. return nil, types.NotImplementedErrorf("not implemented")
  144. }
  145. func (d *driver) NetworkFree(id string) error {
  146. return types.NotImplementedErrorf("not implemented")
  147. }
  148. func (d *driver) EventNotify(etype driverapi.EventType, nid, tableName, key string, value []byte) {
  149. }
  150. func (d *driver) CreateNetwork(id string, option map[string]interface{}, nInfo driverapi.NetworkInfo, ipV4Data, ipV6Data []driverapi.IPAMData) error {
  151. if len(ipV4Data) == 0 || ipV4Data[0].Pool.String() == "0.0.0.0/0" {
  152. return types.BadRequestErrorf("ipv4 pool is empty")
  153. }
  154. // Sanity checks
  155. d.Lock()
  156. if _, ok := d.networks[id]; ok {
  157. d.Unlock()
  158. return types.ForbiddenErrorf("network %s exists", id)
  159. }
  160. d.Unlock()
  161. // Parse and validate the config. It should not conflict with existing networks' config
  162. config, err := parseNetworkOptions(d, id, option)
  163. if err != nil {
  164. return err
  165. }
  166. err = config.processIPAM(id, ipV4Data, ipV6Data)
  167. if err != nil {
  168. return err
  169. }
  170. if err = d.createNetwork(config); err != nil {
  171. return err
  172. }
  173. return d.storeUpdate(config)
  174. }
  175. func newInterface(config *networkConfiguration) *bridgeInterface {
  176. i := &bridgeInterface{}
  177. i.bridgeIPv4 = config.AddressIPv4
  178. i.gatewayIPv4 = config.AddressIPv4.IP
  179. if config.BridgeName == "" {
  180. config.BridgeName = DefaultBridgeName
  181. }
  182. return i
  183. }
  184. // This function prunes the pf.conf for the firewall
  185. // that enable the service successfully.
  186. func fixPFConf() error {
  187. conf := "/etc/firewall/pf.conf"
  188. f, err := os.Open("/etc/firewall/pf.conf")
  189. if err != nil {
  190. return fmt.Errorf("cannot open %s: %v", conf, err)
  191. }
  192. defer f.Close()
  193. // Look for line beginning with "REMOVE THIS LINE"
  194. modify := false
  195. lines := []string{}
  196. scanner := bufio.NewScanner(f)
  197. for scanner.Scan() {
  198. l := scanner.Text()
  199. if strings.Contains(l, "REMOVE THIS LINE") {
  200. modify = true
  201. continue
  202. }
  203. lines = append(lines, fmt.Sprintf("%s\n", l))
  204. }
  205. if err = scanner.Err(); err != nil {
  206. return fmt.Errorf("cannot open %s: %v", conf, err)
  207. }
  208. // No changes needed to fix pf.conf
  209. if !modify {
  210. return nil
  211. }
  212. // Write back the file removing the line found above
  213. tmpname := "/etc/firewall/pf.conf.tmp." + strconv.Itoa(os.Getpid())
  214. tmp, err := os.OpenFile(tmpname,
  215. os.O_CREATE|os.O_TRUNC|os.O_WRONLY|os.O_APPEND, 0644)
  216. if err != nil {
  217. return fmt.Errorf("cannot open %s: %v", tmpname, err)
  218. }
  219. defer tmp.Close()
  220. for _, l := range lines {
  221. _, err = tmp.WriteString(l)
  222. if err != nil {
  223. return fmt.Errorf("cannot write to %s: %v",
  224. tmpname, err)
  225. }
  226. }
  227. if err = tmp.Sync(); err != nil {
  228. return fmt.Errorf("cannot sync %s: %v", tmpname, err)
  229. }
  230. if err = os.Rename(tmpname, conf); err != nil {
  231. return fmt.Errorf("cannot rename %s to %s: %v",
  232. tmpname, conf, err)
  233. }
  234. return nil
  235. }
  236. func (d *driver) initFirewall() error {
  237. out, err := exec.Command("/usr/bin/svcs", "-Ho", "state",
  238. "firewall").Output()
  239. if err != nil {
  240. return fmt.Errorf("cannot check firewall state: %v", err)
  241. }
  242. state := strings.TrimSpace(string(out))
  243. if state != "online" {
  244. if state != "disabled" {
  245. return fmt.Errorf("firewall service is in %s state. "+
  246. "please enable service manually.", state)
  247. }
  248. if err = fixPFConf(); err != nil {
  249. return fmt.Errorf("cannot verify pf.conf: %v", err)
  250. }
  251. err = exec.Command("/usr/sbin/svcadm", "enable", "-ts",
  252. "firewall").Run()
  253. if err != nil {
  254. return fmt.Errorf("cannot enable firewall service: %v", err)
  255. }
  256. }
  257. out, err = exec.Command("/usr/sbin/pfctl", "-sr").Output()
  258. if err != nil {
  259. return fmt.Errorf("failed to list firewall rules: %v", err)
  260. }
  261. if strings.Contains(string(out), "anchor \"_auto/docker/*\" all") {
  262. return nil
  263. }
  264. pfctlCmd := "(/usr/sbin/pfctl -sr; " +
  265. "/usr/bin/echo \"anchor \\\"_auto/docker/*\\\"\") |" +
  266. "/usr/sbin/pfctl -f -"
  267. err = exec.Command("/usr/bin/bash", "-c", pfctlCmd).Run()
  268. if err != nil {
  269. return fmt.Errorf("failed to add docker firewall rules: %v", err)
  270. }
  271. return nil
  272. }
  273. func (d *driver) initRouting() error {
  274. err := exec.Command("/usr/sbin/ipadm", "set-prop", "-t",
  275. "-p", "forwarding=on", "ipv4").Run()
  276. if err != nil {
  277. return fmt.Errorf("cannot switch-on IP forwarding: %v", err)
  278. }
  279. routeCmd := "/usr/sbin/ipadm show-addr -p -o addr " +
  280. "`/usr/sbin/route get default | /usr/bin/grep interface | " +
  281. "/usr/bin/awk '{print $2}'`"
  282. out, err := exec.Command("/usr/bin/bash", "-c", routeCmd).Output()
  283. if err != nil {
  284. return fmt.Errorf("cannot get default route: %v", err)
  285. }
  286. defroute := strings.SplitN(string(out), "/", 2)
  287. d.defrouteIP = net.ParseIP(defroute[0])
  288. if d.defrouteIP == nil {
  289. return &ErrNoIPAddr{}
  290. }
  291. return nil
  292. }
  293. func (d *driver) configure(option map[string]interface{}) error {
  294. var err error
  295. if err = d.initFirewall(); err != nil {
  296. return fmt.Errorf("failed to configure firewall: %v", err)
  297. }
  298. if err = d.initRouting(); err != nil {
  299. return fmt.Errorf("failed to configure routing: %v", err)
  300. }
  301. if err = d.initStore(option); err != nil {
  302. return fmt.Errorf("failed to initialize datastore: %v", err)
  303. }
  304. return nil
  305. }
  306. func (d *driver) getNetwork(id string) (*bridgeNetwork, error) {
  307. d.Lock()
  308. defer d.Unlock()
  309. if id == "" {
  310. return nil, types.BadRequestErrorf("invalid network id: %s", id)
  311. }
  312. if nw, ok := d.networks[id]; ok {
  313. return nw, nil
  314. }
  315. return nil, types.NotFoundErrorf("network not found: %s", id)
  316. }
  317. // Return a slice of networks over which caller can iterate safely
  318. func (d *driver) getNetworks() []*bridgeNetwork {
  319. d.Lock()
  320. defer d.Unlock()
  321. ls := make([]*bridgeNetwork, 0, len(d.networks))
  322. for _, nw := range d.networks {
  323. ls = append(ls, nw)
  324. }
  325. return ls
  326. }
  327. func bridgeSetup(config *networkConfiguration) error {
  328. var err error
  329. var bindingIntf string
  330. bridgeName := config.BridgeName
  331. gwName := fmt.Sprintf("%s_gw0", bridgeName)
  332. gwIP := config.AddressIPv4.String()
  333. if config.DefaultBindingIP == nil {
  334. // Default to net0 if bindingIP is not provided.
  335. bindingIntf = "net0"
  336. } else {
  337. ipadmCmd := "/usr/sbin/ipadm show-addr -p -o addrobj,addr |" +
  338. "/usr/bin/grep " + config.DefaultBindingIP.String()
  339. out, err := exec.Command("/usr/bin/bash", "-c", ipadmCmd).Output()
  340. if err != nil {
  341. logrus.Warn("cannot find binding interface")
  342. return err
  343. }
  344. bindingIntf = strings.SplitN(string(out), "/", 2)[0]
  345. if bindingIntf == "" {
  346. logrus.Warnf("cannot parse binding interface %s", string(out))
  347. return &ErrNoIPAddr{}
  348. }
  349. }
  350. config.DefaultBindingIntf = bindingIntf
  351. err = exec.Command("/usr/sbin/dladm", "create-etherstub",
  352. "-t", config.BridgeNameInternal).Run()
  353. if err != nil {
  354. logrus.Warnf("cannot create etherstub %s: %+v", config.BridgeNameInternal, err)
  355. return err
  356. }
  357. err = exec.Command("/usr/sbin/dladm", "create-vnic",
  358. "-t", "-l", config.BridgeNameInternal, gwName).Run()
  359. if err != nil {
  360. logrus.Warnf("cannot create vnic %s", gwName)
  361. return err
  362. }
  363. err = exec.Command("/usr/sbin/ifconfig", gwName,
  364. "plumb", gwIP, "up").Run()
  365. if err != nil {
  366. logrus.Warnf("cannot create gateway interface %s on %s",
  367. gwIP, gwName)
  368. return err
  369. }
  370. tableName := "bridge_nw_subnets"
  371. pfAnchor := fmt.Sprintf("_auto/docker/%s", tableName)
  372. err = exec.Command("/usr/sbin/pfctl", "-a", pfAnchor, "-t", tableName, "-T", "add", gwIP).Run()
  373. if err != nil {
  374. logrus.Warnf("cannot add bridge network '%s' to PF table", bridgeName)
  375. }
  376. pfCmd := fmt.Sprintf(
  377. "/usr/bin/echo \"pass out on %s from %s:network to any nat-to (%s)\n"+
  378. "block in quick from { <%s>, ! %s } to %s\" |"+
  379. "/usr/sbin/pfctl -a _auto/docker/%s -f -",
  380. bindingIntf, gwName, bindingIntf,
  381. tableName, gwIP, gwIP,
  382. bridgeName)
  383. err = exec.Command("/usr/bin/bash", "-c", pfCmd).Run()
  384. if err != nil {
  385. logrus.Warnf("cannot add pf rule using: %s", pfCmd)
  386. return err
  387. }
  388. return nil
  389. }
  390. func bridgeCleanup(config *networkConfiguration, logErr bool) {
  391. var err error
  392. bridgeName := config.BridgeName
  393. tableName := "bridge_nw_subnets"
  394. gwName := fmt.Sprintf("%s_gw0", bridgeName)
  395. gwIP := config.AddressIPv4.String()
  396. pfAnchor := fmt.Sprintf("_auto/docker/%s", bridgeName)
  397. tableAnchor := fmt.Sprintf("_auto/docker/%s", tableName)
  398. err = exec.Command("/usr/sbin/pfctl", "-a", pfAnchor, "-F", "all").Run()
  399. if err != nil && logErr {
  400. logrus.Warn("cannot flush firewall rules")
  401. }
  402. err = exec.Command("/usr/sbin/ifconfig", gwName, "unplumb").Run()
  403. if err != nil && logErr {
  404. logrus.Warn("cannot remove gateway interface")
  405. }
  406. err = exec.Command("/usr/sbin/dladm", "delete-vnic",
  407. "-t", gwName).Run()
  408. if err != nil && logErr {
  409. logrus.Warn("cannot delete vnic")
  410. }
  411. err = exec.Command("/usr/sbin/dladm", "delete-etherstub",
  412. "-t", config.BridgeNameInternal).Run()
  413. if err != nil && logErr {
  414. logrus.Warn("cannot delete etherstub")
  415. }
  416. err = exec.Command("/usr/sbin/pfctl", "-a", tableAnchor, "-t", tableName, "-T", "delete", gwIP).Run()
  417. if err != nil && logErr {
  418. logrus.Warnf("cannot remove bridge network '%s' from PF table", bridgeName)
  419. }
  420. }
  421. func (d *driver) createNetwork(config *networkConfiguration) error {
  422. var err error
  423. logrus.Infof("Creating bridge network: %s %s %s", config.ID,
  424. config.BridgeName, config.AddressIPv4)
  425. networkList := d.getNetworks()
  426. for i, nw := range networkList {
  427. nw.Lock()
  428. nwConfig := nw.config
  429. nw.Unlock()
  430. if err := nwConfig.Conflicts(config); err != nil {
  431. if config.DefaultBridge {
  432. // We encountered and identified a stale default network
  433. // We must delete it as libnetwork is the source of thruth
  434. // The default network being created must be the only one
  435. // This can happen only from docker 1.12 on ward
  436. logrus.Infof("Removing stale default bridge network %s (%s)", nwConfig.ID, nwConfig.BridgeName)
  437. if err := d.DeleteNetwork(nwConfig.ID); err != nil {
  438. logrus.Warnf("Failed to remove stale default network: %s (%s): %v. Will remove from store.", nwConfig.ID, nwConfig.BridgeName, err)
  439. d.storeDelete(nwConfig)
  440. }
  441. networkList = append(networkList[:i], networkList[i+1:]...)
  442. } else {
  443. return types.ForbiddenErrorf(
  444. "cannot create network %s (%s): "+
  445. "conflicts with network %s (%s): %s",
  446. nwConfig.BridgeName, config.ID, nw.id,
  447. nw.config.BridgeName, err.Error())
  448. }
  449. }
  450. }
  451. if config.DefaultBindingIP == nil ||
  452. config.DefaultBindingIP.IsUnspecified() {
  453. config.DefaultBindingIP = d.defrouteIP
  454. }
  455. // Create and set network handler in driver
  456. network := &bridgeNetwork{
  457. id: config.ID,
  458. endpoints: make(map[string]*bridgeEndpoint),
  459. config: config,
  460. portMapper: portmapper.New(""),
  461. driver: d,
  462. }
  463. d.Lock()
  464. d.networks[config.ID] = network
  465. d.Unlock()
  466. // On failure make sure to reset driver network handler to nil
  467. defer func() {
  468. if err != nil {
  469. d.Lock()
  470. delete(d.networks, config.ID)
  471. d.Unlock()
  472. }
  473. }()
  474. // Create or retrieve the bridge L3 interface
  475. bridgeIface := newInterface(config)
  476. network.bridge = bridgeIface
  477. // Verify the network configuration does not conflict with previously installed
  478. // networks. This step is needed now because driver might have now set the bridge
  479. // name on this config struct. And because we need to check for possible address
  480. // conflicts, so we need to check against operational networks.
  481. if err = config.conflictsWithNetworks(config.ID, networkList); err != nil {
  482. return err
  483. }
  484. // We only attempt to create the bridge when the requested device name is
  485. // the default one.
  486. if config.BridgeName != DefaultBridgeName && config.DefaultBridge {
  487. return NonDefaultBridgeExistError(config.BridgeName)
  488. }
  489. bridgeCleanup(config, false)
  490. err = bridgeSetup(config)
  491. if err != nil {
  492. return err
  493. }
  494. return nil
  495. }
  496. func (d *driver) DeleteNetwork(nid string) error {
  497. var err error
  498. // Get network handler and remove it from driver
  499. d.Lock()
  500. n, ok := d.networks[nid]
  501. d.Unlock()
  502. if !ok {
  503. return types.InternalMaskableErrorf("network %s does not exist", nid)
  504. }
  505. d.Lock()
  506. delete(d.networks, nid)
  507. d.Unlock()
  508. // On failure set network handler back in driver, but
  509. // only if is not already taken over by some other thread
  510. defer func() {
  511. if err != nil {
  512. d.Lock()
  513. if _, ok := d.networks[nid]; !ok {
  514. d.networks[nid] = n
  515. }
  516. d.Unlock()
  517. }
  518. }()
  519. // Sanity check
  520. if n == nil {
  521. err = driverapi.ErrNoNetwork(nid)
  522. return err
  523. }
  524. // Cannot remove network if endpoints are still present
  525. if len(n.endpoints) != 0 {
  526. err = ActiveEndpointsError(n.id)
  527. return err
  528. }
  529. bridgeCleanup(n.config, true)
  530. logrus.Infof("Deleting bridge network: %s", nid[:12])
  531. return d.storeDelete(n.config)
  532. }
  533. func (d *driver) CreateEndpoint(nid, eid string, ifInfo driverapi.InterfaceInfo, epOptions map[string]interface{}) error {
  534. if ifInfo == nil {
  535. return errors.New("invalid interface passed")
  536. }
  537. // Get the network handler and make sure it exists
  538. d.Lock()
  539. n, ok := d.networks[nid]
  540. d.Unlock()
  541. if !ok {
  542. return types.NotFoundErrorf("network %s does not exist", nid)
  543. }
  544. if n == nil {
  545. return driverapi.ErrNoNetwork(nid)
  546. }
  547. // Sanity check
  548. n.Lock()
  549. if n.id != nid {
  550. n.Unlock()
  551. return InvalidNetworkIDError(nid)
  552. }
  553. n.Unlock()
  554. // Check if endpoint id is good and retrieve correspondent endpoint
  555. ep, err := n.getEndpoint(eid)
  556. if err != nil {
  557. return err
  558. }
  559. // Endpoint with that id exists either on desired or other sandbox
  560. if ep != nil {
  561. return driverapi.ErrEndpointExists(eid)
  562. }
  563. // Try to convert the options to endpoint configuration
  564. epConfig, err := parseEndpointOptions(epOptions)
  565. if err != nil {
  566. return err
  567. }
  568. // Create and add the endpoint
  569. n.Lock()
  570. endpoint := &bridgeEndpoint{id: eid, config: epConfig}
  571. n.endpoints[eid] = endpoint
  572. n.Unlock()
  573. // On failure make sure to remove the endpoint
  574. defer func() {
  575. if err != nil {
  576. n.Lock()
  577. delete(n.endpoints, eid)
  578. n.Unlock()
  579. }
  580. }()
  581. // Create the sandbox side pipe interface
  582. if ifInfo.MacAddress() == nil {
  583. // No MAC address assigned to interface. Generate a random MAC to assign
  584. endpoint.macAddress = netutils.GenerateRandomMAC()
  585. if err := ifInfo.SetMacAddress(endpoint.macAddress); err != nil {
  586. logrus.Warnf("Unable to set mac address: %s to endpoint: %s",
  587. endpoint.macAddress.String(), endpoint.id)
  588. return err
  589. }
  590. } else {
  591. endpoint.macAddress = ifInfo.MacAddress()
  592. }
  593. endpoint.addr = ifInfo.Address()
  594. endpoint.addrv6 = ifInfo.AddressIPv6()
  595. c := n.config
  596. // Program any required port mapping and store them in the endpoint
  597. endpoint.portMapping, err = n.allocatePorts(endpoint, c.DefaultBindingIntf, c.DefaultBindingIP, true)
  598. if err != nil {
  599. return err
  600. }
  601. return nil
  602. }
  603. func (d *driver) DeleteEndpoint(nid, eid string) error {
  604. var err error
  605. // Get the network handler and make sure it exists
  606. d.Lock()
  607. n, ok := d.networks[nid]
  608. d.Unlock()
  609. if !ok {
  610. return types.InternalMaskableErrorf("network %s does not exist", nid)
  611. }
  612. if n == nil {
  613. return driverapi.ErrNoNetwork(nid)
  614. }
  615. // Sanity Check
  616. n.Lock()
  617. if n.id != nid {
  618. n.Unlock()
  619. return InvalidNetworkIDError(nid)
  620. }
  621. n.Unlock()
  622. // Check endpoint id and if an endpoint is actually there
  623. ep, err := n.getEndpoint(eid)
  624. if err != nil {
  625. return err
  626. }
  627. if ep == nil {
  628. return EndpointNotFoundError(eid)
  629. }
  630. // Remove it
  631. n.Lock()
  632. delete(n.endpoints, eid)
  633. n.Unlock()
  634. // On failure make sure to set back ep in n.endpoints, but only
  635. // if it hasn't been taken over already by some other thread.
  636. defer func() {
  637. if err != nil {
  638. n.Lock()
  639. if _, ok := n.endpoints[eid]; !ok {
  640. n.endpoints[eid] = ep
  641. }
  642. n.Unlock()
  643. }
  644. }()
  645. err = n.releasePorts(ep)
  646. if err != nil {
  647. logrus.Warn(err)
  648. }
  649. return nil
  650. }
  651. func (d *driver) EndpointOperInfo(nid, eid string) (map[string]interface{}, error) {
  652. // Get the network handler and make sure it exists
  653. d.Lock()
  654. n, ok := d.networks[nid]
  655. d.Unlock()
  656. if !ok {
  657. return nil, types.NotFoundErrorf("network %s does not exist", nid)
  658. }
  659. if n == nil {
  660. return nil, driverapi.ErrNoNetwork(nid)
  661. }
  662. // Sanity check
  663. n.Lock()
  664. if n.id != nid {
  665. n.Unlock()
  666. return nil, InvalidNetworkIDError(nid)
  667. }
  668. n.Unlock()
  669. // Check if endpoint id is good and retrieve correspondent endpoint
  670. ep, err := n.getEndpoint(eid)
  671. if err != nil {
  672. return nil, err
  673. }
  674. if ep == nil {
  675. return nil, driverapi.ErrNoEndpoint(eid)
  676. }
  677. m := make(map[string]interface{})
  678. if ep.extConnConfig != nil && ep.extConnConfig.ExposedPorts != nil {
  679. // Return a copy of the config data
  680. epc := make([]types.TransportPort, 0, len(ep.extConnConfig.ExposedPorts))
  681. for _, tp := range ep.extConnConfig.ExposedPorts {
  682. epc = append(epc, tp.GetCopy())
  683. }
  684. m[netlabel.ExposedPorts] = epc
  685. }
  686. if ep.portMapping != nil {
  687. // Return a copy of the operational data
  688. pmc := make([]types.PortBinding, 0, len(ep.portMapping))
  689. for _, pm := range ep.portMapping {
  690. pmc = append(pmc, pm.GetCopy())
  691. }
  692. m[netlabel.PortMap] = pmc
  693. }
  694. if len(ep.macAddress) != 0 {
  695. m[netlabel.MacAddress] = ep.macAddress
  696. }
  697. return m, nil
  698. }
  699. // Join method is invoked when a Sandbox is attached to an endpoint.
  700. func (d *driver) Join(nid, eid string, sboxKey string, jinfo driverapi.JoinInfo, options map[string]interface{}) error {
  701. network, err := d.getNetwork(nid)
  702. if err != nil {
  703. return err
  704. }
  705. endpoint, err := network.getEndpoint(eid)
  706. if err != nil {
  707. return err
  708. }
  709. if endpoint == nil {
  710. return EndpointNotFoundError(eid)
  711. }
  712. endpoint.containerConfig, err = parseContainerOptions(options)
  713. if err != nil {
  714. return err
  715. }
  716. err = jinfo.SetGateway(network.bridge.gatewayIPv4)
  717. if err != nil {
  718. return err
  719. }
  720. err = jinfo.SetGatewayIPv6(network.bridge.gatewayIPv6)
  721. if err != nil {
  722. return err
  723. }
  724. return nil
  725. }
  726. func (d *driver) link(network *bridgeNetwork, endpoint *bridgeEndpoint, enable bool) error {
  727. return nil
  728. }
  729. // Leave method is invoked when a Sandbox detaches from an endpoint.
  730. func (d *driver) Leave(nid, eid string) error {
  731. network, err := d.getNetwork(nid)
  732. if err != nil {
  733. return types.InternalMaskableErrorf("%s", err)
  734. }
  735. endpoint, err := network.getEndpoint(eid)
  736. if err != nil {
  737. return err
  738. }
  739. if endpoint == nil {
  740. return EndpointNotFoundError(eid)
  741. }
  742. return nil
  743. }
  744. func (d *driver) ProgramExternalConnectivity(nid, eid string, options map[string]interface{}) error {
  745. network, err := d.getNetwork(nid)
  746. if err != nil {
  747. return err
  748. }
  749. endpoint, err := network.getEndpoint(eid)
  750. if err != nil {
  751. return err
  752. }
  753. if endpoint == nil {
  754. return EndpointNotFoundError(eid)
  755. }
  756. endpoint.extConnConfig, err = parseConnectivityOptions(options)
  757. if err != nil {
  758. return err
  759. }
  760. // Program any required port mapping and store them in the endpoint
  761. endpoint.portMapping, err = network.allocatePorts(endpoint, network.config.DefaultBindingIntf, network.config.DefaultBindingIP, true)
  762. if err != nil {
  763. return err
  764. }
  765. if !network.config.EnableICC {
  766. return d.link(network, endpoint, true)
  767. }
  768. return nil
  769. }
  770. func (d *driver) RevokeExternalConnectivity(nid, eid string) error {
  771. network, err := d.getNetwork(nid)
  772. if err != nil {
  773. return err
  774. }
  775. endpoint, err := network.getEndpoint(eid)
  776. if err != nil {
  777. return err
  778. }
  779. if endpoint == nil {
  780. return EndpointNotFoundError(eid)
  781. }
  782. err = network.releasePorts(endpoint)
  783. if err != nil {
  784. logrus.Warn(err)
  785. }
  786. return nil
  787. }
  788. func (d *driver) Type() string {
  789. return networkType
  790. }
  791. // DiscoverNew is a notification for a new discovery event, such as a new node joining a cluster
  792. func (d *driver) DiscoverNew(dType discoverapi.DiscoveryType, data interface{}) error {
  793. return nil
  794. }
  795. // DiscoverDelete is a notification for a discovery delete event, such as a node leaving a cluster
  796. func (d *driver) DiscoverDelete(dType discoverapi.DiscoveryType, data interface{}) error {
  797. return nil
  798. }
  799. // Validate performs a static validation on the network configuration parameters.
  800. // Whatever can be assessed a priori before attempting any programming.
  801. func (c *networkConfiguration) Validate() error {
  802. if c.Mtu < 0 {
  803. return ErrInvalidMtu(c.Mtu)
  804. }
  805. // If bridge v4 subnet is specified
  806. if c.AddressIPv4 != nil {
  807. // If default gw is specified, it must be part of bridge subnet
  808. if c.DefaultGatewayIPv4 != nil {
  809. if !c.AddressIPv4.Contains(c.DefaultGatewayIPv4) {
  810. return &ErrInvalidGateway{}
  811. }
  812. }
  813. }
  814. // If default v6 gw is specified, AddressIPv6 must be specified and gw must belong to AddressIPv6 subnet
  815. if c.EnableIPv6 && c.DefaultGatewayIPv6 != nil {
  816. if c.AddressIPv6 == nil || !c.AddressIPv6.Contains(c.DefaultGatewayIPv6) {
  817. return &ErrInvalidGateway{}
  818. }
  819. }
  820. return nil
  821. }
  822. // Checks whether this network's configuration for the network with this id conflicts with any of the passed networks
  823. func (c *networkConfiguration) conflictsWithNetworks(id string, others []*bridgeNetwork) error {
  824. for _, nw := range others {
  825. nw.Lock()
  826. nwID := nw.id
  827. nwConfig := nw.config
  828. nwBridge := nw.bridge
  829. nw.Unlock()
  830. if nwID == id {
  831. continue
  832. }
  833. // Verify the name (which may have been set by newInterface()) does not conflict with
  834. // existing bridge interfaces. Ironically the system chosen name gets stored in the config...
  835. // Basically we are checking if the two original configs were both empty.
  836. if nwConfig.BridgeName == c.BridgeName {
  837. return types.ForbiddenErrorf("conflicts with network %s (%s) by bridge name", nwID, nwConfig.BridgeName)
  838. }
  839. // If this network config specifies the AddressIPv4, we need
  840. // to make sure it does not conflict with any previously allocated
  841. // bridges. This could not be completely caught by the config conflict
  842. // check, because networks which config does not specify the AddressIPv4
  843. // get their address and subnet selected by the driver (see electBridgeIPv4())
  844. if c.AddressIPv4 != nil {
  845. if nwBridge.bridgeIPv4.Contains(c.AddressIPv4.IP) ||
  846. c.AddressIPv4.Contains(nwBridge.bridgeIPv4.IP) {
  847. return types.ForbiddenErrorf("conflicts with network %s (%s) by ip network", nwID, nwConfig.BridgeName)
  848. }
  849. }
  850. }
  851. return nil
  852. }
  853. // Conflicts check if two NetworkConfiguration objects overlap
  854. func (c *networkConfiguration) Conflicts(o *networkConfiguration) error {
  855. if o == nil {
  856. return fmt.Errorf("same configuration")
  857. }
  858. // Also empty, because only one network with empty name is allowed
  859. if c.BridgeName == o.BridgeName {
  860. return fmt.Errorf("networks have same bridge name")
  861. }
  862. // They must be in different subnets
  863. if (c.AddressIPv4 != nil && o.AddressIPv4 != nil) &&
  864. (c.AddressIPv4.Contains(o.AddressIPv4.IP) || o.AddressIPv4.Contains(c.AddressIPv4.IP)) {
  865. return fmt.Errorf("networks have overlapping IPv4")
  866. }
  867. // They must be in different v6 subnets
  868. if (c.AddressIPv6 != nil && o.AddressIPv6 != nil) &&
  869. (c.AddressIPv6.Contains(o.AddressIPv6.IP) || o.AddressIPv6.Contains(c.AddressIPv6.IP)) {
  870. return fmt.Errorf("networks have overlapping IPv6")
  871. }
  872. return nil
  873. }
  874. func (c *networkConfiguration) fromLabels(labels map[string]string) error {
  875. var err error
  876. for label, value := range labels {
  877. switch label {
  878. case BridgeName:
  879. c.BridgeName = value
  880. case netlabel.DriverMTU:
  881. if c.Mtu, err = strconv.Atoi(value); err != nil {
  882. return parseErr(label, value, err.Error())
  883. }
  884. case netlabel.EnableIPv6:
  885. if c.EnableIPv6, err = strconv.ParseBool(value); err != nil {
  886. return parseErr(label, value, err.Error())
  887. }
  888. case EnableIPMasquerade:
  889. if c.EnableIPMasquerade, err = strconv.ParseBool(value); err != nil {
  890. return parseErr(label, value, err.Error())
  891. }
  892. case EnableICC:
  893. if c.EnableICC, err = strconv.ParseBool(value); err != nil {
  894. return parseErr(label, value, err.Error())
  895. }
  896. case DefaultBridge:
  897. if c.DefaultBridge, err = strconv.ParseBool(value); err != nil {
  898. return parseErr(label, value, err.Error())
  899. }
  900. case DefaultBindingIP:
  901. if c.DefaultBindingIP = net.ParseIP(value); c.DefaultBindingIP == nil {
  902. return parseErr(label, value, "nil ip")
  903. }
  904. }
  905. }
  906. return nil
  907. }
  908. func parseErr(label, value, errString string) error {
  909. return types.BadRequestErrorf("failed to parse %s value: %v (%s)", label, value, errString)
  910. }
  911. func parseNetworkGenericOptions(data interface{}) (*networkConfiguration, error) {
  912. var (
  913. err error
  914. config *networkConfiguration
  915. )
  916. switch opt := data.(type) {
  917. case *networkConfiguration:
  918. config = opt
  919. case map[string]string:
  920. config = &networkConfiguration{
  921. EnableICC: true,
  922. EnableIPMasquerade: true,
  923. }
  924. err = config.fromLabels(opt)
  925. case options.Generic:
  926. var opaqueConfig interface{}
  927. if opaqueConfig, err = options.GenerateFromModel(opt, config); err == nil {
  928. config = opaqueConfig.(*networkConfiguration)
  929. }
  930. default:
  931. err = types.BadRequestErrorf("do not recognize network configuration format: %T", opt)
  932. }
  933. return config, err
  934. }
  935. func parseNetworkOptions(d *driver, id string, option options.Generic) (*networkConfiguration, error) {
  936. var (
  937. err error
  938. config = &networkConfiguration{}
  939. )
  940. // Parse generic label first, config will be re-assigned
  941. if genData, ok := option[netlabel.GenericData]; ok && genData != nil {
  942. if config, err = parseNetworkGenericOptions(genData); err != nil {
  943. return nil, err
  944. }
  945. }
  946. // Process well-known labels next
  947. if val, ok := option[netlabel.EnableIPv6]; ok {
  948. config.EnableIPv6 = val.(bool)
  949. }
  950. if val, ok := option[netlabel.Internal]; ok {
  951. if internal, ok := val.(bool); ok && internal {
  952. config.Internal = true
  953. }
  954. }
  955. // Finally validate the configuration
  956. if err = config.Validate(); err != nil {
  957. return nil, err
  958. }
  959. if config.BridgeName == "" && config.DefaultBridge == false {
  960. config.BridgeName = "br_" + id[:12] + "_0"
  961. }
  962. lastChar := config.BridgeName[len(config.BridgeName)-1:]
  963. if _, err = strconv.Atoi(lastChar); err != nil {
  964. config.BridgeNameInternal = config.BridgeName + "_0"
  965. } else {
  966. config.BridgeNameInternal = config.BridgeName
  967. }
  968. config.ID = id
  969. return config, nil
  970. }
  971. func (c *networkConfiguration) processIPAM(id string, ipamV4Data, ipamV6Data []driverapi.IPAMData) error {
  972. if len(ipamV4Data) > 1 || len(ipamV6Data) > 1 {
  973. return types.ForbiddenErrorf("bridge driver doesnt support multiple subnets")
  974. }
  975. if len(ipamV4Data) == 0 {
  976. return types.BadRequestErrorf("bridge network %s requires ipv4 configuration", id)
  977. }
  978. if ipamV4Data[0].Gateway != nil {
  979. c.AddressIPv4 = types.GetIPNetCopy(ipamV4Data[0].Gateway)
  980. }
  981. if gw, ok := ipamV4Data[0].AuxAddresses[DefaultGatewayV4AuxKey]; ok {
  982. c.DefaultGatewayIPv4 = gw.IP
  983. }
  984. if len(ipamV6Data) > 0 {
  985. c.AddressIPv6 = ipamV6Data[0].Pool
  986. if ipamV6Data[0].Gateway != nil {
  987. c.AddressIPv6 = types.GetIPNetCopy(ipamV6Data[0].Gateway)
  988. }
  989. if gw, ok := ipamV6Data[0].AuxAddresses[DefaultGatewayV6AuxKey]; ok {
  990. c.DefaultGatewayIPv6 = gw.IP
  991. }
  992. }
  993. return nil
  994. }
  995. func (n *bridgeNetwork) getEndpoint(eid string) (*bridgeEndpoint, error) {
  996. n.Lock()
  997. defer n.Unlock()
  998. if eid == "" {
  999. return nil, InvalidEndpointIDError(eid)
  1000. }
  1001. if ep, ok := n.endpoints[eid]; ok {
  1002. return ep, nil
  1003. }
  1004. return nil, nil
  1005. }
  1006. func parseEndpointOptions(epOptions map[string]interface{}) (*endpointConfiguration, error) {
  1007. if epOptions == nil {
  1008. return nil, nil
  1009. }
  1010. ec := &endpointConfiguration{}
  1011. if opt, ok := epOptions[netlabel.MacAddress]; ok {
  1012. if mac, ok := opt.(net.HardwareAddr); ok {
  1013. ec.MacAddress = mac
  1014. } else {
  1015. return nil, &ErrInvalidEndpointConfig{}
  1016. }
  1017. }
  1018. if opt, ok := epOptions[netlabel.PortMap]; ok {
  1019. if bs, ok := opt.([]types.PortBinding); ok {
  1020. ec.PortBindings = bs
  1021. } else {
  1022. return nil, &ErrInvalidEndpointConfig{}
  1023. }
  1024. }
  1025. if opt, ok := epOptions[netlabel.ExposedPorts]; ok {
  1026. if ports, ok := opt.([]types.TransportPort); ok {
  1027. ec.ExposedPorts = ports
  1028. } else {
  1029. return nil, &ErrInvalidEndpointConfig{}
  1030. }
  1031. }
  1032. return ec, nil
  1033. }
  1034. func parseContainerOptions(cOptions map[string]interface{}) (*containerConfiguration, error) {
  1035. if cOptions == nil {
  1036. return nil, nil
  1037. }
  1038. genericData := cOptions[netlabel.GenericData]
  1039. if genericData == nil {
  1040. return nil, nil
  1041. }
  1042. switch opt := genericData.(type) {
  1043. case options.Generic:
  1044. opaqueConfig, err := options.GenerateFromModel(opt, &containerConfiguration{})
  1045. if err != nil {
  1046. return nil, err
  1047. }
  1048. return opaqueConfig.(*containerConfiguration), nil
  1049. case *containerConfiguration:
  1050. return opt, nil
  1051. default:
  1052. return nil, nil
  1053. }
  1054. }
  1055. func parseConnectivityOptions(cOptions map[string]interface{}) (*connectivityConfiguration, error) {
  1056. if cOptions == nil {
  1057. return nil, nil
  1058. }
  1059. cc := &connectivityConfiguration{}
  1060. if opt, ok := cOptions[netlabel.PortMap]; ok {
  1061. if pb, ok := opt.([]types.PortBinding); ok {
  1062. cc.PortBindings = pb
  1063. } else {
  1064. return nil, types.BadRequestErrorf("Invalid port mapping data in connectivity configuration: %v", opt)
  1065. }
  1066. }
  1067. if opt, ok := cOptions[netlabel.ExposedPorts]; ok {
  1068. if ports, ok := opt.([]types.TransportPort); ok {
  1069. cc.ExposedPorts = ports
  1070. } else {
  1071. return nil, types.BadRequestErrorf("Invalid exposed ports data in connectivity configuration: %v", opt)
  1072. }
  1073. }
  1074. return cc, nil
  1075. }