bridge_test.go 30 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111
  1. package bridge
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "fmt"
  6. "net"
  7. "regexp"
  8. "strconv"
  9. "testing"
  10. "github.com/docker/libnetwork/driverapi"
  11. "github.com/docker/libnetwork/iptables"
  12. "github.com/docker/libnetwork/netlabel"
  13. "github.com/docker/libnetwork/netutils"
  14. "github.com/docker/libnetwork/options"
  15. "github.com/docker/libnetwork/testutils"
  16. "github.com/docker/libnetwork/types"
  17. "github.com/vishvananda/netlink"
  18. )
  19. func TestEndpointMarshalling(t *testing.T) {
  20. ip1, _ := types.ParseCIDR("172.22.0.9/16")
  21. ip2, _ := types.ParseCIDR("2001:db8::9")
  22. mac, _ := net.ParseMAC("ac:bd:24:57:66:77")
  23. e := &bridgeEndpoint{
  24. id: "d2c015a1fe5930650cbcd50493efba0500bcebd8ee1f4401a16319f8a567de33",
  25. nid: "ee33fbb43c323f1920b6b35a0101552ac22ede960d0e5245e9738bccc68b2415",
  26. addr: ip1,
  27. addrv6: ip2,
  28. macAddress: mac,
  29. srcName: "veth123456",
  30. config: &endpointConfiguration{MacAddress: mac},
  31. containerConfig: &containerConfiguration{
  32. ParentEndpoints: []string{"one", "due", "three"},
  33. ChildEndpoints: []string{"four", "five", "six"},
  34. },
  35. extConnConfig: &connectivityConfiguration{
  36. ExposedPorts: []types.TransportPort{
  37. {
  38. Proto: 6,
  39. Port: uint16(18),
  40. },
  41. },
  42. PortBindings: []types.PortBinding{
  43. {
  44. Proto: 6,
  45. IP: net.ParseIP("17210.33.9.56"),
  46. Port: uint16(18),
  47. HostPort: uint16(3000),
  48. HostPortEnd: uint16(14000),
  49. },
  50. },
  51. },
  52. portMapping: []types.PortBinding{
  53. {
  54. Proto: 17,
  55. IP: net.ParseIP("172.33.9.56"),
  56. Port: uint16(99),
  57. HostIP: net.ParseIP("10.10.100.2"),
  58. HostPort: uint16(9900),
  59. HostPortEnd: uint16(10000),
  60. },
  61. {
  62. Proto: 6,
  63. IP: net.ParseIP("171.33.9.56"),
  64. Port: uint16(55),
  65. HostIP: net.ParseIP("10.11.100.2"),
  66. HostPort: uint16(5500),
  67. HostPortEnd: uint16(55000),
  68. },
  69. },
  70. }
  71. b, err := json.Marshal(e)
  72. if err != nil {
  73. t.Fatal(err)
  74. }
  75. ee := &bridgeEndpoint{}
  76. err = json.Unmarshal(b, ee)
  77. if err != nil {
  78. t.Fatal(err)
  79. }
  80. if e.id != ee.id || e.nid != ee.nid || e.srcName != ee.srcName || !bytes.Equal(e.macAddress, ee.macAddress) ||
  81. !types.CompareIPNet(e.addr, ee.addr) || !types.CompareIPNet(e.addrv6, ee.addrv6) ||
  82. !compareEpConfig(e.config, ee.config) ||
  83. !compareContainerConfig(e.containerConfig, ee.containerConfig) ||
  84. !compareConnConfig(e.extConnConfig, ee.extConnConfig) ||
  85. !compareBindings(e.portMapping, ee.portMapping) {
  86. t.Fatalf("JSON marsh/unmarsh failed.\nOriginal:\n%#v\nDecoded:\n%#v", e, ee)
  87. }
  88. }
  89. func compareEpConfig(a, b *endpointConfiguration) bool {
  90. if a == b {
  91. return true
  92. }
  93. if a == nil || b == nil {
  94. return false
  95. }
  96. return bytes.Equal(a.MacAddress, b.MacAddress)
  97. }
  98. func compareContainerConfig(a, b *containerConfiguration) bool {
  99. if a == b {
  100. return true
  101. }
  102. if a == nil || b == nil {
  103. return false
  104. }
  105. if len(a.ParentEndpoints) != len(b.ParentEndpoints) ||
  106. len(a.ChildEndpoints) != len(b.ChildEndpoints) {
  107. return false
  108. }
  109. for i := 0; i < len(a.ParentEndpoints); i++ {
  110. if a.ParentEndpoints[i] != b.ParentEndpoints[i] {
  111. return false
  112. }
  113. }
  114. for i := 0; i < len(a.ChildEndpoints); i++ {
  115. if a.ChildEndpoints[i] != b.ChildEndpoints[i] {
  116. return false
  117. }
  118. }
  119. return true
  120. }
  121. func compareConnConfig(a, b *connectivityConfiguration) bool {
  122. if a == b {
  123. return true
  124. }
  125. if a == nil || b == nil {
  126. return false
  127. }
  128. if len(a.ExposedPorts) != len(b.ExposedPorts) ||
  129. len(a.PortBindings) != len(b.PortBindings) {
  130. return false
  131. }
  132. for i := 0; i < len(a.ExposedPorts); i++ {
  133. if !a.ExposedPorts[i].Equal(&b.ExposedPorts[i]) {
  134. return false
  135. }
  136. }
  137. for i := 0; i < len(a.PortBindings); i++ {
  138. if !a.PortBindings[i].Equal(&b.PortBindings[i]) {
  139. return false
  140. }
  141. }
  142. return true
  143. }
  144. func compareBindings(a, b []types.PortBinding) bool {
  145. if len(a) != len(b) {
  146. return false
  147. }
  148. for i := 0; i < len(a); i++ {
  149. if !a[i].Equal(&b[i]) {
  150. return false
  151. }
  152. }
  153. return true
  154. }
  155. func getIPv4Data(t *testing.T, iface string) []driverapi.IPAMData {
  156. ipd := driverapi.IPAMData{AddressSpace: "full"}
  157. nws, _, err := netutils.ElectInterfaceAddresses(iface)
  158. if err != nil {
  159. t.Fatal(err)
  160. }
  161. ipd.Pool = nws[0]
  162. // Set network gateway to X.X.X.1
  163. ipd.Gateway = types.GetIPNetCopy(nws[0])
  164. ipd.Gateway.IP[len(ipd.Gateway.IP)-1] = 1
  165. return []driverapi.IPAMData{ipd}
  166. }
  167. func TestCreateFullOptions(t *testing.T) {
  168. if !testutils.IsRunningInContainer() {
  169. defer testutils.SetupTestOSContext(t)()
  170. }
  171. d := newDriver()
  172. config := &configuration{
  173. EnableIPForwarding: true,
  174. EnableIPTables: true,
  175. }
  176. // Test this scenario: Default gw address does not belong to
  177. // container network and it's greater than bridge address
  178. cnw, _ := types.ParseCIDR("172.16.122.0/24")
  179. bnw, _ := types.ParseCIDR("172.16.0.0/24")
  180. br, _ := types.ParseCIDR("172.16.0.1/16")
  181. defgw, _ := types.ParseCIDR("172.16.0.100/16")
  182. genericOption := make(map[string]interface{})
  183. genericOption[netlabel.GenericData] = config
  184. if err := d.configure(genericOption); err != nil {
  185. t.Fatalf("Failed to setup driver config: %v", err)
  186. }
  187. netOption := make(map[string]interface{})
  188. netOption[netlabel.EnableIPv6] = true
  189. netOption[netlabel.GenericData] = &networkConfiguration{
  190. BridgeName: DefaultBridgeName,
  191. }
  192. ipdList := []driverapi.IPAMData{
  193. {
  194. Pool: bnw,
  195. Gateway: br,
  196. AuxAddresses: map[string]*net.IPNet{DefaultGatewayV4AuxKey: defgw},
  197. },
  198. }
  199. err := d.CreateNetwork("dummy", netOption, nil, ipdList, nil)
  200. if err != nil {
  201. t.Fatalf("Failed to create bridge: %v", err)
  202. }
  203. // Verify the IP address allocated for the endpoint belongs to the container network
  204. epOptions := make(map[string]interface{})
  205. te := newTestEndpoint(cnw, 10)
  206. err = d.CreateEndpoint("dummy", "ep1", te.Interface(), epOptions)
  207. if err != nil {
  208. t.Fatalf("Failed to create an endpoint : %s", err.Error())
  209. }
  210. if !cnw.Contains(te.Interface().Address().IP) {
  211. t.Fatalf("endpoint got assigned address outside of container network(%s): %s", cnw.String(), te.Interface().Address())
  212. }
  213. }
  214. func TestCreateNoConfig(t *testing.T) {
  215. if !testutils.IsRunningInContainer() {
  216. defer testutils.SetupTestOSContext(t)()
  217. }
  218. d := newDriver()
  219. netconfig := &networkConfiguration{BridgeName: DefaultBridgeName}
  220. genericOption := make(map[string]interface{})
  221. genericOption[netlabel.GenericData] = netconfig
  222. if err := d.CreateNetwork("dummy", genericOption, nil, getIPv4Data(t, ""), nil); err != nil {
  223. t.Fatalf("Failed to create bridge: %v", err)
  224. }
  225. }
  226. func TestCreateFullOptionsLabels(t *testing.T) {
  227. if !testutils.IsRunningInContainer() {
  228. defer testutils.SetupTestOSContext(t)()
  229. }
  230. d := newDriver()
  231. config := &configuration{
  232. EnableIPForwarding: true,
  233. }
  234. genericOption := make(map[string]interface{})
  235. genericOption[netlabel.GenericData] = config
  236. if err := d.configure(genericOption); err != nil {
  237. t.Fatalf("Failed to setup driver config: %v", err)
  238. }
  239. bndIPs := "127.0.0.1"
  240. nwV6s := "2001:db8:2600:2700:2800::/80"
  241. gwV6s := "2001:db8:2600:2700:2800::25/80"
  242. nwV6, _ := types.ParseCIDR(nwV6s)
  243. gwV6, _ := types.ParseCIDR(gwV6s)
  244. labels := map[string]string{
  245. BridgeName: DefaultBridgeName,
  246. DefaultBridge: "true",
  247. EnableICC: "true",
  248. EnableIPMasquerade: "true",
  249. DefaultBindingIP: bndIPs,
  250. }
  251. netOption := make(map[string]interface{})
  252. netOption[netlabel.EnableIPv6] = true
  253. netOption[netlabel.GenericData] = labels
  254. ipdList := getIPv4Data(t, "")
  255. ipd6List := []driverapi.IPAMData{
  256. {
  257. Pool: nwV6,
  258. AuxAddresses: map[string]*net.IPNet{
  259. DefaultGatewayV6AuxKey: gwV6,
  260. },
  261. },
  262. }
  263. err := d.CreateNetwork("dummy", netOption, nil, ipdList, ipd6List)
  264. if err != nil {
  265. t.Fatalf("Failed to create bridge: %v", err)
  266. }
  267. nw, ok := d.networks["dummy"]
  268. if !ok {
  269. t.Fatal("Cannot find dummy network in bridge driver")
  270. }
  271. if nw.config.BridgeName != DefaultBridgeName {
  272. t.Fatal("incongruent name in bridge network")
  273. }
  274. if !nw.config.EnableIPv6 {
  275. t.Fatal("incongruent EnableIPv6 in bridge network")
  276. }
  277. if !nw.config.EnableICC {
  278. t.Fatal("incongruent EnableICC in bridge network")
  279. }
  280. if !nw.config.EnableIPMasquerade {
  281. t.Fatal("incongruent EnableIPMasquerade in bridge network")
  282. }
  283. bndIP := net.ParseIP(bndIPs)
  284. if !bndIP.Equal(nw.config.DefaultBindingIP) {
  285. t.Fatalf("Unexpected: %v", nw.config.DefaultBindingIP)
  286. }
  287. if !types.CompareIPNet(nw.config.AddressIPv6, nwV6) {
  288. t.Fatalf("Unexpected: %v", nw.config.AddressIPv6)
  289. }
  290. if !gwV6.IP.Equal(nw.config.DefaultGatewayIPv6) {
  291. t.Fatalf("Unexpected: %v", nw.config.DefaultGatewayIPv6)
  292. }
  293. // In short here we are testing --fixed-cidr-v6 daemon option
  294. // plus --mac-address run option
  295. mac, _ := net.ParseMAC("aa:bb:cc:dd:ee:ff")
  296. epOptions := map[string]interface{}{netlabel.MacAddress: mac}
  297. te := newTestEndpoint(ipdList[0].Pool, 20)
  298. err = d.CreateEndpoint("dummy", "ep1", te.Interface(), epOptions)
  299. if err != nil {
  300. t.Fatal(err)
  301. }
  302. if !nwV6.Contains(te.Interface().AddressIPv6().IP) {
  303. t.Fatalf("endpoint got assigned address outside of container network(%s): %s", nwV6.String(), te.Interface().AddressIPv6())
  304. }
  305. if te.Interface().AddressIPv6().IP.String() != "2001:db8:2600:2700:2800:aabb:ccdd:eeff" {
  306. t.Fatalf("Unexpected endpoint IPv6 address: %v", te.Interface().AddressIPv6().IP)
  307. }
  308. }
  309. func TestCreate(t *testing.T) {
  310. if !testutils.IsRunningInContainer() {
  311. defer testutils.SetupTestOSContext(t)()
  312. }
  313. d := newDriver()
  314. if err := d.configure(nil); err != nil {
  315. t.Fatalf("Failed to setup driver config: %v", err)
  316. }
  317. netconfig := &networkConfiguration{BridgeName: DefaultBridgeName}
  318. genericOption := make(map[string]interface{})
  319. genericOption[netlabel.GenericData] = netconfig
  320. if err := d.CreateNetwork("dummy", genericOption, nil, getIPv4Data(t, ""), nil); err != nil {
  321. t.Fatalf("Failed to create bridge: %v", err)
  322. }
  323. err := d.CreateNetwork("dummy", genericOption, nil, getIPv4Data(t, ""), nil)
  324. if err == nil {
  325. t.Fatal("Expected bridge driver to refuse creation of second network with default name")
  326. }
  327. if _, ok := err.(types.ForbiddenError); !ok {
  328. t.Fatal("Creation of second network with default name failed with unexpected error type")
  329. }
  330. }
  331. func TestCreateFail(t *testing.T) {
  332. if !testutils.IsRunningInContainer() {
  333. defer testutils.SetupTestOSContext(t)()
  334. }
  335. d := newDriver()
  336. if err := d.configure(nil); err != nil {
  337. t.Fatalf("Failed to setup driver config: %v", err)
  338. }
  339. netconfig := &networkConfiguration{BridgeName: "dummy0", DefaultBridge: true}
  340. genericOption := make(map[string]interface{})
  341. genericOption[netlabel.GenericData] = netconfig
  342. if err := d.CreateNetwork("dummy", genericOption, nil, getIPv4Data(t, ""), nil); err == nil {
  343. t.Fatal("Bridge creation was expected to fail")
  344. }
  345. }
  346. func TestCreateMultipleNetworks(t *testing.T) {
  347. if !testutils.IsRunningInContainer() {
  348. defer testutils.SetupTestOSContext(t)()
  349. }
  350. d := newDriver()
  351. config := &configuration{
  352. EnableIPTables: true,
  353. }
  354. genericOption := make(map[string]interface{})
  355. genericOption[netlabel.GenericData] = config
  356. if err := d.configure(genericOption); err != nil {
  357. t.Fatalf("Failed to setup driver config: %v", err)
  358. }
  359. config1 := &networkConfiguration{BridgeName: "net_test_1"}
  360. genericOption = make(map[string]interface{})
  361. genericOption[netlabel.GenericData] = config1
  362. if err := d.CreateNetwork("1", genericOption, nil, getIPv4Data(t, ""), nil); err != nil {
  363. t.Fatalf("Failed to create bridge: %v", err)
  364. }
  365. verifyV4INCEntries(d.networks, t)
  366. config2 := &networkConfiguration{BridgeName: "net_test_2"}
  367. genericOption[netlabel.GenericData] = config2
  368. if err := d.CreateNetwork("2", genericOption, nil, getIPv4Data(t, ""), nil); err != nil {
  369. t.Fatalf("Failed to create bridge: %v", err)
  370. }
  371. verifyV4INCEntries(d.networks, t)
  372. config3 := &networkConfiguration{BridgeName: "net_test_3"}
  373. genericOption[netlabel.GenericData] = config3
  374. if err := d.CreateNetwork("3", genericOption, nil, getIPv4Data(t, ""), nil); err != nil {
  375. t.Fatalf("Failed to create bridge: %v", err)
  376. }
  377. verifyV4INCEntries(d.networks, t)
  378. config4 := &networkConfiguration{BridgeName: "net_test_4"}
  379. genericOption[netlabel.GenericData] = config4
  380. if err := d.CreateNetwork("4", genericOption, nil, getIPv4Data(t, ""), nil); err != nil {
  381. t.Fatalf("Failed to create bridge: %v", err)
  382. }
  383. verifyV4INCEntries(d.networks, t)
  384. d.DeleteNetwork("1")
  385. verifyV4INCEntries(d.networks, t)
  386. d.DeleteNetwork("2")
  387. verifyV4INCEntries(d.networks, t)
  388. d.DeleteNetwork("3")
  389. verifyV4INCEntries(d.networks, t)
  390. d.DeleteNetwork("4")
  391. verifyV4INCEntries(d.networks, t)
  392. }
  393. // Verify the network isolation rules are installed for each network
  394. func verifyV4INCEntries(networks map[string]*bridgeNetwork, t *testing.T) {
  395. out1, err := iptables.Raw("-S", IsolationChain1)
  396. if err != nil {
  397. t.Fatal(err)
  398. }
  399. out2, err := iptables.Raw("-S", IsolationChain2)
  400. if err != nil {
  401. t.Fatal(err)
  402. }
  403. for _, n := range networks {
  404. re := regexp.MustCompile(fmt.Sprintf("-i %s ! -o %s -j %s", n.config.BridgeName, n.config.BridgeName, IsolationChain2))
  405. matches := re.FindAllString(string(out1[:]), -1)
  406. if len(matches) != 1 {
  407. t.Fatalf("Cannot find expected inter-network isolation rules in IP Tables for network %s:\n%s.", n.id, string(out1[:]))
  408. }
  409. re = regexp.MustCompile(fmt.Sprintf("-o %s -j DROP", n.config.BridgeName))
  410. matches = re.FindAllString(string(out2[:]), -1)
  411. if len(matches) != 1 {
  412. t.Fatalf("Cannot find expected inter-network isolation rules in IP Tables for network %s:\n%s.", n.id, string(out2[:]))
  413. }
  414. }
  415. }
  416. type testInterface struct {
  417. mac net.HardwareAddr
  418. addr *net.IPNet
  419. addrv6 *net.IPNet
  420. srcName string
  421. dstName string
  422. }
  423. type testEndpoint struct {
  424. iface *testInterface
  425. gw net.IP
  426. gw6 net.IP
  427. hostsPath string
  428. resolvConfPath string
  429. routes []types.StaticRoute
  430. }
  431. func newTestEndpoint(nw *net.IPNet, ordinal byte) *testEndpoint {
  432. addr := types.GetIPNetCopy(nw)
  433. addr.IP[len(addr.IP)-1] = ordinal
  434. return &testEndpoint{iface: &testInterface{addr: addr}}
  435. }
  436. func (te *testEndpoint) Interface() driverapi.InterfaceInfo {
  437. if te.iface != nil {
  438. return te.iface
  439. }
  440. return nil
  441. }
  442. func (i *testInterface) MacAddress() net.HardwareAddr {
  443. return i.mac
  444. }
  445. func (i *testInterface) Address() *net.IPNet {
  446. return i.addr
  447. }
  448. func (i *testInterface) AddressIPv6() *net.IPNet {
  449. return i.addrv6
  450. }
  451. func (i *testInterface) SetMacAddress(mac net.HardwareAddr) error {
  452. if i.mac != nil {
  453. return types.ForbiddenErrorf("endpoint interface MAC address present (%s). Cannot be modified with %s.", i.mac, mac)
  454. }
  455. if mac == nil {
  456. return types.BadRequestErrorf("tried to set nil MAC address to endpoint interface")
  457. }
  458. i.mac = types.GetMacCopy(mac)
  459. return nil
  460. }
  461. func (i *testInterface) SetIPAddress(address *net.IPNet) error {
  462. if address.IP == nil {
  463. return types.BadRequestErrorf("tried to set nil IP address to endpoint interface")
  464. }
  465. if address.IP.To4() == nil {
  466. return setAddress(&i.addrv6, address)
  467. }
  468. return setAddress(&i.addr, address)
  469. }
  470. func setAddress(ifaceAddr **net.IPNet, address *net.IPNet) error {
  471. if *ifaceAddr != nil {
  472. return types.ForbiddenErrorf("endpoint interface IP present (%s). Cannot be modified with (%s).", *ifaceAddr, address)
  473. }
  474. *ifaceAddr = types.GetIPNetCopy(address)
  475. return nil
  476. }
  477. func (i *testInterface) SetNames(srcName string, dstName string) error {
  478. i.srcName = srcName
  479. i.dstName = dstName
  480. return nil
  481. }
  482. func (te *testEndpoint) InterfaceName() driverapi.InterfaceNameInfo {
  483. if te.iface != nil {
  484. return te.iface
  485. }
  486. return nil
  487. }
  488. func (te *testEndpoint) SetGateway(gw net.IP) error {
  489. te.gw = gw
  490. return nil
  491. }
  492. func (te *testEndpoint) SetGatewayIPv6(gw6 net.IP) error {
  493. te.gw6 = gw6
  494. return nil
  495. }
  496. func (te *testEndpoint) AddStaticRoute(destination *net.IPNet, routeType int, nextHop net.IP) error {
  497. te.routes = append(te.routes, types.StaticRoute{Destination: destination, RouteType: routeType, NextHop: nextHop})
  498. return nil
  499. }
  500. func (te *testEndpoint) AddTableEntry(tableName string, key string, value []byte) error {
  501. return nil
  502. }
  503. func (te *testEndpoint) DisableGatewayService() {}
  504. func TestQueryEndpointInfo(t *testing.T) {
  505. testQueryEndpointInfo(t, true)
  506. }
  507. func TestQueryEndpointInfoHairpin(t *testing.T) {
  508. testQueryEndpointInfo(t, false)
  509. }
  510. func testQueryEndpointInfo(t *testing.T, ulPxyEnabled bool) {
  511. if !testutils.IsRunningInContainer() {
  512. defer testutils.SetupTestOSContext(t)()
  513. }
  514. d := newDriver()
  515. config := &configuration{
  516. EnableIPTables: true,
  517. EnableUserlandProxy: ulPxyEnabled,
  518. }
  519. genericOption := make(map[string]interface{})
  520. genericOption[netlabel.GenericData] = config
  521. if err := d.configure(genericOption); err != nil {
  522. t.Fatalf("Failed to setup driver config: %v", err)
  523. }
  524. netconfig := &networkConfiguration{
  525. BridgeName: DefaultBridgeName,
  526. EnableICC: false,
  527. }
  528. genericOption = make(map[string]interface{})
  529. genericOption[netlabel.GenericData] = netconfig
  530. ipdList := getIPv4Data(t, "")
  531. err := d.CreateNetwork("net1", genericOption, nil, ipdList, nil)
  532. if err != nil {
  533. t.Fatalf("Failed to create bridge: %v", err)
  534. }
  535. sbOptions := make(map[string]interface{})
  536. sbOptions[netlabel.PortMap] = getPortMapping()
  537. te := newTestEndpoint(ipdList[0].Pool, 11)
  538. err = d.CreateEndpoint("net1", "ep1", te.Interface(), nil)
  539. if err != nil {
  540. t.Fatalf("Failed to create an endpoint : %s", err.Error())
  541. }
  542. err = d.Join("net1", "ep1", "sbox", te, sbOptions)
  543. if err != nil {
  544. t.Fatalf("Failed to join the endpoint: %v", err)
  545. }
  546. err = d.ProgramExternalConnectivity("net1", "ep1", sbOptions)
  547. if err != nil {
  548. t.Fatalf("Failed to program external connectivity: %v", err)
  549. }
  550. network, ok := d.networks["net1"]
  551. if !ok {
  552. t.Fatalf("Cannot find network %s inside driver", "net1")
  553. }
  554. ep, _ := network.endpoints["ep1"]
  555. data, err := d.EndpointOperInfo(network.id, ep.id)
  556. if err != nil {
  557. t.Fatalf("Failed to ask for endpoint operational data: %v", err)
  558. }
  559. pmd, ok := data[netlabel.PortMap]
  560. if !ok {
  561. t.Fatal("Endpoint operational data does not contain port mapping data")
  562. }
  563. pm, ok := pmd.([]types.PortBinding)
  564. if !ok {
  565. t.Fatal("Unexpected format for port mapping in endpoint operational data")
  566. }
  567. if len(ep.portMapping) != len(pm) {
  568. t.Fatal("Incomplete data for port mapping in endpoint operational data")
  569. }
  570. for i, pb := range ep.portMapping {
  571. if !pb.Equal(&pm[i]) {
  572. t.Fatal("Unexpected data for port mapping in endpoint operational data")
  573. }
  574. }
  575. err = d.RevokeExternalConnectivity("net1", "ep1")
  576. if err != nil {
  577. t.Fatal(err)
  578. }
  579. // release host mapped ports
  580. err = d.Leave("net1", "ep1")
  581. if err != nil {
  582. t.Fatal(err)
  583. }
  584. }
  585. func getExposedPorts() []types.TransportPort {
  586. return []types.TransportPort{
  587. {Proto: types.TCP, Port: uint16(5000)},
  588. {Proto: types.UDP, Port: uint16(400)},
  589. {Proto: types.TCP, Port: uint16(600)},
  590. }
  591. }
  592. func getPortMapping() []types.PortBinding {
  593. return []types.PortBinding{
  594. {Proto: types.TCP, Port: uint16(230), HostPort: uint16(23000)},
  595. {Proto: types.UDP, Port: uint16(200), HostPort: uint16(22000)},
  596. {Proto: types.TCP, Port: uint16(120), HostPort: uint16(12000)},
  597. }
  598. }
  599. func TestLinkContainers(t *testing.T) {
  600. if !testutils.IsRunningInContainer() {
  601. defer testutils.SetupTestOSContext(t)()
  602. }
  603. d := newDriver()
  604. config := &configuration{
  605. EnableIPTables: true,
  606. }
  607. genericOption := make(map[string]interface{})
  608. genericOption[netlabel.GenericData] = config
  609. if err := d.configure(genericOption); err != nil {
  610. t.Fatalf("Failed to setup driver config: %v", err)
  611. }
  612. netconfig := &networkConfiguration{
  613. BridgeName: DefaultBridgeName,
  614. EnableICC: false,
  615. }
  616. genericOption = make(map[string]interface{})
  617. genericOption[netlabel.GenericData] = netconfig
  618. ipdList := getIPv4Data(t, "")
  619. err := d.CreateNetwork("net1", genericOption, nil, ipdList, nil)
  620. if err != nil {
  621. t.Fatalf("Failed to create bridge: %v", err)
  622. }
  623. te1 := newTestEndpoint(ipdList[0].Pool, 11)
  624. err = d.CreateEndpoint("net1", "ep1", te1.Interface(), nil)
  625. if err != nil {
  626. t.Fatalf("Failed to create an endpoint : %s", err.Error())
  627. }
  628. exposedPorts := getExposedPorts()
  629. sbOptions := make(map[string]interface{})
  630. sbOptions[netlabel.ExposedPorts] = exposedPorts
  631. err = d.Join("net1", "ep1", "sbox", te1, sbOptions)
  632. if err != nil {
  633. t.Fatalf("Failed to join the endpoint: %v", err)
  634. }
  635. err = d.ProgramExternalConnectivity("net1", "ep1", sbOptions)
  636. if err != nil {
  637. t.Fatalf("Failed to program external connectivity: %v", err)
  638. }
  639. addr1 := te1.iface.addr
  640. if addr1.IP.To4() == nil {
  641. t.Fatal("No Ipv4 address assigned to the endpoint: ep1")
  642. }
  643. te2 := newTestEndpoint(ipdList[0].Pool, 22)
  644. err = d.CreateEndpoint("net1", "ep2", te2.Interface(), nil)
  645. if err != nil {
  646. t.Fatalf("Failed to create an endpoint : %s", err.Error())
  647. }
  648. addr2 := te2.iface.addr
  649. if addr2.IP.To4() == nil {
  650. t.Fatal("No Ipv4 address assigned to the endpoint: ep2")
  651. }
  652. sbOptions = make(map[string]interface{})
  653. sbOptions[netlabel.GenericData] = options.Generic{
  654. "ChildEndpoints": []string{"ep1"},
  655. }
  656. err = d.Join("net1", "ep2", "", te2, sbOptions)
  657. if err != nil {
  658. t.Fatal("Failed to link ep1 and ep2")
  659. }
  660. err = d.ProgramExternalConnectivity("net1", "ep2", sbOptions)
  661. if err != nil {
  662. t.Fatalf("Failed to program external connectivity: %v", err)
  663. }
  664. out, err := iptables.Raw("-L", DockerChain)
  665. for _, pm := range exposedPorts {
  666. regex := fmt.Sprintf("%s dpt:%d", pm.Proto.String(), pm.Port)
  667. re := regexp.MustCompile(regex)
  668. matches := re.FindAllString(string(out[:]), -1)
  669. if len(matches) != 1 {
  670. t.Fatalf("IP Tables programming failed %s", string(out[:]))
  671. }
  672. regex = fmt.Sprintf("%s spt:%d", pm.Proto.String(), pm.Port)
  673. matched, _ := regexp.MatchString(regex, string(out[:]))
  674. if !matched {
  675. t.Fatalf("IP Tables programming failed %s", string(out[:]))
  676. }
  677. }
  678. err = d.RevokeExternalConnectivity("net1", "ep2")
  679. if err != nil {
  680. t.Fatalf("Failed to revoke external connectivity: %v", err)
  681. }
  682. err = d.Leave("net1", "ep2")
  683. if err != nil {
  684. t.Fatal("Failed to unlink ep1 and ep2")
  685. }
  686. out, err = iptables.Raw("-L", DockerChain)
  687. for _, pm := range exposedPorts {
  688. regex := fmt.Sprintf("%s dpt:%d", pm.Proto.String(), pm.Port)
  689. re := regexp.MustCompile(regex)
  690. matches := re.FindAllString(string(out[:]), -1)
  691. if len(matches) != 0 {
  692. t.Fatalf("Leave should have deleted relevant IPTables rules %s", string(out[:]))
  693. }
  694. regex = fmt.Sprintf("%s spt:%d", pm.Proto.String(), pm.Port)
  695. matched, _ := regexp.MatchString(regex, string(out[:]))
  696. if matched {
  697. t.Fatalf("Leave should have deleted relevant IPTables rules %s", string(out[:]))
  698. }
  699. }
  700. // Error condition test with an invalid endpoint-id "ep4"
  701. sbOptions = make(map[string]interface{})
  702. sbOptions[netlabel.GenericData] = options.Generic{
  703. "ChildEndpoints": []string{"ep1", "ep4"},
  704. }
  705. err = d.Join("net1", "ep2", "", te2, sbOptions)
  706. if err != nil {
  707. t.Fatal(err)
  708. }
  709. err = d.ProgramExternalConnectivity("net1", "ep2", sbOptions)
  710. if err != nil {
  711. out, err = iptables.Raw("-L", DockerChain)
  712. for _, pm := range exposedPorts {
  713. regex := fmt.Sprintf("%s dpt:%d", pm.Proto.String(), pm.Port)
  714. re := regexp.MustCompile(regex)
  715. matches := re.FindAllString(string(out[:]), -1)
  716. if len(matches) != 0 {
  717. t.Fatalf("Error handling should rollback relevant IPTables rules %s", string(out[:]))
  718. }
  719. regex = fmt.Sprintf("%s spt:%d", pm.Proto.String(), pm.Port)
  720. matched, _ := regexp.MatchString(regex, string(out[:]))
  721. if matched {
  722. t.Fatalf("Error handling should rollback relevant IPTables rules %s", string(out[:]))
  723. }
  724. }
  725. } else {
  726. t.Fatal("Expected Join to fail given link conditions are not satisfied")
  727. }
  728. }
  729. func TestValidateConfig(t *testing.T) {
  730. if !testutils.IsRunningInContainer() {
  731. defer testutils.SetupTestOSContext(t)()
  732. }
  733. // Test mtu
  734. c := networkConfiguration{Mtu: -2}
  735. err := c.Validate()
  736. if err == nil {
  737. t.Fatal("Failed to detect invalid MTU number")
  738. }
  739. c.Mtu = 9000
  740. err = c.Validate()
  741. if err != nil {
  742. t.Fatal("unexpected validation error on MTU number")
  743. }
  744. // Bridge network
  745. _, network, _ := net.ParseCIDR("172.28.0.0/16")
  746. c = networkConfiguration{
  747. AddressIPv4: network,
  748. }
  749. err = c.Validate()
  750. if err != nil {
  751. t.Fatal(err)
  752. }
  753. // Test v4 gw
  754. c.DefaultGatewayIPv4 = net.ParseIP("172.27.30.234")
  755. err = c.Validate()
  756. if err == nil {
  757. t.Fatal("Failed to detect invalid default gateway")
  758. }
  759. c.DefaultGatewayIPv4 = net.ParseIP("172.28.30.234")
  760. err = c.Validate()
  761. if err != nil {
  762. t.Fatal("Unexpected validation error on default gateway")
  763. }
  764. // Test v6 gw
  765. _, v6nw, _ := net.ParseCIDR("2001:db8:ae:b004::/64")
  766. c = networkConfiguration{
  767. EnableIPv6: true,
  768. AddressIPv6: v6nw,
  769. DefaultGatewayIPv6: net.ParseIP("2001:db8:ac:b004::bad:a55"),
  770. }
  771. err = c.Validate()
  772. if err == nil {
  773. t.Fatal("Failed to detect invalid v6 default gateway")
  774. }
  775. c.DefaultGatewayIPv6 = net.ParseIP("2001:db8:ae:b004::bad:a55")
  776. err = c.Validate()
  777. if err != nil {
  778. t.Fatal("Unexpected validation error on v6 default gateway")
  779. }
  780. c.AddressIPv6 = nil
  781. err = c.Validate()
  782. if err == nil {
  783. t.Fatal("Failed to detect invalid v6 default gateway")
  784. }
  785. c.AddressIPv6 = nil
  786. err = c.Validate()
  787. if err == nil {
  788. t.Fatal("Failed to detect invalid v6 default gateway")
  789. }
  790. }
  791. func TestSetDefaultGw(t *testing.T) {
  792. if !testutils.IsRunningInContainer() {
  793. defer testutils.SetupTestOSContext(t)()
  794. }
  795. d := newDriver()
  796. if err := d.configure(nil); err != nil {
  797. t.Fatalf("Failed to setup driver config: %v", err)
  798. }
  799. _, subnetv6, _ := net.ParseCIDR("2001:db8:ea9:9abc:b0c4::/80")
  800. ipdList := getIPv4Data(t, "")
  801. gw4 := types.GetIPCopy(ipdList[0].Pool.IP).To4()
  802. gw4[3] = 254
  803. gw6 := net.ParseIP("2001:db8:ea9:9abc:b0c4::254")
  804. config := &networkConfiguration{
  805. BridgeName: DefaultBridgeName,
  806. AddressIPv6: subnetv6,
  807. DefaultGatewayIPv4: gw4,
  808. DefaultGatewayIPv6: gw6,
  809. }
  810. genericOption := make(map[string]interface{})
  811. genericOption[netlabel.EnableIPv6] = true
  812. genericOption[netlabel.GenericData] = config
  813. err := d.CreateNetwork("dummy", genericOption, nil, ipdList, nil)
  814. if err != nil {
  815. t.Fatalf("Failed to create bridge: %v", err)
  816. }
  817. te := newTestEndpoint(ipdList[0].Pool, 10)
  818. err = d.CreateEndpoint("dummy", "ep", te.Interface(), nil)
  819. if err != nil {
  820. t.Fatalf("Failed to create endpoint: %v", err)
  821. }
  822. err = d.Join("dummy", "ep", "sbox", te, nil)
  823. if err != nil {
  824. t.Fatalf("Failed to join endpoint: %v", err)
  825. }
  826. if !gw4.Equal(te.gw) {
  827. t.Fatalf("Failed to configure default gateway. Expected %v. Found %v", gw4, te.gw)
  828. }
  829. if !gw6.Equal(te.gw6) {
  830. t.Fatalf("Failed to configure default gateway. Expected %v. Found %v", gw6, te.gw6)
  831. }
  832. }
  833. func TestCleanupIptableRules(t *testing.T) {
  834. defer testutils.SetupTestOSContext(t)()
  835. bridgeChain := []iptables.ChainInfo{
  836. {Name: DockerChain, Table: iptables.Nat},
  837. {Name: DockerChain, Table: iptables.Filter},
  838. {Name: IsolationChain1, Table: iptables.Filter},
  839. }
  840. if _, _, _, _, err := setupIPChains(&configuration{EnableIPTables: true}); err != nil {
  841. t.Fatalf("Error setting up ip chains: %v", err)
  842. }
  843. for _, chainInfo := range bridgeChain {
  844. if !iptables.ExistChain(chainInfo.Name, chainInfo.Table) {
  845. t.Fatalf("iptables chain %s of %s table should have been created", chainInfo.Name, chainInfo.Table)
  846. }
  847. }
  848. removeIPChains()
  849. for _, chainInfo := range bridgeChain {
  850. if iptables.ExistChain(chainInfo.Name, chainInfo.Table) {
  851. t.Fatalf("iptables chain %s of %s table should have been deleted", chainInfo.Name, chainInfo.Table)
  852. }
  853. }
  854. }
  855. func TestCreateWithExistingBridge(t *testing.T) {
  856. defer testutils.SetupTestOSContext(t)()
  857. d := newDriver()
  858. if err := d.configure(nil); err != nil {
  859. t.Fatalf("Failed to setup driver config: %v", err)
  860. }
  861. brName := "br111"
  862. br := &netlink.Bridge{
  863. LinkAttrs: netlink.LinkAttrs{
  864. Name: brName,
  865. },
  866. }
  867. if err := netlink.LinkAdd(br); err != nil {
  868. t.Fatalf("Failed to create bridge interface: %v", err)
  869. }
  870. defer netlink.LinkDel(br)
  871. if err := netlink.LinkSetUp(br); err != nil {
  872. t.Fatalf("Failed to set bridge interface up: %v", err)
  873. }
  874. ip := net.IP{192, 168, 122, 1}
  875. addr := &netlink.Addr{IPNet: &net.IPNet{
  876. IP: ip,
  877. Mask: net.IPv4Mask(255, 255, 255, 0),
  878. }}
  879. if err := netlink.AddrAdd(br, addr); err != nil {
  880. t.Fatalf("Failed to add IP address to bridge: %v", err)
  881. }
  882. netconfig := &networkConfiguration{BridgeName: brName}
  883. genericOption := make(map[string]interface{})
  884. genericOption[netlabel.GenericData] = netconfig
  885. if err := d.CreateNetwork(brName, genericOption, nil, getIPv4Data(t, brName), nil); err != nil {
  886. t.Fatalf("Failed to create bridge network: %v", err)
  887. }
  888. nw, err := d.getNetwork(brName)
  889. if err != nil {
  890. t.Fatalf("Failed to getNetwork(%s): %v", brName, err)
  891. }
  892. addrs4, _, err := nw.bridge.addresses()
  893. if err != nil {
  894. t.Fatalf("Failed to get the bridge network's address: %v", err)
  895. }
  896. if !addrs4[0].IP.Equal(ip) {
  897. t.Fatal("Creating bridge network with existing bridge interface unexpectedly modified the IP address of the bridge")
  898. }
  899. if err := d.DeleteNetwork(brName); err != nil {
  900. t.Fatalf("Failed to delete network %s: %v", brName, err)
  901. }
  902. if _, err := netlink.LinkByName(brName); err != nil {
  903. t.Fatal("Deleting bridge network that using existing bridge interface unexpectedly deleted the bridge interface")
  904. }
  905. }
  906. func TestCreateParallel(t *testing.T) {
  907. if !testutils.IsRunningInContainer() {
  908. defer testutils.SetupTestOSContext(t)()
  909. }
  910. d := newDriver()
  911. if err := d.configure(nil); err != nil {
  912. t.Fatalf("Failed to setup driver config: %v", err)
  913. }
  914. ch := make(chan error, 100)
  915. for i := 0; i < 100; i++ {
  916. go func(name string, ch chan<- error) {
  917. config := &networkConfiguration{BridgeName: name}
  918. genericOption := make(map[string]interface{})
  919. genericOption[netlabel.GenericData] = config
  920. if err := d.CreateNetwork(name, genericOption, nil, getIPv4Data(t, "docker0"), nil); err != nil {
  921. ch <- fmt.Errorf("failed to create %s", name)
  922. return
  923. }
  924. if err := d.CreateNetwork(name, genericOption, nil, getIPv4Data(t, "docker0"), nil); err == nil {
  925. ch <- fmt.Errorf("failed was able to create overlap %s", name)
  926. return
  927. }
  928. ch <- nil
  929. }("net"+strconv.Itoa(i), ch)
  930. }
  931. // wait for the go routines
  932. var success int
  933. for i := 0; i < 100; i++ {
  934. val := <-ch
  935. if val == nil {
  936. success++
  937. }
  938. }
  939. if success != 1 {
  940. t.Fatalf("Success should be 1 instead: %d", success)
  941. }
  942. }