bridge_test.go 30 KB

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