allocator_test.go 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554
  1. package ipam
  2. import (
  3. "encoding/json"
  4. "flag"
  5. "fmt"
  6. "math/rand"
  7. "net"
  8. "os"
  9. "path/filepath"
  10. "strconv"
  11. "sync"
  12. "testing"
  13. "time"
  14. "github.com/docker/docker/libnetwork/bitseq"
  15. "github.com/docker/docker/libnetwork/datastore"
  16. "github.com/docker/docker/libnetwork/ipamapi"
  17. "github.com/docker/docker/libnetwork/types"
  18. "github.com/docker/libkv/store"
  19. "github.com/docker/libkv/store/boltdb"
  20. "golang.org/x/sync/errgroup"
  21. "gotest.tools/v3/assert"
  22. is "gotest.tools/v3/assert/cmp"
  23. )
  24. var (
  25. defaultPrefix = filepath.Join(os.TempDir(), "libnetwork", "test", "ipam")
  26. )
  27. func init() {
  28. boltdb.Register()
  29. }
  30. // OptionBoltdbWithRandomDBFile function returns a random dir for local store backend
  31. func randomLocalStore(needStore bool) (datastore.DataStore, error) {
  32. if !needStore {
  33. return nil, nil
  34. }
  35. tmp, err := os.CreateTemp("", "libnetwork-")
  36. if err != nil {
  37. return nil, fmt.Errorf("Error creating temp file: %v", err)
  38. }
  39. if err := tmp.Close(); err != nil {
  40. return nil, fmt.Errorf("Error closing temp file: %v", err)
  41. }
  42. return datastore.NewDataStore(datastore.LocalScope, &datastore.ScopeCfg{
  43. Client: datastore.ScopeClientCfg{
  44. Provider: "boltdb",
  45. Address: filepath.Join(defaultPrefix, filepath.Base(tmp.Name())),
  46. Config: &store.Config{
  47. Bucket: "libnetwork",
  48. ConnectionTimeout: 3 * time.Second,
  49. },
  50. },
  51. })
  52. }
  53. func getAllocator(store bool) (*Allocator, error) {
  54. ds, err := randomLocalStore(store)
  55. if err != nil {
  56. return nil, err
  57. }
  58. return NewAllocator(ds, nil)
  59. }
  60. func TestInt2IP2IntConversion(t *testing.T) {
  61. for i := uint64(0); i < 256*256*256; i++ {
  62. var array [4]byte // new array at each cycle
  63. addIntToIP(array[:], i)
  64. j := ipToUint64(array[:])
  65. if j != i {
  66. t.Fatalf("Failed to convert ordinal %d to IP % x and back to ordinal. Got %d", i, array, j)
  67. }
  68. }
  69. }
  70. func TestGetAddressVersion(t *testing.T) {
  71. if v4 != getAddressVersion(net.ParseIP("172.28.30.112")) {
  72. t.Fatal("Failed to detect IPv4 version")
  73. }
  74. if v4 != getAddressVersion(net.ParseIP("0.0.0.1")) {
  75. t.Fatal("Failed to detect IPv4 version")
  76. }
  77. if v6 != getAddressVersion(net.ParseIP("ff01::1")) {
  78. t.Fatal("Failed to detect IPv6 version")
  79. }
  80. if v6 != getAddressVersion(net.ParseIP("2001:db8::76:51")) {
  81. t.Fatal("Failed to detect IPv6 version")
  82. }
  83. }
  84. func TestKeyString(t *testing.T) {
  85. k := &SubnetKey{AddressSpace: "default", Subnet: "172.27.0.0/16"}
  86. expected := "default/172.27.0.0/16"
  87. if expected != k.String() {
  88. t.Fatalf("Unexpected key string: %s", k.String())
  89. }
  90. k2 := &SubnetKey{}
  91. err := k2.FromString(expected)
  92. if err != nil {
  93. t.Fatal(err)
  94. }
  95. if k2.AddressSpace != k.AddressSpace || k2.Subnet != k.Subnet {
  96. t.Fatalf("SubnetKey.FromString() failed. Expected %v. Got %v", k, k2)
  97. }
  98. expected = fmt.Sprintf("%s/%s", expected, "172.27.3.0/24")
  99. k.ChildSubnet = "172.27.3.0/24"
  100. if expected != k.String() {
  101. t.Fatalf("Unexpected key string: %s", k.String())
  102. }
  103. err = k2.FromString(expected)
  104. if err != nil {
  105. t.Fatal(err)
  106. }
  107. if k2.AddressSpace != k.AddressSpace || k2.Subnet != k.Subnet || k2.ChildSubnet != k.ChildSubnet {
  108. t.Fatalf("SubnetKey.FromString() failed. Expected %v. Got %v", k, k2)
  109. }
  110. }
  111. func TestPoolDataMarshal(t *testing.T) {
  112. _, nw, err := net.ParseCIDR("172.28.30.1/24")
  113. if err != nil {
  114. t.Fatal(err)
  115. }
  116. p := &PoolData{
  117. ParentKey: SubnetKey{AddressSpace: "Blue", Subnet: "172.28.0.0/16"},
  118. Pool: nw,
  119. Range: &AddressRange{Sub: &net.IPNet{IP: net.IP{172, 28, 20, 0}, Mask: net.IPMask{255, 255, 255, 0}}, Start: 0, End: 255},
  120. RefCount: 4,
  121. }
  122. ba, err := json.Marshal(p)
  123. if err != nil {
  124. t.Fatal(err)
  125. }
  126. var q PoolData
  127. err = json.Unmarshal(ba, &q)
  128. if err != nil {
  129. t.Fatal(err)
  130. }
  131. if p.ParentKey != q.ParentKey || !types.CompareIPNet(p.Range.Sub, q.Range.Sub) ||
  132. p.Range.Start != q.Range.Start || p.Range.End != q.Range.End || p.RefCount != q.RefCount ||
  133. !types.CompareIPNet(p.Pool, q.Pool) {
  134. t.Fatalf("\n%#v\n%#v", p, &q)
  135. }
  136. p = &PoolData{
  137. ParentKey: SubnetKey{AddressSpace: "Blue", Subnet: "172.28.0.0/16"},
  138. Pool: nw,
  139. RefCount: 4,
  140. }
  141. ba, err = json.Marshal(p)
  142. if err != nil {
  143. t.Fatal(err)
  144. }
  145. err = json.Unmarshal(ba, &q)
  146. if err != nil {
  147. t.Fatal(err)
  148. }
  149. if q.Range != nil {
  150. t.Fatal("Unexpected Range")
  151. }
  152. }
  153. func TestSubnetsMarshal(t *testing.T) {
  154. for _, store := range []bool{false, true} {
  155. a, err := getAllocator(store)
  156. if err != nil {
  157. t.Fatal(err)
  158. }
  159. pid0, _, _, err := a.RequestPool(localAddressSpace, "192.168.0.0/16", "", nil, false)
  160. if err != nil {
  161. t.Fatal(err)
  162. }
  163. pid1, _, _, err := a.RequestPool(localAddressSpace, "192.169.0.0/16", "", nil, false)
  164. if err != nil {
  165. t.Fatal(err)
  166. }
  167. _, _, err = a.RequestAddress(pid0, nil, nil)
  168. if err != nil {
  169. t.Fatal(err)
  170. }
  171. cfg, err := a.getAddrSpace(localAddressSpace)
  172. if err != nil {
  173. t.Fatal(err)
  174. }
  175. ba := cfg.Value()
  176. if err := cfg.SetValue(ba); err != nil {
  177. t.Fatal(err)
  178. }
  179. expIP := &net.IPNet{IP: net.IP{192, 168, 0, 2}, Mask: net.IPMask{255, 255, 0, 0}}
  180. ip, _, err := a.RequestAddress(pid0, nil, nil)
  181. if err != nil {
  182. t.Fatal(err)
  183. }
  184. if !types.CompareIPNet(expIP, ip) {
  185. t.Fatalf("Got unexpected ip after pool config restore: %s", ip)
  186. }
  187. expIP = &net.IPNet{IP: net.IP{192, 169, 0, 1}, Mask: net.IPMask{255, 255, 0, 0}}
  188. ip, _, err = a.RequestAddress(pid1, nil, nil)
  189. if err != nil {
  190. t.Fatal(err)
  191. }
  192. if !types.CompareIPNet(expIP, ip) {
  193. t.Fatalf("Got unexpected ip after pool config restore: %s", ip)
  194. }
  195. }
  196. }
  197. func TestAddSubnets(t *testing.T) {
  198. for _, store := range []bool{false, true} {
  199. a, err := getAllocator(store)
  200. if err != nil {
  201. t.Fatal(err)
  202. }
  203. a.addrSpaces["abc"] = a.addrSpaces[localAddressSpace]
  204. pid0, _, _, err := a.RequestPool(localAddressSpace, "10.0.0.0/8", "", nil, false)
  205. if err != nil {
  206. t.Fatal("Unexpected failure in adding subnet")
  207. }
  208. pid1, _, _, err := a.RequestPool("abc", "10.0.0.0/8", "", nil, false)
  209. if err != nil {
  210. t.Fatalf("Unexpected failure in adding overlapping subnets to different address spaces: %v", err)
  211. }
  212. if pid0 == pid1 {
  213. t.Fatal("returned same pool id for same subnets in different namespaces")
  214. }
  215. _, _, _, err = a.RequestPool("abc", "10.0.0.0/8", "", nil, false)
  216. if err == nil {
  217. t.Fatalf("Expected failure requesting existing subnet")
  218. }
  219. _, _, _, err = a.RequestPool("abc", "10.128.0.0/9", "", nil, false)
  220. if err == nil {
  221. t.Fatal("Expected failure on adding overlapping base subnet")
  222. }
  223. _, _, _, err = a.RequestPool("abc", "10.0.0.0/8", "10.128.0.0/9", nil, false)
  224. if err != nil {
  225. t.Fatalf("Unexpected failure on adding sub pool: %v", err)
  226. }
  227. _, _, _, err = a.RequestPool("abc", "10.0.0.0/8", "10.128.0.0/9", nil, false)
  228. if err == nil {
  229. t.Fatalf("Expected failure on adding overlapping sub pool")
  230. }
  231. _, _, _, err = a.RequestPool(localAddressSpace, "10.20.2.0/24", "", nil, false)
  232. if err == nil {
  233. t.Fatal("Failed to detect overlapping subnets")
  234. }
  235. _, _, _, err = a.RequestPool(localAddressSpace, "10.128.0.0/9", "", nil, false)
  236. if err == nil {
  237. t.Fatal("Failed to detect overlapping subnets")
  238. }
  239. _, _, _, err = a.RequestPool(localAddressSpace, "1003:1:2:3:4:5:6::/112", "", nil, false)
  240. if err != nil {
  241. t.Fatalf("Failed to add v6 subnet: %s", err.Error())
  242. }
  243. _, _, _, err = a.RequestPool(localAddressSpace, "1003:1:2:3::/64", "", nil, false)
  244. if err == nil {
  245. t.Fatal("Failed to detect overlapping v6 subnet")
  246. }
  247. }
  248. }
  249. // TestDoublePoolRelease tests that releasing a pool which has already
  250. // been released raises an error.
  251. func TestDoublePoolRelease(t *testing.T) {
  252. for _, store := range []bool{false, true} {
  253. a, err := getAllocator(store)
  254. assert.NilError(t, err)
  255. pid0, _, _, err := a.RequestPool(localAddressSpace, "10.0.0.0/8", "", nil, false)
  256. assert.NilError(t, err)
  257. err = a.ReleasePool(pid0)
  258. assert.NilError(t, err)
  259. err = a.ReleasePool(pid0)
  260. assert.Check(t, is.ErrorContains(err, ""))
  261. }
  262. }
  263. func TestAddReleasePoolID(t *testing.T) {
  264. for _, store := range []bool{false, true} {
  265. a, err := getAllocator(store)
  266. assert.NilError(t, err)
  267. var k0, k1 SubnetKey
  268. _, err = a.getAddrSpace(localAddressSpace)
  269. if err != nil {
  270. t.Fatal(err)
  271. }
  272. pid0, _, _, err := a.RequestPool(localAddressSpace, "10.0.0.0/8", "", nil, false)
  273. if err != nil {
  274. t.Fatal("Unexpected failure in adding pool")
  275. }
  276. if err := k0.FromString(pid0); err != nil {
  277. t.Fatal(err)
  278. }
  279. aSpace, err := a.getAddrSpace(localAddressSpace)
  280. if err != nil {
  281. t.Fatal(err)
  282. }
  283. subnets := aSpace.subnets
  284. if subnets[k0].RefCount != 1 {
  285. t.Fatalf("Unexpected ref count for %s: %d", k0, subnets[k0].RefCount)
  286. }
  287. pid1, _, _, err := a.RequestPool(localAddressSpace, "10.0.0.0/8", "10.0.0.0/16", nil, false)
  288. if err != nil {
  289. t.Fatal("Unexpected failure in adding sub pool")
  290. }
  291. if err := k1.FromString(pid1); err != nil {
  292. t.Fatal(err)
  293. }
  294. if pid0 == pid1 {
  295. t.Fatalf("Incorrect poolIDs returned %s, %s", pid0, pid1)
  296. }
  297. aSpace, err = a.getAddrSpace(localAddressSpace)
  298. if err != nil {
  299. t.Fatal(err)
  300. }
  301. subnets = aSpace.subnets
  302. if subnets[k1].RefCount != 1 {
  303. t.Fatalf("Unexpected ref count for %s: %d", k1, subnets[k1].RefCount)
  304. }
  305. _, _, _, err = a.RequestPool(localAddressSpace, "10.0.0.0/8", "10.0.0.0/16", nil, false)
  306. if err == nil {
  307. t.Fatal("Expected failure in adding sub pool")
  308. }
  309. aSpace, err = a.getAddrSpace(localAddressSpace)
  310. if err != nil {
  311. t.Fatal(err)
  312. }
  313. subnets = aSpace.subnets
  314. if subnets[k0].RefCount != 2 {
  315. t.Fatalf("Unexpected ref count for %s: %d", k0, subnets[k0].RefCount)
  316. }
  317. if err := a.ReleasePool(pid1); err != nil {
  318. t.Fatal(err)
  319. }
  320. aSpace, err = a.getAddrSpace(localAddressSpace)
  321. if err != nil {
  322. t.Fatal(err)
  323. }
  324. subnets = aSpace.subnets
  325. if subnets[k0].RefCount != 1 {
  326. t.Fatalf("Unexpected ref count for %s: %d", k0, subnets[k0].RefCount)
  327. }
  328. if err := a.ReleasePool(pid0); err != nil {
  329. t.Fatal(err)
  330. }
  331. pid00, _, _, err := a.RequestPool(localAddressSpace, "10.0.0.0/8", "", nil, false)
  332. if err != nil {
  333. t.Fatal("Unexpected failure in adding pool")
  334. }
  335. if pid00 != pid0 {
  336. t.Fatal("main pool should still exist")
  337. }
  338. aSpace, err = a.getAddrSpace(localAddressSpace)
  339. if err != nil {
  340. t.Fatal(err)
  341. }
  342. subnets = aSpace.subnets
  343. if subnets[k0].RefCount != 1 {
  344. t.Fatalf("Unexpected ref count for %s: %d", k0, subnets[k0].RefCount)
  345. }
  346. if err := a.ReleasePool(pid00); err != nil {
  347. t.Fatal(err)
  348. }
  349. aSpace, err = a.getAddrSpace(localAddressSpace)
  350. if err != nil {
  351. t.Fatal(err)
  352. }
  353. subnets = aSpace.subnets
  354. if bp, ok := subnets[k0]; ok {
  355. t.Fatalf("Base pool %s is still present: %v", k0, bp)
  356. }
  357. _, _, _, err = a.RequestPool(localAddressSpace, "10.0.0.0/8", "", nil, false)
  358. if err != nil {
  359. t.Fatal("Unexpected failure in adding pool")
  360. }
  361. aSpace, err = a.getAddrSpace(localAddressSpace)
  362. if err != nil {
  363. t.Fatal(err)
  364. }
  365. subnets = aSpace.subnets
  366. if subnets[k0].RefCount != 1 {
  367. t.Fatalf("Unexpected ref count for %s: %d", k0, subnets[k0].RefCount)
  368. }
  369. }
  370. }
  371. func TestPredefinedPool(t *testing.T) {
  372. for _, store := range []bool{false, true} {
  373. a, err := getAllocator(store)
  374. assert.NilError(t, err)
  375. if _, err := a.getPredefinedPool("blue", false); err == nil {
  376. t.Fatal("Expected failure for non default addr space")
  377. }
  378. pid, nw, _, err := a.RequestPool(localAddressSpace, "", "", nil, false)
  379. if err != nil {
  380. t.Fatal(err)
  381. }
  382. nw2, err := a.getPredefinedPool(localAddressSpace, false)
  383. if err != nil {
  384. t.Fatal(err)
  385. }
  386. if types.CompareIPNet(nw, nw2) {
  387. t.Fatalf("Unexpected default network returned: %s = %s", nw2, nw)
  388. }
  389. if err := a.ReleasePool(pid); err != nil {
  390. t.Fatal(err)
  391. }
  392. }
  393. }
  394. func TestRemoveSubnet(t *testing.T) {
  395. for _, store := range []bool{false, true} {
  396. a, err := getAllocator(store)
  397. assert.NilError(t, err)
  398. a.addrSpaces["splane"] = &addrSpace{
  399. id: dsConfigKey + "/" + "splane",
  400. ds: a.addrSpaces[localAddressSpace].ds,
  401. alloc: a.addrSpaces[localAddressSpace].alloc,
  402. scope: a.addrSpaces[localAddressSpace].scope,
  403. subnets: map[SubnetKey]*PoolData{},
  404. }
  405. input := []struct {
  406. addrSpace string
  407. subnet string
  408. v6 bool
  409. }{
  410. {localAddressSpace, "192.168.0.0/16", false},
  411. {localAddressSpace, "172.17.0.0/16", false},
  412. {localAddressSpace, "10.0.0.0/8", false},
  413. {localAddressSpace, "2001:db8:1:2:3:4:ffff::/112", false},
  414. {"splane", "172.17.0.0/16", false},
  415. {"splane", "10.0.0.0/8", false},
  416. {"splane", "2001:db8:1:2:3:4:5::/112", true},
  417. {"splane", "2001:db8:1:2:3:4:ffff::/112", true},
  418. }
  419. poolIDs := make([]string, len(input))
  420. for ind, i := range input {
  421. if poolIDs[ind], _, _, err = a.RequestPool(i.addrSpace, i.subnet, "", nil, i.v6); err != nil {
  422. t.Fatalf("Failed to apply input. Can't proceed: %s", err.Error())
  423. }
  424. }
  425. for ind, id := range poolIDs {
  426. if err := a.ReleasePool(id); err != nil {
  427. t.Fatalf("Failed to release poolID %s (%d)", id, ind)
  428. }
  429. }
  430. }
  431. }
  432. func TestGetSameAddress(t *testing.T) {
  433. for _, store := range []bool{false, true} {
  434. a, err := getAllocator(store)
  435. assert.NilError(t, err)
  436. a.addrSpaces["giallo"] = &addrSpace{
  437. id: dsConfigKey + "/" + "giallo",
  438. ds: a.addrSpaces[localAddressSpace].ds,
  439. alloc: a.addrSpaces[localAddressSpace].alloc,
  440. scope: a.addrSpaces[localAddressSpace].scope,
  441. subnets: map[SubnetKey]*PoolData{},
  442. }
  443. pid, _, _, err := a.RequestPool("giallo", "192.168.100.0/24", "", nil, false)
  444. if err != nil {
  445. t.Fatal(err)
  446. }
  447. ip := net.ParseIP("192.168.100.250")
  448. _, _, err = a.RequestAddress(pid, ip, nil)
  449. if err != nil {
  450. t.Fatal(err)
  451. }
  452. _, _, err = a.RequestAddress(pid, ip, nil)
  453. if err == nil {
  454. t.Fatal(err)
  455. }
  456. }
  457. }
  458. func TestPoolAllocationReuse(t *testing.T) {
  459. for _, store := range []bool{false, true} {
  460. a, err := getAllocator(store)
  461. assert.NilError(t, err)
  462. // First get all pools until they are exhausted to
  463. pList := []string{}
  464. pool, _, _, err := a.RequestPool(localAddressSpace, "", "", nil, false)
  465. for err == nil {
  466. pList = append(pList, pool)
  467. pool, _, _, err = a.RequestPool(localAddressSpace, "", "", nil, false)
  468. }
  469. nPools := len(pList)
  470. for _, pool := range pList {
  471. if err := a.ReleasePool(pool); err != nil {
  472. t.Fatal(err)
  473. }
  474. }
  475. // Now try to allocate then free nPool pools sequentially.
  476. // Verify that we don't see any repeat networks even though
  477. // we have freed them.
  478. seen := map[string]bool{}
  479. for i := 0; i < nPools; i++ {
  480. pool, nw, _, err := a.RequestPool(localAddressSpace, "", "", nil, false)
  481. if err != nil {
  482. t.Fatal(err)
  483. }
  484. if _, ok := seen[nw.String()]; ok {
  485. t.Fatalf("Network %s was reused before exhausing the pool list", nw.String())
  486. }
  487. seen[nw.String()] = true
  488. if err := a.ReleasePool(pool); err != nil {
  489. t.Fatal(err)
  490. }
  491. }
  492. }
  493. }
  494. func TestGetAddressSubPoolEqualPool(t *testing.T) {
  495. for _, store := range []bool{false, true} {
  496. a, err := getAllocator(store)
  497. assert.NilError(t, err)
  498. // Requesting a subpool of same size of the master pool should not cause any problem on ip allocation
  499. pid, _, _, err := a.RequestPool(localAddressSpace, "172.18.0.0/16", "172.18.0.0/16", nil, false)
  500. if err != nil {
  501. t.Fatal(err)
  502. }
  503. _, _, err = a.RequestAddress(pid, nil, nil)
  504. if err != nil {
  505. t.Fatal(err)
  506. }
  507. }
  508. }
  509. func TestRequestReleaseAddressFromSubPool(t *testing.T) {
  510. for _, store := range []bool{false, true} {
  511. a, err := getAllocator(store)
  512. assert.NilError(t, err)
  513. a.addrSpaces["rosso"] = &addrSpace{
  514. id: dsConfigKey + "/" + "rosso",
  515. ds: a.addrSpaces[localAddressSpace].ds,
  516. alloc: a.addrSpaces[localAddressSpace].alloc,
  517. scope: a.addrSpaces[localAddressSpace].scope,
  518. subnets: map[SubnetKey]*PoolData{},
  519. }
  520. poolID, _, _, err := a.RequestPool("rosso", "172.28.0.0/16", "172.28.30.0/24", nil, false)
  521. if err != nil {
  522. t.Fatal(err)
  523. }
  524. var ip *net.IPNet
  525. expected := &net.IPNet{IP: net.IP{172, 28, 30, 255}, Mask: net.IPMask{255, 255, 0, 0}}
  526. for err == nil {
  527. var c *net.IPNet
  528. if c, _, err = a.RequestAddress(poolID, nil, nil); err == nil {
  529. ip = c
  530. }
  531. }
  532. if err != ipamapi.ErrNoAvailableIPs {
  533. t.Fatal(err)
  534. }
  535. if !types.CompareIPNet(expected, ip) {
  536. t.Fatalf("Unexpected last IP from subpool. Expected: %s. Got: %v.", expected, ip)
  537. }
  538. rp := &net.IPNet{IP: net.IP{172, 28, 30, 97}, Mask: net.IPMask{255, 255, 0, 0}}
  539. if err = a.ReleaseAddress(poolID, rp.IP); err != nil {
  540. t.Fatal(err)
  541. }
  542. if ip, _, err = a.RequestAddress(poolID, nil, nil); err != nil {
  543. t.Fatal(err)
  544. }
  545. if !types.CompareIPNet(rp, ip) {
  546. t.Fatalf("Unexpected IP from subpool. Expected: %s. Got: %v.", rp, ip)
  547. }
  548. _, _, _, err = a.RequestPool("rosso", "10.0.0.0/8", "10.0.0.0/16", nil, false)
  549. if err != nil {
  550. t.Fatal(err)
  551. }
  552. poolID, _, _, err = a.RequestPool("rosso", "10.0.0.0/16", "10.0.0.0/24", nil, false)
  553. if err != nil {
  554. t.Fatal(err)
  555. }
  556. expected = &net.IPNet{IP: net.IP{10, 0, 0, 255}, Mask: net.IPMask{255, 255, 0, 0}}
  557. for err == nil {
  558. var c *net.IPNet
  559. if c, _, err = a.RequestAddress(poolID, nil, nil); err == nil {
  560. ip = c
  561. }
  562. }
  563. if err != ipamapi.ErrNoAvailableIPs {
  564. t.Fatal(err)
  565. }
  566. if !types.CompareIPNet(expected, ip) {
  567. t.Fatalf("Unexpected last IP from subpool. Expected: %s. Got: %v.", expected, ip)
  568. }
  569. rp = &net.IPNet{IP: net.IP{10, 0, 0, 79}, Mask: net.IPMask{255, 255, 0, 0}}
  570. if err = a.ReleaseAddress(poolID, rp.IP); err != nil {
  571. t.Fatal(err)
  572. }
  573. if ip, _, err = a.RequestAddress(poolID, nil, nil); err != nil {
  574. t.Fatal(err)
  575. }
  576. if !types.CompareIPNet(rp, ip) {
  577. t.Fatalf("Unexpected IP from subpool. Expected: %s. Got: %v.", rp, ip)
  578. }
  579. // Request any addresses from subpool after explicit address request
  580. unoExp, _ := types.ParseCIDR("10.2.2.0/16")
  581. dueExp, _ := types.ParseCIDR("10.2.2.2/16")
  582. treExp, _ := types.ParseCIDR("10.2.2.1/16")
  583. if poolID, _, _, err = a.RequestPool("rosso", "10.2.0.0/16", "10.2.2.0/24", nil, false); err != nil {
  584. t.Fatal(err)
  585. }
  586. tre, _, err := a.RequestAddress(poolID, treExp.IP, nil)
  587. if err != nil {
  588. t.Fatal(err)
  589. }
  590. if !types.CompareIPNet(tre, treExp) {
  591. t.Fatalf("Unexpected address: %v", tre)
  592. }
  593. uno, _, err := a.RequestAddress(poolID, nil, nil)
  594. if err != nil {
  595. t.Fatal(err)
  596. }
  597. if !types.CompareIPNet(uno, unoExp) {
  598. t.Fatalf("Unexpected address: %v", uno)
  599. }
  600. due, _, err := a.RequestAddress(poolID, nil, nil)
  601. if err != nil {
  602. t.Fatal(err)
  603. }
  604. if !types.CompareIPNet(due, dueExp) {
  605. t.Fatalf("Unexpected address: %v", due)
  606. }
  607. if err = a.ReleaseAddress(poolID, uno.IP); err != nil {
  608. t.Fatal(err)
  609. }
  610. uno, _, err = a.RequestAddress(poolID, nil, nil)
  611. if err != nil {
  612. t.Fatal(err)
  613. }
  614. if !types.CompareIPNet(uno, unoExp) {
  615. t.Fatalf("Unexpected address: %v", uno)
  616. }
  617. if err = a.ReleaseAddress(poolID, tre.IP); err != nil {
  618. t.Fatal(err)
  619. }
  620. tre, _, err = a.RequestAddress(poolID, nil, nil)
  621. if err != nil {
  622. t.Fatal(err)
  623. }
  624. if !types.CompareIPNet(tre, treExp) {
  625. t.Fatalf("Unexpected address: %v", tre)
  626. }
  627. }
  628. }
  629. func TestSerializeRequestReleaseAddressFromSubPool(t *testing.T) {
  630. opts := map[string]string{
  631. ipamapi.AllocSerialPrefix: "true"}
  632. for _, store := range []bool{false, true} {
  633. a, err := getAllocator(store)
  634. assert.NilError(t, err)
  635. a.addrSpaces["rosso"] = &addrSpace{
  636. id: dsConfigKey + "/" + "rosso",
  637. ds: a.addrSpaces[localAddressSpace].ds,
  638. alloc: a.addrSpaces[localAddressSpace].alloc,
  639. scope: a.addrSpaces[localAddressSpace].scope,
  640. subnets: map[SubnetKey]*PoolData{},
  641. }
  642. poolID, _, _, err := a.RequestPool("rosso", "172.28.0.0/16", "172.28.30.0/24", nil, false)
  643. if err != nil {
  644. t.Fatal(err)
  645. }
  646. var ip *net.IPNet
  647. expected := &net.IPNet{IP: net.IP{172, 28, 30, 255}, Mask: net.IPMask{255, 255, 0, 0}}
  648. for err == nil {
  649. var c *net.IPNet
  650. if c, _, err = a.RequestAddress(poolID, nil, opts); err == nil {
  651. ip = c
  652. }
  653. }
  654. if err != ipamapi.ErrNoAvailableIPs {
  655. t.Fatal(err)
  656. }
  657. if !types.CompareIPNet(expected, ip) {
  658. t.Fatalf("Unexpected last IP from subpool. Expected: %s. Got: %v.", expected, ip)
  659. }
  660. rp := &net.IPNet{IP: net.IP{172, 28, 30, 97}, Mask: net.IPMask{255, 255, 0, 0}}
  661. if err = a.ReleaseAddress(poolID, rp.IP); err != nil {
  662. t.Fatal(err)
  663. }
  664. if ip, _, err = a.RequestAddress(poolID, nil, opts); err != nil {
  665. t.Fatal(err)
  666. }
  667. if !types.CompareIPNet(rp, ip) {
  668. t.Fatalf("Unexpected IP from subpool. Expected: %s. Got: %v.", rp, ip)
  669. }
  670. _, _, _, err = a.RequestPool("rosso", "10.0.0.0/8", "10.0.0.0/16", nil, false)
  671. if err != nil {
  672. t.Fatal(err)
  673. }
  674. poolID, _, _, err = a.RequestPool("rosso", "10.0.0.0/16", "10.0.0.0/24", nil, false)
  675. if err != nil {
  676. t.Fatal(err)
  677. }
  678. expected = &net.IPNet{IP: net.IP{10, 0, 0, 255}, Mask: net.IPMask{255, 255, 0, 0}}
  679. for err == nil {
  680. var c *net.IPNet
  681. if c, _, err = a.RequestAddress(poolID, nil, opts); err == nil {
  682. ip = c
  683. }
  684. }
  685. if err != ipamapi.ErrNoAvailableIPs {
  686. t.Fatal(err)
  687. }
  688. if !types.CompareIPNet(expected, ip) {
  689. t.Fatalf("Unexpected last IP from subpool. Expected: %s. Got: %v.", expected, ip)
  690. }
  691. rp = &net.IPNet{IP: net.IP{10, 0, 0, 79}, Mask: net.IPMask{255, 255, 0, 0}}
  692. if err = a.ReleaseAddress(poolID, rp.IP); err != nil {
  693. t.Fatal(err)
  694. }
  695. if ip, _, err = a.RequestAddress(poolID, nil, opts); err != nil {
  696. t.Fatal(err)
  697. }
  698. if !types.CompareIPNet(rp, ip) {
  699. t.Fatalf("Unexpected IP from subpool. Expected: %s. Got: %v.", rp, ip)
  700. }
  701. // Request any addresses from subpool after explicit address request
  702. unoExp, _ := types.ParseCIDR("10.2.2.0/16")
  703. dueExp, _ := types.ParseCIDR("10.2.2.2/16")
  704. treExp, _ := types.ParseCIDR("10.2.2.1/16")
  705. quaExp, _ := types.ParseCIDR("10.2.2.3/16")
  706. fivExp, _ := types.ParseCIDR("10.2.2.4/16")
  707. if poolID, _, _, err = a.RequestPool("rosso", "10.2.0.0/16", "10.2.2.0/24", nil, false); err != nil {
  708. t.Fatal(err)
  709. }
  710. tre, _, err := a.RequestAddress(poolID, treExp.IP, opts)
  711. if err != nil {
  712. t.Fatal(err)
  713. }
  714. if !types.CompareIPNet(tre, treExp) {
  715. t.Fatalf("Unexpected address: %v", tre)
  716. }
  717. uno, _, err := a.RequestAddress(poolID, nil, opts)
  718. if err != nil {
  719. t.Fatal(err)
  720. }
  721. if !types.CompareIPNet(uno, unoExp) {
  722. t.Fatalf("Unexpected address: %v", uno)
  723. }
  724. due, _, err := a.RequestAddress(poolID, nil, opts)
  725. if err != nil {
  726. t.Fatal(err)
  727. }
  728. if !types.CompareIPNet(due, dueExp) {
  729. t.Fatalf("Unexpected address: %v", due)
  730. }
  731. if err = a.ReleaseAddress(poolID, uno.IP); err != nil {
  732. t.Fatal(err)
  733. }
  734. uno, _, err = a.RequestAddress(poolID, nil, opts)
  735. if err != nil {
  736. t.Fatal(err)
  737. }
  738. if !types.CompareIPNet(uno, quaExp) {
  739. t.Fatalf("Unexpected address: %v", uno)
  740. }
  741. if err = a.ReleaseAddress(poolID, tre.IP); err != nil {
  742. t.Fatal(err)
  743. }
  744. tre, _, err = a.RequestAddress(poolID, nil, opts)
  745. if err != nil {
  746. t.Fatal(err)
  747. }
  748. if !types.CompareIPNet(tre, fivExp) {
  749. t.Fatalf("Unexpected address: %v", tre)
  750. }
  751. }
  752. }
  753. func TestGetAddress(t *testing.T) {
  754. input := []string{
  755. /*"10.0.0.0/8", "10.0.0.0/9", "10.0.0.0/10",*/ "10.0.0.0/11", "10.0.0.0/12", "10.0.0.0/13", "10.0.0.0/14",
  756. "10.0.0.0/15", "10.0.0.0/16", "10.0.0.0/17", "10.0.0.0/18", "10.0.0.0/19", "10.0.0.0/20", "10.0.0.0/21",
  757. "10.0.0.0/22", "10.0.0.0/23", "10.0.0.0/24", "10.0.0.0/25", "10.0.0.0/26", "10.0.0.0/27", "10.0.0.0/28",
  758. "10.0.0.0/29", "10.0.0.0/30", "10.0.0.0/31"}
  759. for _, subnet := range input {
  760. assertGetAddress(t, subnet)
  761. }
  762. }
  763. func TestRequestSyntaxCheck(t *testing.T) {
  764. var (
  765. pool = "192.168.0.0/16"
  766. subPool = "192.168.0.0/24"
  767. as = "green"
  768. )
  769. for _, store := range []bool{false, true} {
  770. a, err := getAllocator(store)
  771. assert.NilError(t, err)
  772. a.addrSpaces[as] = &addrSpace{
  773. id: dsConfigKey + "/" + as,
  774. ds: a.addrSpaces[localAddressSpace].ds,
  775. alloc: a.addrSpaces[localAddressSpace].alloc,
  776. scope: a.addrSpaces[localAddressSpace].scope,
  777. subnets: map[SubnetKey]*PoolData{},
  778. }
  779. _, _, _, err = a.RequestPool("", pool, "", nil, false)
  780. if err == nil {
  781. t.Fatal("Failed to detect wrong request: empty address space")
  782. }
  783. _, _, _, err = a.RequestPool("", pool, subPool, nil, false)
  784. if err == nil {
  785. t.Fatal("Failed to detect wrong request: empty address space")
  786. }
  787. _, _, _, err = a.RequestPool(as, "", subPool, nil, false)
  788. if err == nil {
  789. t.Fatal("Failed to detect wrong request: subPool specified and no pool")
  790. }
  791. pid, _, _, err := a.RequestPool(as, pool, subPool, nil, false)
  792. if err != nil {
  793. t.Fatalf("Unexpected failure: %v", err)
  794. }
  795. _, _, err = a.RequestAddress("", nil, nil)
  796. if err == nil {
  797. t.Fatal("Failed to detect wrong request: no pool id specified")
  798. }
  799. ip := net.ParseIP("172.17.0.23")
  800. _, _, err = a.RequestAddress(pid, ip, nil)
  801. if err == nil {
  802. t.Fatal("Failed to detect wrong request: requested IP from different subnet")
  803. }
  804. ip = net.ParseIP("192.168.0.50")
  805. _, _, err = a.RequestAddress(pid, ip, nil)
  806. if err != nil {
  807. t.Fatalf("Unexpected failure: %v", err)
  808. }
  809. err = a.ReleaseAddress("", ip)
  810. if err == nil {
  811. t.Fatal("Failed to detect wrong request: no pool id specified")
  812. }
  813. err = a.ReleaseAddress(pid, nil)
  814. if err == nil {
  815. t.Fatal("Failed to detect wrong request: no pool id specified")
  816. }
  817. err = a.ReleaseAddress(pid, ip)
  818. if err != nil {
  819. t.Fatalf("Unexpected failure: %v: %s, %s", err, pid, ip)
  820. }
  821. }
  822. }
  823. func TestRequest(t *testing.T) {
  824. // Request N addresses from different size subnets, verifying last request
  825. // returns expected address. Internal subnet host size is Allocator's default, 16
  826. input := []struct {
  827. subnet string
  828. numReq int
  829. lastIP string
  830. }{
  831. {"192.168.59.0/24", 254, "192.168.59.254"},
  832. {"192.168.240.0/20", 255, "192.168.240.255"},
  833. {"192.168.0.0/16", 255, "192.168.0.255"},
  834. {"192.168.0.0/16", 256, "192.168.1.0"},
  835. {"10.16.0.0/16", 255, "10.16.0.255"},
  836. {"10.128.0.0/12", 255, "10.128.0.255"},
  837. {"10.0.0.0/8", 256, "10.0.1.0"},
  838. {"192.168.128.0/18", 4*256 - 1, "192.168.131.255"},
  839. /*
  840. {"192.168.240.0/20", 16*256 - 2, "192.168.255.254"},
  841. {"192.168.0.0/16", 256*256 - 2, "192.168.255.254"},
  842. {"10.0.0.0/8", 2 * 256, "10.0.2.0"},
  843. {"10.0.0.0/8", 5 * 256, "10.0.5.0"},
  844. {"10.0.0.0/8", 100 * 256 * 254, "10.99.255.254"},
  845. */
  846. }
  847. for _, d := range input {
  848. assertNRequests(t, d.subnet, d.numReq, d.lastIP)
  849. }
  850. }
  851. // TestOverlappingRequests tests that overlapping subnets cannot be allocated.
  852. // Requests for subnets which are supersets or subsets of existing allocations,
  853. // or which overlap at the beginning or end, should not be permitted.
  854. func TestOverlappingRequests(t *testing.T) {
  855. input := []struct {
  856. environment []string
  857. subnet string
  858. ok bool
  859. }{
  860. // IPv4
  861. // Previously allocated network does not overlap with request
  862. {[]string{"10.0.0.0/8"}, "11.0.0.0/8", true},
  863. {[]string{"74.0.0.0/7"}, "9.111.99.72/30", true},
  864. {[]string{"110.192.0.0/10"}, "16.0.0.0/10", true},
  865. // Previously allocated network entirely contains request
  866. {[]string{"10.0.0.0/8"}, "10.0.0.0/8", false}, // exact overlap
  867. {[]string{"0.0.0.0/1"}, "16.182.0.0/15", false},
  868. {[]string{"16.0.0.0/4"}, "17.11.66.0/23", false},
  869. // Previously allocated network overlaps beginning of request
  870. {[]string{"0.0.0.0/1"}, "0.0.0.0/0", false},
  871. {[]string{"64.0.0.0/6"}, "64.0.0.0/3", false},
  872. {[]string{"112.0.0.0/6"}, "112.0.0.0/4", false},
  873. // Previously allocated network overlaps end of request
  874. {[]string{"96.0.0.0/3"}, "0.0.0.0/1", false},
  875. {[]string{"192.0.0.0/2"}, "128.0.0.0/1", false},
  876. {[]string{"95.0.0.0/8"}, "92.0.0.0/6", false},
  877. // Previously allocated network entirely contained within request
  878. {[]string{"10.0.0.0/8"}, "10.0.0.0/6", false}, // non-canonical
  879. {[]string{"10.0.0.0/8"}, "8.0.0.0/6", false}, // canonical
  880. {[]string{"25.173.144.0/20"}, "0.0.0.0/0", false},
  881. // IPv6
  882. // Previously allocated network entirely contains request
  883. {[]string{"::/0"}, "f656:3484:c878:a05:e540:a6ed:4d70:3740/123", false},
  884. {[]string{"8000::/1"}, "8fe8:e7c4:5779::/49", false},
  885. {[]string{"f000::/4"}, "ffc7:6000::/19", false},
  886. // Previously allocated network overlaps beginning of request
  887. {[]string{"::/2"}, "::/0", false},
  888. {[]string{"::/3"}, "::/1", false},
  889. {[]string{"::/6"}, "::/5", false},
  890. // Previously allocated network overlaps end of request
  891. {[]string{"c000::/2"}, "8000::/1", false},
  892. {[]string{"7c00::/6"}, "::/1", false},
  893. {[]string{"cf80::/9"}, "c000::/4", false},
  894. // Previously allocated network entirely contained within request
  895. {[]string{"ff77:93f8::/29"}, "::/0", false},
  896. {[]string{"9287:2e20:5134:fab6:9061:a0c6:bfe3:9400/119"}, "8000::/1", false},
  897. {[]string{"3ea1:bfa9:8691:d1c6:8c46:519b:db6d:e700/120"}, "3000::/4", false},
  898. }
  899. for _, store := range []bool{false, true} {
  900. for _, tc := range input {
  901. a, err := getAllocator(store)
  902. assert.NilError(t, err)
  903. // Set up some existing allocations. This should always succeed.
  904. for _, env := range tc.environment {
  905. _, _, _, err = a.RequestPool(localAddressSpace, env, "", nil, false)
  906. assert.NilError(t, err)
  907. }
  908. // Make the test allocation.
  909. _, _, _, err = a.RequestPool(localAddressSpace, tc.subnet, "", nil, false)
  910. if tc.ok {
  911. assert.NilError(t, err)
  912. } else {
  913. assert.Check(t, is.ErrorContains(err, ""))
  914. }
  915. }
  916. }
  917. }
  918. func TestRelease(t *testing.T) {
  919. var (
  920. subnet = "192.168.0.0/23"
  921. )
  922. for _, store := range []bool{false, true} {
  923. a, err := getAllocator(store)
  924. assert.NilError(t, err)
  925. pid, _, _, err := a.RequestPool(localAddressSpace, subnet, "", nil, false)
  926. if err != nil {
  927. t.Fatal(err)
  928. }
  929. // Allocate all addresses
  930. for err != ipamapi.ErrNoAvailableIPs {
  931. _, _, err = a.RequestAddress(pid, nil, nil)
  932. }
  933. toRelease := []struct {
  934. address string
  935. }{
  936. {"192.168.0.1"},
  937. {"192.168.0.2"},
  938. {"192.168.0.3"},
  939. {"192.168.0.4"},
  940. {"192.168.0.5"},
  941. {"192.168.0.6"},
  942. {"192.168.0.7"},
  943. {"192.168.0.8"},
  944. {"192.168.0.9"},
  945. {"192.168.0.10"},
  946. {"192.168.0.30"},
  947. {"192.168.0.31"},
  948. {"192.168.1.32"},
  949. {"192.168.0.254"},
  950. {"192.168.1.1"},
  951. {"192.168.1.2"},
  952. {"192.168.1.3"},
  953. {"192.168.1.253"},
  954. {"192.168.1.254"},
  955. }
  956. // One by one, release the address and request again. We should get the same IP
  957. for i, inp := range toRelease {
  958. ip0 := net.ParseIP(inp.address)
  959. a.ReleaseAddress(pid, ip0)
  960. bm := a.addresses[SubnetKey{localAddressSpace, subnet, ""}]
  961. if bm.Unselected() != 1 {
  962. t.Fatalf("Failed to update free address count after release. Expected %d, Found: %d", i+1, bm.Unselected())
  963. }
  964. nw, _, err := a.RequestAddress(pid, nil, nil)
  965. if err != nil {
  966. t.Fatalf("Failed to obtain the address: %s", err.Error())
  967. }
  968. ip := nw.IP
  969. if !ip0.Equal(ip) {
  970. t.Fatalf("Failed to obtain the same address. Expected: %s, Got: %s", ip0, ip)
  971. }
  972. }
  973. }
  974. }
  975. func assertGetAddress(t *testing.T, subnet string) {
  976. var (
  977. err error
  978. printTime = false
  979. a = &Allocator{}
  980. )
  981. _, sub, _ := net.ParseCIDR(subnet)
  982. ones, bits := sub.Mask.Size()
  983. zeroes := bits - ones
  984. numAddresses := 1 << uint(zeroes)
  985. bm, err := bitseq.NewHandle("ipam_test", nil, "default/"+subnet, uint64(numAddresses))
  986. if err != nil {
  987. t.Fatal(err)
  988. }
  989. start := time.Now()
  990. run := 0
  991. for err != ipamapi.ErrNoAvailableIPs {
  992. _, err = a.getAddress(sub, bm, nil, nil, false)
  993. run++
  994. }
  995. if printTime {
  996. fmt.Printf("\nTaken %v, to allocate all addresses on %s. (nemAddresses: %d. Runs: %d)", time.Since(start), subnet, numAddresses, run)
  997. }
  998. if bm.Unselected() != 0 {
  999. t.Fatalf("Unexpected free count after reserving all addresses: %d", bm.Unselected())
  1000. }
  1001. /*
  1002. if bm.Head.Block != expectedMax || bm.Head.Count != numBlocks {
  1003. t.Fatalf("Failed to effectively reserve all addresses on %s. Expected (0x%x, %d) as first sequence. Found (0x%x,%d)",
  1004. subnet, expectedMax, numBlocks, bm.Head.Block, bm.Head.Count)
  1005. }
  1006. */
  1007. }
  1008. func assertNRequests(t *testing.T, subnet string, numReq int, lastExpectedIP string) {
  1009. var (
  1010. nw *net.IPNet
  1011. printTime = false
  1012. )
  1013. lastIP := net.ParseIP(lastExpectedIP)
  1014. for _, store := range []bool{false, true} {
  1015. a, err := getAllocator(store)
  1016. assert.NilError(t, err)
  1017. pid, _, _, err := a.RequestPool(localAddressSpace, subnet, "", nil, false)
  1018. if err != nil {
  1019. t.Fatal(err)
  1020. }
  1021. i := 0
  1022. start := time.Now()
  1023. for ; i < numReq; i++ {
  1024. nw, _, err = a.RequestAddress(pid, nil, nil)
  1025. }
  1026. if printTime {
  1027. fmt.Printf("\nTaken %v, to allocate %d addresses on %s\n", time.Since(start), numReq, subnet)
  1028. }
  1029. if !lastIP.Equal(nw.IP) {
  1030. t.Fatalf("Wrong last IP. Expected %s. Got: %s (err: %v, ind: %d)", lastExpectedIP, nw.IP.String(), err, i)
  1031. }
  1032. }
  1033. }
  1034. func benchmarkRequest(b *testing.B, a *Allocator, subnet string) {
  1035. pid, _, _, err := a.RequestPool(localAddressSpace, subnet, "", nil, false)
  1036. for err != ipamapi.ErrNoAvailableIPs {
  1037. _, _, err = a.RequestAddress(pid, nil, nil)
  1038. }
  1039. }
  1040. func BenchmarkRequest(b *testing.B) {
  1041. subnets := []string{
  1042. "10.0.0.0/24",
  1043. "10.0.0.0/16",
  1044. "10.0.0.0/8",
  1045. }
  1046. for _, subnet := range subnets {
  1047. name := fmt.Sprintf("%vSubnet", subnet)
  1048. b.Run(name, func(b *testing.B) {
  1049. a, _ := getAllocator(true)
  1050. benchmarkRequest(b, a, subnet)
  1051. })
  1052. }
  1053. }
  1054. func TestAllocateRandomDeallocate(t *testing.T) {
  1055. for _, store := range []bool{false, true} {
  1056. testAllocateRandomDeallocate(t, "172.25.0.0/16", "", 384, store)
  1057. testAllocateRandomDeallocate(t, "172.25.0.0/16", "172.25.252.0/22", 384, store)
  1058. }
  1059. }
  1060. func testAllocateRandomDeallocate(t *testing.T, pool, subPool string, num int, store bool) {
  1061. ds, err := randomLocalStore(store)
  1062. assert.NilError(t, err)
  1063. a, err := NewAllocator(ds, nil)
  1064. if err != nil {
  1065. t.Fatal(err)
  1066. }
  1067. pid, _, _, err := a.RequestPool(localAddressSpace, pool, subPool, nil, false)
  1068. if err != nil {
  1069. t.Fatal(err)
  1070. }
  1071. // Allocate num ip addresses
  1072. indices := make(map[int]*net.IPNet, num)
  1073. allocated := make(map[string]bool, num)
  1074. for i := 0; i < num; i++ {
  1075. ip, _, err := a.RequestAddress(pid, nil, nil)
  1076. if err != nil {
  1077. t.Fatal(err)
  1078. }
  1079. ips := ip.String()
  1080. if _, ok := allocated[ips]; ok {
  1081. t.Fatalf("Address %s is already allocated", ips)
  1082. }
  1083. allocated[ips] = true
  1084. indices[i] = ip
  1085. }
  1086. if len(indices) != len(allocated) || len(indices) != num {
  1087. t.Fatalf("Unexpected number of allocated addresses: (%d,%d).", len(indices), len(allocated))
  1088. }
  1089. seed := time.Now().Unix()
  1090. rand.Seed(seed)
  1091. // Deallocate half of the allocated addresses following a random pattern
  1092. pattern := rand.Perm(num)
  1093. for i := 0; i < num/2; i++ {
  1094. idx := pattern[i]
  1095. ip := indices[idx]
  1096. err := a.ReleaseAddress(pid, ip.IP)
  1097. if err != nil {
  1098. t.Fatalf("Unexpected failure on deallocation of %s: %v.\nSeed: %d.", ip, err, seed)
  1099. }
  1100. delete(indices, idx)
  1101. delete(allocated, ip.String())
  1102. }
  1103. // Request a quarter of addresses
  1104. for i := 0; i < num/2; i++ {
  1105. ip, _, err := a.RequestAddress(pid, nil, nil)
  1106. if err != nil {
  1107. t.Fatal(err)
  1108. }
  1109. ips := ip.String()
  1110. if _, ok := allocated[ips]; ok {
  1111. t.Fatalf("\nAddress %s is already allocated.\nSeed: %d.", ips, seed)
  1112. }
  1113. allocated[ips] = true
  1114. }
  1115. if len(allocated) != num {
  1116. t.Fatalf("Unexpected number of allocated addresses: %d.\nSeed: %d.", len(allocated), seed)
  1117. }
  1118. }
  1119. func TestRetrieveFromStore(t *testing.T) {
  1120. num := 200
  1121. ds, err := randomLocalStore(true)
  1122. if err != nil {
  1123. t.Fatal(err)
  1124. }
  1125. a, err := NewAllocator(ds, nil)
  1126. if err != nil {
  1127. t.Fatal(err)
  1128. }
  1129. pid, _, _, err := a.RequestPool(localAddressSpace, "172.25.0.0/16", "", nil, false)
  1130. if err != nil {
  1131. t.Fatal(err)
  1132. }
  1133. for i := 0; i < num; i++ {
  1134. if _, _, err := a.RequestAddress(pid, nil, nil); err != nil {
  1135. t.Fatal(err)
  1136. }
  1137. }
  1138. // Restore
  1139. a1, err := NewAllocator(ds, nil)
  1140. if err != nil {
  1141. t.Fatal(err)
  1142. }
  1143. a1.refresh(localAddressSpace)
  1144. db := a.DumpDatabase()
  1145. db1 := a1.DumpDatabase()
  1146. if db != db1 {
  1147. t.Fatalf("Unexpected db change.\nExpected:%s\nGot:%s", db, db1)
  1148. }
  1149. checkDBEquality(a, a1, t)
  1150. pid, _, _, err = a1.RequestPool(localAddressSpace, "172.25.0.0/16", "172.25.1.0/24", nil, false)
  1151. if err != nil {
  1152. t.Fatal(err)
  1153. }
  1154. for i := 0; i < num/2; i++ {
  1155. if _, _, err := a1.RequestAddress(pid, nil, nil); err != nil {
  1156. t.Fatal(err)
  1157. }
  1158. }
  1159. // Restore
  1160. a2, err := NewAllocator(ds, nil)
  1161. if err != nil {
  1162. t.Fatal(err)
  1163. }
  1164. a2.refresh(localAddressSpace)
  1165. checkDBEquality(a1, a2, t)
  1166. pid, _, _, err = a2.RequestPool(localAddressSpace, "172.25.0.0/16", "172.25.2.0/24", nil, false)
  1167. if err != nil {
  1168. t.Fatal(err)
  1169. }
  1170. for i := 0; i < num/2; i++ {
  1171. if _, _, err := a2.RequestAddress(pid, nil, nil); err != nil {
  1172. t.Fatal(err)
  1173. }
  1174. }
  1175. // Restore
  1176. a3, err := NewAllocator(ds, nil)
  1177. if err != nil {
  1178. t.Fatal(err)
  1179. }
  1180. a3.refresh(localAddressSpace)
  1181. checkDBEquality(a2, a3, t)
  1182. pid, _, _, err = a3.RequestPool(localAddressSpace, "172.26.0.0/16", "", nil, false)
  1183. if err != nil {
  1184. t.Fatal(err)
  1185. }
  1186. for i := 0; i < num/2; i++ {
  1187. if _, _, err := a3.RequestAddress(pid, nil, nil); err != nil {
  1188. t.Fatal(err)
  1189. }
  1190. }
  1191. // Restore
  1192. a4, err := NewAllocator(ds, nil)
  1193. if err != nil {
  1194. t.Fatal(err)
  1195. }
  1196. a4.refresh(localAddressSpace)
  1197. checkDBEquality(a3, a4, t)
  1198. }
  1199. func checkDBEquality(a1, a2 *Allocator, t *testing.T) {
  1200. for k, cnf1 := range a1.addrSpaces[localAddressSpace].subnets {
  1201. cnf2 := a2.addrSpaces[localAddressSpace].subnets[k]
  1202. if cnf1.String() != cnf2.String() {
  1203. t.Fatalf("%s\n%s", cnf1, cnf2)
  1204. }
  1205. if cnf1.Range == nil {
  1206. a2.retrieveBitmask(k, cnf1.Pool)
  1207. }
  1208. }
  1209. for k, bm1 := range a1.addresses {
  1210. bm2 := a2.addresses[k]
  1211. if bm1.String() != bm2.String() {
  1212. t.Fatalf("%s\n%s", bm1, bm2)
  1213. }
  1214. }
  1215. }
  1216. const (
  1217. numInstances = 5
  1218. first = 0
  1219. last = numInstances - 1
  1220. )
  1221. var (
  1222. allocator *Allocator
  1223. start = make(chan struct{})
  1224. done = make(chan chan struct{}, numInstances-1)
  1225. pools = make([]*net.IPNet, numInstances)
  1226. )
  1227. func runParallelTests(t *testing.T, instance int) {
  1228. var err error
  1229. t.Parallel()
  1230. pTest := flag.Lookup("test.parallel")
  1231. if pTest == nil {
  1232. t.Skip("Skipped because test.parallel flag not set;")
  1233. }
  1234. numParallel, err := strconv.Atoi(pTest.Value.String())
  1235. if err != nil {
  1236. t.Fatal(err)
  1237. }
  1238. if numParallel < numInstances {
  1239. t.Skip("Skipped because t.parallel was less than ", numInstances)
  1240. }
  1241. // The first instance creates the allocator, gives the start
  1242. // and finally checks the pools each instance was assigned
  1243. if instance == first {
  1244. allocator, err = getAllocator(true)
  1245. if err != nil {
  1246. t.Fatal(err)
  1247. }
  1248. close(start)
  1249. }
  1250. if instance != first {
  1251. <-start
  1252. instDone := make(chan struct{})
  1253. done <- instDone
  1254. defer close(instDone)
  1255. if instance == last {
  1256. defer close(done)
  1257. }
  1258. }
  1259. _, pools[instance], _, err = allocator.RequestPool(localAddressSpace, "", "", nil, false)
  1260. if err != nil {
  1261. t.Fatal(err)
  1262. }
  1263. if instance == first {
  1264. for instDone := range done {
  1265. <-instDone
  1266. }
  1267. // Now check each instance got a different pool
  1268. for i := 0; i < numInstances; i++ {
  1269. for j := i + 1; j < numInstances; j++ {
  1270. if types.CompareIPNet(pools[i], pools[j]) {
  1271. t.Fatalf("Instance %d and %d were given the same predefined pool: %v", i, j, pools)
  1272. }
  1273. }
  1274. }
  1275. }
  1276. }
  1277. func TestRequestReleaseAddressDuplicate(t *testing.T) {
  1278. a, err := getAllocator(false)
  1279. if err != nil {
  1280. t.Fatal(err)
  1281. }
  1282. type IP struct {
  1283. ip *net.IPNet
  1284. ref int
  1285. }
  1286. ips := []IP{}
  1287. allocatedIPs := []*net.IPNet{}
  1288. a.addrSpaces["rosso"] = &addrSpace{
  1289. id: dsConfigKey + "/" + "rosso",
  1290. ds: a.addrSpaces[localAddressSpace].ds,
  1291. alloc: a.addrSpaces[localAddressSpace].alloc,
  1292. scope: a.addrSpaces[localAddressSpace].scope,
  1293. subnets: map[SubnetKey]*PoolData{},
  1294. }
  1295. opts := map[string]string{
  1296. ipamapi.AllocSerialPrefix: "true",
  1297. }
  1298. var l sync.Mutex
  1299. poolID, _, _, err := a.RequestPool("rosso", "198.168.0.0/23", "", nil, false)
  1300. if err != nil {
  1301. t.Fatal(err)
  1302. }
  1303. group := new(errgroup.Group)
  1304. for err == nil {
  1305. var c *net.IPNet
  1306. if c, _, err = a.RequestAddress(poolID, nil, opts); err == nil {
  1307. l.Lock()
  1308. ips = append(ips, IP{c, 1})
  1309. l.Unlock()
  1310. allocatedIPs = append(allocatedIPs, c)
  1311. if len(allocatedIPs) > 500 {
  1312. i := rand.Intn(len(allocatedIPs) - 1)
  1313. ip := allocatedIPs[i]
  1314. group.Go(func() error {
  1315. if err = a.ReleaseAddress(poolID, ip.IP); err != nil {
  1316. return err
  1317. }
  1318. l.Lock()
  1319. ips = append(ips, IP{ip, -1})
  1320. l.Unlock()
  1321. return nil
  1322. })
  1323. allocatedIPs = append(allocatedIPs[:i], allocatedIPs[i+1:]...)
  1324. }
  1325. }
  1326. }
  1327. if err := group.Wait(); err != nil {
  1328. t.Fatal(err)
  1329. }
  1330. refMap := make(map[string]int)
  1331. for _, ip := range ips {
  1332. refMap[ip.ip.String()] = refMap[ip.ip.String()] + ip.ref
  1333. if refMap[ip.ip.String()] < 0 {
  1334. t.Fatalf("IP %s was previously released", ip.ip.String())
  1335. }
  1336. if refMap[ip.ip.String()] > 1 {
  1337. t.Fatalf("IP %s was previously allocated", ip.ip.String())
  1338. }
  1339. }
  1340. }
  1341. func TestParallelPredefinedRequest1(t *testing.T) {
  1342. runParallelTests(t, 0)
  1343. }
  1344. func TestParallelPredefinedRequest2(t *testing.T) {
  1345. runParallelTests(t, 1)
  1346. }
  1347. func TestParallelPredefinedRequest3(t *testing.T) {
  1348. runParallelTests(t, 2)
  1349. }
  1350. func TestParallelPredefinedRequest4(t *testing.T) {
  1351. runParallelTests(t, 3)
  1352. }
  1353. func TestParallelPredefinedRequest5(t *testing.T) {
  1354. runParallelTests(t, 4)
  1355. }