bridge.go 33 KB

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