bridge.go 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258
  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. func (d *driver) IsBuiltIn() bool {
  792. return true
  793. }
  794. // DiscoverNew is a notification for a new discovery event, such as a new node joining a cluster
  795. func (d *driver) DiscoverNew(dType discoverapi.DiscoveryType, data interface{}) error {
  796. return nil
  797. }
  798. // DiscoverDelete is a notification for a discovery delete event, such as a node leaving a cluster
  799. func (d *driver) DiscoverDelete(dType discoverapi.DiscoveryType, data interface{}) error {
  800. return nil
  801. }
  802. // Validate performs a static validation on the network configuration parameters.
  803. // Whatever can be assessed a priori before attempting any programming.
  804. func (c *networkConfiguration) Validate() error {
  805. if c.Mtu < 0 {
  806. return ErrInvalidMtu(c.Mtu)
  807. }
  808. // If bridge v4 subnet is specified
  809. if c.AddressIPv4 != nil {
  810. // If default gw is specified, it must be part of bridge subnet
  811. if c.DefaultGatewayIPv4 != nil {
  812. if !c.AddressIPv4.Contains(c.DefaultGatewayIPv4) {
  813. return &ErrInvalidGateway{}
  814. }
  815. }
  816. }
  817. // If default v6 gw is specified, AddressIPv6 must be specified and gw must belong to AddressIPv6 subnet
  818. if c.EnableIPv6 && c.DefaultGatewayIPv6 != nil {
  819. if c.AddressIPv6 == nil || !c.AddressIPv6.Contains(c.DefaultGatewayIPv6) {
  820. return &ErrInvalidGateway{}
  821. }
  822. }
  823. return nil
  824. }
  825. // Checks whether this network's configuration for the network with this id conflicts with any of the passed networks
  826. func (c *networkConfiguration) conflictsWithNetworks(id string, others []*bridgeNetwork) error {
  827. for _, nw := range others {
  828. nw.Lock()
  829. nwID := nw.id
  830. nwConfig := nw.config
  831. nwBridge := nw.bridge
  832. nw.Unlock()
  833. if nwID == id {
  834. continue
  835. }
  836. // Verify the name (which may have been set by newInterface()) does not conflict with
  837. // existing bridge interfaces. Ironically the system chosen name gets stored in the config...
  838. // Basically we are checking if the two original configs were both empty.
  839. if nwConfig.BridgeName == c.BridgeName {
  840. return types.ForbiddenErrorf("conflicts with network %s (%s) by bridge name", nwID, nwConfig.BridgeName)
  841. }
  842. // If this network config specifies the AddressIPv4, we need
  843. // to make sure it does not conflict with any previously allocated
  844. // bridges. This could not be completely caught by the config conflict
  845. // check, because networks which config does not specify the AddressIPv4
  846. // get their address and subnet selected by the driver (see electBridgeIPv4())
  847. if c.AddressIPv4 != nil {
  848. if nwBridge.bridgeIPv4.Contains(c.AddressIPv4.IP) ||
  849. c.AddressIPv4.Contains(nwBridge.bridgeIPv4.IP) {
  850. return types.ForbiddenErrorf("conflicts with network %s (%s) by ip network", nwID, nwConfig.BridgeName)
  851. }
  852. }
  853. }
  854. return nil
  855. }
  856. // Conflicts check if two NetworkConfiguration objects overlap
  857. func (c *networkConfiguration) Conflicts(o *networkConfiguration) error {
  858. if o == nil {
  859. return fmt.Errorf("same configuration")
  860. }
  861. // Also empty, because only one network with empty name is allowed
  862. if c.BridgeName == o.BridgeName {
  863. return fmt.Errorf("networks have same bridge name")
  864. }
  865. // They must be in different subnets
  866. if (c.AddressIPv4 != nil && o.AddressIPv4 != nil) &&
  867. (c.AddressIPv4.Contains(o.AddressIPv4.IP) || o.AddressIPv4.Contains(c.AddressIPv4.IP)) {
  868. return fmt.Errorf("networks have overlapping IPv4")
  869. }
  870. // They must be in different v6 subnets
  871. if (c.AddressIPv6 != nil && o.AddressIPv6 != nil) &&
  872. (c.AddressIPv6.Contains(o.AddressIPv6.IP) || o.AddressIPv6.Contains(c.AddressIPv6.IP)) {
  873. return fmt.Errorf("networks have overlapping IPv6")
  874. }
  875. return nil
  876. }
  877. func (c *networkConfiguration) fromLabels(labels map[string]string) error {
  878. var err error
  879. for label, value := range labels {
  880. switch label {
  881. case BridgeName:
  882. c.BridgeName = value
  883. case netlabel.DriverMTU:
  884. if c.Mtu, err = strconv.Atoi(value); err != nil {
  885. return parseErr(label, value, err.Error())
  886. }
  887. case netlabel.EnableIPv6:
  888. if c.EnableIPv6, err = strconv.ParseBool(value); err != nil {
  889. return parseErr(label, value, err.Error())
  890. }
  891. case EnableIPMasquerade:
  892. if c.EnableIPMasquerade, err = strconv.ParseBool(value); err != nil {
  893. return parseErr(label, value, err.Error())
  894. }
  895. case EnableICC:
  896. if c.EnableICC, err = strconv.ParseBool(value); err != nil {
  897. return parseErr(label, value, err.Error())
  898. }
  899. case DefaultBridge:
  900. if c.DefaultBridge, err = strconv.ParseBool(value); err != nil {
  901. return parseErr(label, value, err.Error())
  902. }
  903. case DefaultBindingIP:
  904. if c.DefaultBindingIP = net.ParseIP(value); c.DefaultBindingIP == nil {
  905. return parseErr(label, value, "nil ip")
  906. }
  907. }
  908. }
  909. return nil
  910. }
  911. func parseErr(label, value, errString string) error {
  912. return types.BadRequestErrorf("failed to parse %s value: %v (%s)", label, value, errString)
  913. }
  914. func parseNetworkGenericOptions(data interface{}) (*networkConfiguration, error) {
  915. var (
  916. err error
  917. config *networkConfiguration
  918. )
  919. switch opt := data.(type) {
  920. case *networkConfiguration:
  921. config = opt
  922. case map[string]string:
  923. config = &networkConfiguration{
  924. EnableICC: true,
  925. EnableIPMasquerade: true,
  926. }
  927. err = config.fromLabels(opt)
  928. case options.Generic:
  929. var opaqueConfig interface{}
  930. if opaqueConfig, err = options.GenerateFromModel(opt, config); err == nil {
  931. config = opaqueConfig.(*networkConfiguration)
  932. }
  933. default:
  934. err = types.BadRequestErrorf("do not recognize network configuration format: %T", opt)
  935. }
  936. return config, err
  937. }
  938. func parseNetworkOptions(d *driver, id string, option options.Generic) (*networkConfiguration, error) {
  939. var (
  940. err error
  941. config = &networkConfiguration{}
  942. )
  943. // Parse generic label first, config will be re-assigned
  944. if genData, ok := option[netlabel.GenericData]; ok && genData != nil {
  945. if config, err = parseNetworkGenericOptions(genData); err != nil {
  946. return nil, err
  947. }
  948. }
  949. // Process well-known labels next
  950. if val, ok := option[netlabel.EnableIPv6]; ok {
  951. config.EnableIPv6 = val.(bool)
  952. }
  953. if val, ok := option[netlabel.Internal]; ok {
  954. if internal, ok := val.(bool); ok && internal {
  955. config.Internal = true
  956. }
  957. }
  958. // Finally validate the configuration
  959. if err = config.Validate(); err != nil {
  960. return nil, err
  961. }
  962. if config.BridgeName == "" && config.DefaultBridge == false {
  963. config.BridgeName = "br_" + id[:12] + "_0"
  964. }
  965. lastChar := config.BridgeName[len(config.BridgeName)-1:]
  966. if _, err = strconv.Atoi(lastChar); err != nil {
  967. config.BridgeNameInternal = config.BridgeName + "_0"
  968. } else {
  969. config.BridgeNameInternal = config.BridgeName
  970. }
  971. config.ID = id
  972. return config, nil
  973. }
  974. func (c *networkConfiguration) processIPAM(id string, ipamV4Data, ipamV6Data []driverapi.IPAMData) error {
  975. if len(ipamV4Data) > 1 || len(ipamV6Data) > 1 {
  976. return types.ForbiddenErrorf("bridge driver doesnt support multiple subnets")
  977. }
  978. if len(ipamV4Data) == 0 {
  979. return types.BadRequestErrorf("bridge network %s requires ipv4 configuration", id)
  980. }
  981. if ipamV4Data[0].Gateway != nil {
  982. c.AddressIPv4 = types.GetIPNetCopy(ipamV4Data[0].Gateway)
  983. }
  984. if gw, ok := ipamV4Data[0].AuxAddresses[DefaultGatewayV4AuxKey]; ok {
  985. c.DefaultGatewayIPv4 = gw.IP
  986. }
  987. if len(ipamV6Data) > 0 {
  988. c.AddressIPv6 = ipamV6Data[0].Pool
  989. if ipamV6Data[0].Gateway != nil {
  990. c.AddressIPv6 = types.GetIPNetCopy(ipamV6Data[0].Gateway)
  991. }
  992. if gw, ok := ipamV6Data[0].AuxAddresses[DefaultGatewayV6AuxKey]; ok {
  993. c.DefaultGatewayIPv6 = gw.IP
  994. }
  995. }
  996. return nil
  997. }
  998. func (n *bridgeNetwork) getEndpoint(eid string) (*bridgeEndpoint, error) {
  999. n.Lock()
  1000. defer n.Unlock()
  1001. if eid == "" {
  1002. return nil, InvalidEndpointIDError(eid)
  1003. }
  1004. if ep, ok := n.endpoints[eid]; ok {
  1005. return ep, nil
  1006. }
  1007. return nil, nil
  1008. }
  1009. func parseEndpointOptions(epOptions map[string]interface{}) (*endpointConfiguration, error) {
  1010. if epOptions == nil {
  1011. return nil, nil
  1012. }
  1013. ec := &endpointConfiguration{}
  1014. if opt, ok := epOptions[netlabel.MacAddress]; ok {
  1015. if mac, ok := opt.(net.HardwareAddr); ok {
  1016. ec.MacAddress = mac
  1017. } else {
  1018. return nil, &ErrInvalidEndpointConfig{}
  1019. }
  1020. }
  1021. if opt, ok := epOptions[netlabel.PortMap]; ok {
  1022. if bs, ok := opt.([]types.PortBinding); ok {
  1023. ec.PortBindings = bs
  1024. } else {
  1025. return nil, &ErrInvalidEndpointConfig{}
  1026. }
  1027. }
  1028. if opt, ok := epOptions[netlabel.ExposedPorts]; ok {
  1029. if ports, ok := opt.([]types.TransportPort); ok {
  1030. ec.ExposedPorts = ports
  1031. } else {
  1032. return nil, &ErrInvalidEndpointConfig{}
  1033. }
  1034. }
  1035. return ec, nil
  1036. }
  1037. func parseContainerOptions(cOptions map[string]interface{}) (*containerConfiguration, error) {
  1038. if cOptions == nil {
  1039. return nil, nil
  1040. }
  1041. genericData := cOptions[netlabel.GenericData]
  1042. if genericData == nil {
  1043. return nil, nil
  1044. }
  1045. switch opt := genericData.(type) {
  1046. case options.Generic:
  1047. opaqueConfig, err := options.GenerateFromModel(opt, &containerConfiguration{})
  1048. if err != nil {
  1049. return nil, err
  1050. }
  1051. return opaqueConfig.(*containerConfiguration), nil
  1052. case *containerConfiguration:
  1053. return opt, nil
  1054. default:
  1055. return nil, nil
  1056. }
  1057. }
  1058. func parseConnectivityOptions(cOptions map[string]interface{}) (*connectivityConfiguration, error) {
  1059. if cOptions == nil {
  1060. return nil, nil
  1061. }
  1062. cc := &connectivityConfiguration{}
  1063. if opt, ok := cOptions[netlabel.PortMap]; ok {
  1064. if pb, ok := opt.([]types.PortBinding); ok {
  1065. cc.PortBindings = pb
  1066. } else {
  1067. return nil, types.BadRequestErrorf("Invalid port mapping data in connectivity configuration: %v", opt)
  1068. }
  1069. }
  1070. if opt, ok := cOptions[netlabel.ExposedPorts]; ok {
  1071. if ports, ok := opt.([]types.TransportPort); ok {
  1072. cc.ExposedPorts = ports
  1073. } else {
  1074. return nil, types.BadRequestErrorf("Invalid exposed ports data in connectivity configuration: %v", opt)
  1075. }
  1076. }
  1077. return cc, nil
  1078. }