driver_test.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614
  1. package remote
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "net"
  9. "net/http"
  10. "net/http/httptest"
  11. "os"
  12. "path/filepath"
  13. "runtime"
  14. "testing"
  15. "github.com/docker/docker/libnetwork/discoverapi"
  16. "github.com/docker/docker/libnetwork/driverapi"
  17. "github.com/docker/docker/libnetwork/scope"
  18. "github.com/docker/docker/libnetwork/types"
  19. "github.com/docker/docker/pkg/plugins"
  20. )
  21. func decodeToMap(r *http.Request) (res map[string]interface{}, err error) {
  22. err = json.NewDecoder(r.Body).Decode(&res)
  23. return
  24. }
  25. func handle(t *testing.T, mux *http.ServeMux, method string, h func(map[string]interface{}) interface{}) {
  26. mux.HandleFunc(fmt.Sprintf("/%s.%s", driverapi.NetworkPluginEndpointType, method), func(w http.ResponseWriter, r *http.Request) {
  27. ask, err := decodeToMap(r)
  28. if err != nil && err != io.EOF {
  29. t.Fatal(err)
  30. }
  31. answer := h(ask)
  32. err = json.NewEncoder(w).Encode(&answer)
  33. if err != nil {
  34. t.Fatal(err)
  35. }
  36. })
  37. }
  38. func setupPlugin(t *testing.T, name string, mux *http.ServeMux) func() {
  39. specPath := "/etc/docker/plugins"
  40. if runtime.GOOS == "windows" {
  41. specPath = filepath.Join(os.Getenv("programdata"), "docker", "plugins")
  42. }
  43. if err := os.MkdirAll(specPath, 0o755); err != nil {
  44. t.Fatal(err)
  45. }
  46. defer func() {
  47. if t.Failed() {
  48. _ = os.RemoveAll(specPath)
  49. }
  50. }()
  51. server := httptest.NewServer(mux)
  52. if server == nil {
  53. t.Fatal("Failed to start an HTTP Server")
  54. }
  55. if err := os.WriteFile(filepath.Join(specPath, name+".spec"), []byte(server.URL), 0o644); err != nil {
  56. t.Fatal(err)
  57. }
  58. mux.HandleFunc("/Plugin.Activate", func(w http.ResponseWriter, r *http.Request) {
  59. w.Header().Set("Content-Type", plugins.VersionMimetype)
  60. fmt.Fprintf(w, `{"Implements": ["%s"]}`, driverapi.NetworkPluginEndpointType)
  61. })
  62. return func() {
  63. if err := os.RemoveAll(specPath); err != nil {
  64. t.Fatal(err)
  65. }
  66. server.Close()
  67. }
  68. }
  69. type testEndpoint struct {
  70. t *testing.T
  71. src string
  72. dst string
  73. address string
  74. addressIPv6 string
  75. macAddress string
  76. gateway string
  77. gatewayIPv6 string
  78. resolvConfPath string
  79. hostsPath string
  80. nextHop string
  81. destination string
  82. routeType int
  83. disableGatewayService bool
  84. }
  85. func (test *testEndpoint) Address() *net.IPNet {
  86. if test.address == "" {
  87. return nil
  88. }
  89. nw, _ := types.ParseCIDR(test.address)
  90. return nw
  91. }
  92. func (test *testEndpoint) AddressIPv6() *net.IPNet {
  93. if test.addressIPv6 == "" {
  94. return nil
  95. }
  96. nw, _ := types.ParseCIDR(test.addressIPv6)
  97. return nw
  98. }
  99. func (test *testEndpoint) MacAddress() net.HardwareAddr {
  100. if test.macAddress == "" {
  101. return nil
  102. }
  103. mac, _ := net.ParseMAC(test.macAddress)
  104. return mac
  105. }
  106. func (test *testEndpoint) SetMacAddress(mac net.HardwareAddr) error {
  107. if test.macAddress != "" {
  108. return types.ForbiddenErrorf("endpoint interface MAC address present (%s). Cannot be modified with %s.", test.macAddress, mac)
  109. }
  110. if mac == nil {
  111. return types.InvalidParameterErrorf("tried to set nil MAC address to endpoint interface")
  112. }
  113. test.macAddress = mac.String()
  114. return nil
  115. }
  116. func (test *testEndpoint) SetIPAddress(address *net.IPNet) error {
  117. if address.IP == nil {
  118. return types.InvalidParameterErrorf("tried to set nil IP address to endpoint interface")
  119. }
  120. if address.IP.To4() == nil {
  121. return setAddress(&test.addressIPv6, address)
  122. }
  123. return setAddress(&test.address, address)
  124. }
  125. func setAddress(ifaceAddr *string, address *net.IPNet) error {
  126. if *ifaceAddr != "" {
  127. return types.ForbiddenErrorf("endpoint interface IP present (%s). Cannot be modified with (%s).", *ifaceAddr, address)
  128. }
  129. *ifaceAddr = address.String()
  130. return nil
  131. }
  132. func (test *testEndpoint) InterfaceName() driverapi.InterfaceNameInfo {
  133. return test
  134. }
  135. func compareIPs(t *testing.T, kind string, shouldBe string, supplied net.IP) {
  136. ip := net.ParseIP(shouldBe)
  137. if ip == nil {
  138. t.Fatalf(`Invalid IP to test against: "%s"`, shouldBe)
  139. }
  140. if !ip.Equal(supplied) {
  141. t.Fatalf(`%s IPs are not equal: expected "%s", got %v`, kind, shouldBe, supplied)
  142. }
  143. }
  144. func compareIPNets(t *testing.T, kind string, shouldBe string, supplied net.IPNet) {
  145. _, ipNet, _ := net.ParseCIDR(shouldBe)
  146. if ipNet == nil {
  147. t.Fatalf(`Invalid IP network to test against: "%s"`, shouldBe)
  148. }
  149. if !types.CompareIPNet(ipNet, &supplied) {
  150. t.Fatalf(`%s IP networks are not equal: expected "%s", got %v`, kind, shouldBe, supplied)
  151. }
  152. }
  153. func (test *testEndpoint) SetGateway(ipv4 net.IP) error {
  154. compareIPs(test.t, "Gateway", test.gateway, ipv4)
  155. return nil
  156. }
  157. func (test *testEndpoint) SetGatewayIPv6(ipv6 net.IP) error {
  158. compareIPs(test.t, "GatewayIPv6", test.gatewayIPv6, ipv6)
  159. return nil
  160. }
  161. func (test *testEndpoint) SetNames(src string, dst string) error {
  162. if test.src != src {
  163. test.t.Fatalf(`Wrong SrcName; expected "%s", got "%s"`, test.src, src)
  164. }
  165. if test.dst != dst {
  166. test.t.Fatalf(`Wrong DstPrefix; expected "%s", got "%s"`, test.dst, dst)
  167. }
  168. return nil
  169. }
  170. func (test *testEndpoint) AddStaticRoute(destination *net.IPNet, routeType int, nextHop net.IP) error {
  171. compareIPNets(test.t, "Destination", test.destination, *destination)
  172. compareIPs(test.t, "NextHop", test.nextHop, nextHop)
  173. if test.routeType != routeType {
  174. test.t.Fatalf(`Wrong RouteType; expected "%d", got "%d"`, test.routeType, routeType)
  175. }
  176. return nil
  177. }
  178. func (test *testEndpoint) DisableGatewayService() {
  179. test.disableGatewayService = true
  180. }
  181. func (test *testEndpoint) AddTableEntry(tableName string, key string, value []byte) error {
  182. return nil
  183. }
  184. func TestGetEmptyCapabilities(t *testing.T) {
  185. plugin := "test-net-driver-empty-cap"
  186. mux := http.NewServeMux()
  187. defer setupPlugin(t, plugin, mux)()
  188. handle(t, mux, "GetCapabilities", func(msg map[string]interface{}) interface{} {
  189. return map[string]interface{}{}
  190. })
  191. p, err := plugins.Get(plugin, driverapi.NetworkPluginEndpointType)
  192. if err != nil {
  193. t.Fatal(err)
  194. }
  195. client, err := getPluginClient(p)
  196. if err != nil {
  197. t.Fatal(err)
  198. }
  199. d := newDriver(plugin, client)
  200. if d.Type() != plugin {
  201. t.Fatal("Driver type does not match that given")
  202. }
  203. _, err = d.getCapabilities()
  204. if err == nil {
  205. t.Fatal("There should be error reported when get empty capability")
  206. }
  207. }
  208. func TestGetExtraCapabilities(t *testing.T) {
  209. plugin := "test-net-driver-extra-cap"
  210. mux := http.NewServeMux()
  211. defer setupPlugin(t, plugin, mux)()
  212. handle(t, mux, "GetCapabilities", func(msg map[string]interface{}) interface{} {
  213. return map[string]interface{}{
  214. "Scope": "local",
  215. "foo": "bar",
  216. "ConnectivityScope": "global",
  217. }
  218. })
  219. p, err := plugins.Get(plugin, driverapi.NetworkPluginEndpointType)
  220. if err != nil {
  221. t.Fatal(err)
  222. }
  223. client, err := getPluginClient(p)
  224. if err != nil {
  225. t.Fatal(err)
  226. }
  227. d := newDriver(plugin, client)
  228. if d.Type() != plugin {
  229. t.Fatal("Driver type does not match that given")
  230. }
  231. c, err := d.getCapabilities()
  232. if err != nil {
  233. t.Fatal(err)
  234. } else if c.DataScope != scope.Local {
  235. t.Fatalf("get capability '%s', expecting 'local'", c.DataScope)
  236. } else if c.ConnectivityScope != scope.Global {
  237. t.Fatalf("get capability '%s', expecting %q", c.ConnectivityScope, scope.Global)
  238. }
  239. }
  240. func TestGetInvalidCapabilities(t *testing.T) {
  241. plugin := "test-net-driver-invalid-cap"
  242. mux := http.NewServeMux()
  243. defer setupPlugin(t, plugin, mux)()
  244. handle(t, mux, "GetCapabilities", func(msg map[string]interface{}) interface{} {
  245. return map[string]interface{}{
  246. "Scope": "fake",
  247. }
  248. })
  249. p, err := plugins.Get(plugin, driverapi.NetworkPluginEndpointType)
  250. if err != nil {
  251. t.Fatal(err)
  252. }
  253. client, err := getPluginClient(p)
  254. if err != nil {
  255. t.Fatal(err)
  256. }
  257. d := newDriver(plugin, client)
  258. if d.Type() != plugin {
  259. t.Fatal("Driver type does not match that given")
  260. }
  261. _, err = d.getCapabilities()
  262. if err == nil {
  263. t.Fatal("There should be error reported when get invalid capability")
  264. }
  265. }
  266. func TestRemoteDriver(t *testing.T) {
  267. plugin := "test-net-driver"
  268. ep := &testEndpoint{
  269. t: t,
  270. src: "vethsrc",
  271. dst: "vethdst",
  272. address: "192.168.5.7/16",
  273. addressIPv6: "2001:DB8::5:7/48",
  274. macAddress: "ab:cd:ef:ee:ee:ee",
  275. gateway: "192.168.0.1",
  276. gatewayIPv6: "2001:DB8::1",
  277. hostsPath: "/here/comes/the/host/path",
  278. resolvConfPath: "/there/goes/the/resolv/conf",
  279. destination: "10.0.0.0/8",
  280. nextHop: "10.0.0.1",
  281. routeType: 1,
  282. }
  283. mux := http.NewServeMux()
  284. defer setupPlugin(t, plugin, mux)()
  285. var networkID string
  286. handle(t, mux, "GetCapabilities", func(msg map[string]interface{}) interface{} {
  287. return map[string]interface{}{
  288. "Scope": "global",
  289. }
  290. })
  291. handle(t, mux, "CreateNetwork", func(msg map[string]interface{}) interface{} {
  292. nid := msg["NetworkID"]
  293. var ok bool
  294. if networkID, ok = nid.(string); !ok {
  295. t.Fatal("RPC did not include network ID string")
  296. }
  297. return map[string]interface{}{}
  298. })
  299. handle(t, mux, "DeleteNetwork", func(msg map[string]interface{}) interface{} {
  300. if nid, ok := msg["NetworkID"]; !ok || nid != networkID {
  301. t.Fatal("Network ID missing or does not match that created")
  302. }
  303. return map[string]interface{}{}
  304. })
  305. handle(t, mux, "CreateEndpoint", func(msg map[string]interface{}) interface{} {
  306. iface := map[string]interface{}{
  307. "MacAddress": ep.macAddress,
  308. "Address": ep.address,
  309. "AddressIPv6": ep.addressIPv6,
  310. }
  311. return map[string]interface{}{
  312. "Interface": iface,
  313. }
  314. })
  315. handle(t, mux, "Join", func(msg map[string]interface{}) interface{} {
  316. options := msg["Options"].(map[string]interface{})
  317. foo, ok := options["foo"].(string)
  318. if !ok || foo != "fooValue" {
  319. t.Fatalf("Did not receive expected foo string in request options: %+v", msg)
  320. }
  321. return map[string]interface{}{
  322. "Gateway": ep.gateway,
  323. "GatewayIPv6": ep.gatewayIPv6,
  324. "HostsPath": ep.hostsPath,
  325. "ResolvConfPath": ep.resolvConfPath,
  326. "InterfaceName": map[string]interface{}{
  327. "SrcName": ep.src,
  328. "DstPrefix": ep.dst,
  329. },
  330. "StaticRoutes": []map[string]interface{}{
  331. {
  332. "Destination": ep.destination,
  333. "RouteType": ep.routeType,
  334. "NextHop": ep.nextHop,
  335. },
  336. },
  337. }
  338. })
  339. handle(t, mux, "Leave", func(msg map[string]interface{}) interface{} {
  340. return map[string]string{}
  341. })
  342. handle(t, mux, "DeleteEndpoint", func(msg map[string]interface{}) interface{} {
  343. return map[string]interface{}{}
  344. })
  345. handle(t, mux, "EndpointOperInfo", func(msg map[string]interface{}) interface{} {
  346. return map[string]interface{}{
  347. "Value": map[string]string{
  348. "Arbitrary": "key",
  349. "Value": "pairs?",
  350. },
  351. }
  352. })
  353. handle(t, mux, "DiscoverNew", func(msg map[string]interface{}) interface{} {
  354. return map[string]string{}
  355. })
  356. handle(t, mux, "DiscoverDelete", func(msg map[string]interface{}) interface{} {
  357. return map[string]interface{}{}
  358. })
  359. p, err := plugins.Get(plugin, driverapi.NetworkPluginEndpointType)
  360. if err != nil {
  361. t.Fatal(err)
  362. }
  363. client, err := getPluginClient(p)
  364. if err != nil {
  365. t.Fatal(err)
  366. }
  367. d := newDriver(plugin, client)
  368. if d.Type() != plugin {
  369. t.Fatal("Driver type does not match that given")
  370. }
  371. c, err := d.getCapabilities()
  372. if err != nil {
  373. t.Fatal(err)
  374. } else if c.DataScope != scope.Global {
  375. t.Fatalf("get capability '%s', expecting 'global'", c.DataScope)
  376. }
  377. netID := "dummy-network"
  378. err = d.CreateNetwork(netID, map[string]interface{}{}, nil, nil, nil)
  379. if err != nil {
  380. t.Fatal(err)
  381. }
  382. endID := "dummy-endpoint"
  383. ifInfo := &testEndpoint{}
  384. err = d.CreateEndpoint(netID, endID, ifInfo, map[string]interface{}{})
  385. if err != nil {
  386. t.Fatal(err)
  387. }
  388. if !bytes.Equal(ep.MacAddress(), ifInfo.MacAddress()) || !types.CompareIPNet(ep.Address(), ifInfo.Address()) ||
  389. !types.CompareIPNet(ep.AddressIPv6(), ifInfo.AddressIPv6()) {
  390. t.Fatalf("Unexpected InterfaceInfo data. Expected (%s, %s, %s). Got (%v, %v, %v)",
  391. ep.MacAddress(), ep.Address(), ep.AddressIPv6(),
  392. ifInfo.MacAddress(), ifInfo.Address(), ifInfo.AddressIPv6())
  393. }
  394. joinOpts := map[string]interface{}{"foo": "fooValue"}
  395. err = d.Join(netID, endID, "sandbox-key", ep, joinOpts)
  396. if err != nil {
  397. t.Fatal(err)
  398. }
  399. if _, err = d.EndpointOperInfo(netID, endID); err != nil {
  400. t.Fatal(err)
  401. }
  402. if err = d.Leave(netID, endID); err != nil {
  403. t.Fatal(err)
  404. }
  405. if err = d.DeleteEndpoint(netID, endID); err != nil {
  406. t.Fatal(err)
  407. }
  408. if err = d.DeleteNetwork(netID); err != nil {
  409. t.Fatal(err)
  410. }
  411. data := discoverapi.NodeDiscoveryData{
  412. Address: "192.168.1.1",
  413. }
  414. if err = d.DiscoverNew(discoverapi.NodeDiscovery, data); err != nil {
  415. t.Fatal(err)
  416. }
  417. if err = d.DiscoverDelete(discoverapi.NodeDiscovery, data); err != nil {
  418. t.Fatal(err)
  419. }
  420. }
  421. func TestDriverError(t *testing.T) {
  422. plugin := "test-net-driver-error"
  423. mux := http.NewServeMux()
  424. defer setupPlugin(t, plugin, mux)()
  425. handle(t, mux, "CreateEndpoint", func(msg map[string]interface{}) interface{} {
  426. return map[string]interface{}{
  427. "Err": "this should get raised as an error",
  428. }
  429. })
  430. p, err := plugins.Get(plugin, driverapi.NetworkPluginEndpointType)
  431. if err != nil {
  432. t.Fatal(err)
  433. }
  434. client, err := getPluginClient(p)
  435. if err != nil {
  436. t.Fatal(err)
  437. }
  438. d := newDriver(plugin, client)
  439. if err := d.CreateEndpoint("dummy", "dummy", &testEndpoint{t: t}, map[string]interface{}{}); err == nil {
  440. t.Fatal("Expected error from driver")
  441. }
  442. }
  443. func TestMissingValues(t *testing.T) {
  444. plugin := "test-net-driver-missing"
  445. mux := http.NewServeMux()
  446. defer setupPlugin(t, plugin, mux)()
  447. ep := &testEndpoint{
  448. t: t,
  449. }
  450. handle(t, mux, "CreateEndpoint", func(msg map[string]interface{}) interface{} {
  451. iface := map[string]interface{}{
  452. "Address": ep.address,
  453. "AddressIPv6": ep.addressIPv6,
  454. "MacAddress": ep.macAddress,
  455. }
  456. return map[string]interface{}{
  457. "Interface": iface,
  458. }
  459. })
  460. p, err := plugins.Get(plugin, driverapi.NetworkPluginEndpointType)
  461. if err != nil {
  462. t.Fatal(err)
  463. }
  464. client, err := getPluginClient(p)
  465. if err != nil {
  466. t.Fatal(err)
  467. }
  468. d := newDriver(plugin, client)
  469. if err := d.CreateEndpoint("dummy", "dummy", ep, map[string]interface{}{}); err != nil {
  470. t.Fatal(err)
  471. }
  472. }
  473. type rollbackEndpoint struct{}
  474. func (r *rollbackEndpoint) Interface() *rollbackEndpoint {
  475. return r
  476. }
  477. func (r *rollbackEndpoint) MacAddress() net.HardwareAddr {
  478. return nil
  479. }
  480. func (r *rollbackEndpoint) Address() *net.IPNet {
  481. return nil
  482. }
  483. func (r *rollbackEndpoint) AddressIPv6() *net.IPNet {
  484. return nil
  485. }
  486. func (r *rollbackEndpoint) SetMacAddress(mac net.HardwareAddr) error {
  487. return errors.New("invalid mac")
  488. }
  489. func (r *rollbackEndpoint) SetIPAddress(ip *net.IPNet) error {
  490. return errors.New("invalid ip")
  491. }
  492. func TestRollback(t *testing.T) {
  493. plugin := "test-net-driver-rollback"
  494. mux := http.NewServeMux()
  495. defer setupPlugin(t, plugin, mux)()
  496. rolledback := false
  497. handle(t, mux, "CreateEndpoint", func(msg map[string]interface{}) interface{} {
  498. iface := map[string]interface{}{
  499. "Address": "192.168.4.5/16",
  500. "AddressIPv6": "",
  501. "MacAddress": "7a:12:34:56:78:90",
  502. }
  503. return map[string]interface{}{
  504. "Interface": interface{}(iface),
  505. }
  506. })
  507. handle(t, mux, "DeleteEndpoint", func(msg map[string]interface{}) interface{} {
  508. rolledback = true
  509. return map[string]interface{}{}
  510. })
  511. p, err := plugins.Get(plugin, driverapi.NetworkPluginEndpointType)
  512. if err != nil {
  513. t.Fatal(err)
  514. }
  515. client, err := getPluginClient(p)
  516. if err != nil {
  517. t.Fatal(err)
  518. }
  519. d := newDriver(plugin, client)
  520. ep := &rollbackEndpoint{}
  521. if err := d.CreateEndpoint("dummy", "dummy", ep.Interface(), map[string]interface{}{}); err == nil {
  522. t.Fatal("Expected error from driver")
  523. }
  524. if !rolledback {
  525. t.Fatal("Expected to have had DeleteEndpoint called")
  526. }
  527. }