bridge_test.go 29 KB

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