allocator_test.go 40 KB

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