allocator_test.go 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616
  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 TestUnusualSubnets(t *testing.T) {
  919. subnet := "192.168.0.2/31"
  920. outsideTheRangeAddresses := []struct {
  921. address string
  922. }{
  923. {"192.168.0.1"},
  924. {"192.168.0.4"},
  925. {"192.168.0.100"},
  926. }
  927. expectedAddresses := []struct {
  928. address string
  929. }{
  930. {"192.168.0.2"},
  931. {"192.168.0.3"},
  932. }
  933. for _, store := range []bool{false, true} {
  934. allocator, err := getAllocator(store)
  935. if err != nil {
  936. t.Fatal(err)
  937. }
  938. //
  939. // IPv4 /31 blocks. See RFC 3021.
  940. //
  941. pool, _, _, err := allocator.RequestPool(localAddressSpace, subnet, "", nil, false)
  942. if err != nil {
  943. t.Fatal(err)
  944. }
  945. // Outside-the-range
  946. for _, outside := range outsideTheRangeAddresses {
  947. _, _, errx := allocator.RequestAddress(pool, net.ParseIP(outside.address), nil)
  948. if errx != ipamapi.ErrIPOutOfRange {
  949. t.Fatalf("Address %s failed to throw expected error: %s", outside.address, errx.Error())
  950. }
  951. }
  952. // Should get just these two IPs followed by exhaustion on the next request
  953. for _, expected := range expectedAddresses {
  954. got, _, errx := allocator.RequestAddress(pool, nil, nil)
  955. if errx != nil {
  956. t.Fatalf("Failed to obtain the address: %s", errx.Error())
  957. }
  958. expectedIP := net.ParseIP(expected.address)
  959. gotIP := got.IP
  960. if !gotIP.Equal(expectedIP) {
  961. t.Fatalf("Failed to obtain sequentialaddress. Expected: %s, Got: %s", expectedIP, gotIP)
  962. }
  963. }
  964. _, _, err = allocator.RequestAddress(pool, nil, nil)
  965. if err != ipamapi.ErrNoAvailableIPs {
  966. t.Fatal("Did not get expected error when pool is exhausted.")
  967. }
  968. }
  969. }
  970. func TestRelease(t *testing.T) {
  971. var (
  972. subnet = "192.168.0.0/23"
  973. )
  974. for _, store := range []bool{false, true} {
  975. a, err := getAllocator(store)
  976. assert.NilError(t, err)
  977. pid, _, _, err := a.RequestPool(localAddressSpace, subnet, "", nil, false)
  978. if err != nil {
  979. t.Fatal(err)
  980. }
  981. // Allocate all addresses
  982. for err != ipamapi.ErrNoAvailableIPs {
  983. _, _, err = a.RequestAddress(pid, nil, nil)
  984. }
  985. toRelease := []struct {
  986. address string
  987. }{
  988. {"192.168.0.1"},
  989. {"192.168.0.2"},
  990. {"192.168.0.3"},
  991. {"192.168.0.4"},
  992. {"192.168.0.5"},
  993. {"192.168.0.6"},
  994. {"192.168.0.7"},
  995. {"192.168.0.8"},
  996. {"192.168.0.9"},
  997. {"192.168.0.10"},
  998. {"192.168.0.30"},
  999. {"192.168.0.31"},
  1000. {"192.168.1.32"},
  1001. {"192.168.0.254"},
  1002. {"192.168.1.1"},
  1003. {"192.168.1.2"},
  1004. {"192.168.1.3"},
  1005. {"192.168.1.253"},
  1006. {"192.168.1.254"},
  1007. }
  1008. // One by one, release the address and request again. We should get the same IP
  1009. for i, inp := range toRelease {
  1010. ip0 := net.ParseIP(inp.address)
  1011. a.ReleaseAddress(pid, ip0)
  1012. bm := a.addresses[SubnetKey{localAddressSpace, subnet, ""}]
  1013. if bm.Unselected() != 1 {
  1014. t.Fatalf("Failed to update free address count after release. Expected %d, Found: %d", i+1, bm.Unselected())
  1015. }
  1016. nw, _, err := a.RequestAddress(pid, nil, nil)
  1017. if err != nil {
  1018. t.Fatalf("Failed to obtain the address: %s", err.Error())
  1019. }
  1020. ip := nw.IP
  1021. if !ip0.Equal(ip) {
  1022. t.Fatalf("Failed to obtain the same address. Expected: %s, Got: %s", ip0, ip)
  1023. }
  1024. }
  1025. }
  1026. }
  1027. func assertGetAddress(t *testing.T, subnet string) {
  1028. var (
  1029. err error
  1030. printTime = false
  1031. a = &Allocator{}
  1032. )
  1033. _, sub, _ := net.ParseCIDR(subnet)
  1034. ones, bits := sub.Mask.Size()
  1035. zeroes := bits - ones
  1036. numAddresses := 1 << uint(zeroes)
  1037. bm, err := bitseq.NewHandle("ipam_test", nil, "default/"+subnet, uint64(numAddresses))
  1038. if err != nil {
  1039. t.Fatal(err)
  1040. }
  1041. start := time.Now()
  1042. run := 0
  1043. for err != ipamapi.ErrNoAvailableIPs {
  1044. _, err = a.getAddress(sub, bm, nil, nil, false)
  1045. run++
  1046. }
  1047. if printTime {
  1048. fmt.Printf("\nTaken %v, to allocate all addresses on %s. (nemAddresses: %d. Runs: %d)", time.Since(start), subnet, numAddresses, run)
  1049. }
  1050. if bm.Unselected() != 0 {
  1051. t.Fatalf("Unexpected free count after reserving all addresses: %d", bm.Unselected())
  1052. }
  1053. /*
  1054. if bm.Head.Block != expectedMax || bm.Head.Count != numBlocks {
  1055. t.Fatalf("Failed to effectively reserve all addresses on %s. Expected (0x%x, %d) as first sequence. Found (0x%x,%d)",
  1056. subnet, expectedMax, numBlocks, bm.Head.Block, bm.Head.Count)
  1057. }
  1058. */
  1059. }
  1060. func assertNRequests(t *testing.T, subnet string, numReq int, lastExpectedIP string) {
  1061. var (
  1062. nw *net.IPNet
  1063. printTime = false
  1064. )
  1065. lastIP := net.ParseIP(lastExpectedIP)
  1066. for _, store := range []bool{false, true} {
  1067. a, err := getAllocator(store)
  1068. assert.NilError(t, err)
  1069. pid, _, _, err := a.RequestPool(localAddressSpace, subnet, "", nil, false)
  1070. if err != nil {
  1071. t.Fatal(err)
  1072. }
  1073. i := 0
  1074. start := time.Now()
  1075. for ; i < numReq; i++ {
  1076. nw, _, err = a.RequestAddress(pid, nil, nil)
  1077. }
  1078. if printTime {
  1079. fmt.Printf("\nTaken %v, to allocate %d addresses on %s\n", time.Since(start), numReq, subnet)
  1080. }
  1081. if !lastIP.Equal(nw.IP) {
  1082. t.Fatalf("Wrong last IP. Expected %s. Got: %s (err: %v, ind: %d)", lastExpectedIP, nw.IP.String(), err, i)
  1083. }
  1084. }
  1085. }
  1086. func benchmarkRequest(b *testing.B, a *Allocator, subnet string) {
  1087. pid, _, _, err := a.RequestPool(localAddressSpace, subnet, "", nil, false)
  1088. for err != ipamapi.ErrNoAvailableIPs {
  1089. _, _, err = a.RequestAddress(pid, nil, nil)
  1090. }
  1091. }
  1092. func BenchmarkRequest(b *testing.B) {
  1093. subnets := []string{
  1094. "10.0.0.0/24",
  1095. "10.0.0.0/16",
  1096. "10.0.0.0/8",
  1097. }
  1098. for _, subnet := range subnets {
  1099. name := fmt.Sprintf("%vSubnet", subnet)
  1100. b.Run(name, func(b *testing.B) {
  1101. a, _ := getAllocator(true)
  1102. benchmarkRequest(b, a, subnet)
  1103. })
  1104. }
  1105. }
  1106. func TestAllocateRandomDeallocate(t *testing.T) {
  1107. for _, store := range []bool{false, true} {
  1108. testAllocateRandomDeallocate(t, "172.25.0.0/16", "", 384, store)
  1109. testAllocateRandomDeallocate(t, "172.25.0.0/16", "172.25.252.0/22", 384, store)
  1110. }
  1111. }
  1112. func testAllocateRandomDeallocate(t *testing.T, pool, subPool string, num int, store bool) {
  1113. ds, err := randomLocalStore(store)
  1114. assert.NilError(t, err)
  1115. a, err := NewAllocator(ds, nil)
  1116. if err != nil {
  1117. t.Fatal(err)
  1118. }
  1119. pid, _, _, err := a.RequestPool(localAddressSpace, pool, subPool, nil, false)
  1120. if err != nil {
  1121. t.Fatal(err)
  1122. }
  1123. // Allocate num ip addresses
  1124. indices := make(map[int]*net.IPNet, num)
  1125. allocated := make(map[string]bool, num)
  1126. for i := 0; i < num; i++ {
  1127. ip, _, err := a.RequestAddress(pid, nil, nil)
  1128. if err != nil {
  1129. t.Fatal(err)
  1130. }
  1131. ips := ip.String()
  1132. if _, ok := allocated[ips]; ok {
  1133. t.Fatalf("Address %s is already allocated", ips)
  1134. }
  1135. allocated[ips] = true
  1136. indices[i] = ip
  1137. }
  1138. if len(indices) != len(allocated) || len(indices) != num {
  1139. t.Fatalf("Unexpected number of allocated addresses: (%d,%d).", len(indices), len(allocated))
  1140. }
  1141. seed := time.Now().Unix()
  1142. rand.Seed(seed)
  1143. // Deallocate half of the allocated addresses following a random pattern
  1144. pattern := rand.Perm(num)
  1145. for i := 0; i < num/2; i++ {
  1146. idx := pattern[i]
  1147. ip := indices[idx]
  1148. err := a.ReleaseAddress(pid, ip.IP)
  1149. if err != nil {
  1150. t.Fatalf("Unexpected failure on deallocation of %s: %v.\nSeed: %d.", ip, err, seed)
  1151. }
  1152. delete(indices, idx)
  1153. delete(allocated, ip.String())
  1154. }
  1155. // Request a quarter of addresses
  1156. for i := 0; i < num/2; i++ {
  1157. ip, _, err := a.RequestAddress(pid, nil, nil)
  1158. if err != nil {
  1159. t.Fatal(err)
  1160. }
  1161. ips := ip.String()
  1162. if _, ok := allocated[ips]; ok {
  1163. t.Fatalf("\nAddress %s is already allocated.\nSeed: %d.", ips, seed)
  1164. }
  1165. allocated[ips] = true
  1166. }
  1167. if len(allocated) != num {
  1168. t.Fatalf("Unexpected number of allocated addresses: %d.\nSeed: %d.", len(allocated), seed)
  1169. }
  1170. }
  1171. func TestRetrieveFromStore(t *testing.T) {
  1172. num := 200
  1173. ds, err := randomLocalStore(true)
  1174. if err != nil {
  1175. t.Fatal(err)
  1176. }
  1177. a, err := NewAllocator(ds, nil)
  1178. if err != nil {
  1179. t.Fatal(err)
  1180. }
  1181. pid, _, _, err := a.RequestPool(localAddressSpace, "172.25.0.0/16", "", nil, false)
  1182. if err != nil {
  1183. t.Fatal(err)
  1184. }
  1185. for i := 0; i < num; i++ {
  1186. if _, _, err := a.RequestAddress(pid, nil, nil); err != nil {
  1187. t.Fatal(err)
  1188. }
  1189. }
  1190. // Restore
  1191. a1, err := NewAllocator(ds, nil)
  1192. if err != nil {
  1193. t.Fatal(err)
  1194. }
  1195. a1.refresh(localAddressSpace)
  1196. db := a.DumpDatabase()
  1197. db1 := a1.DumpDatabase()
  1198. if db != db1 {
  1199. t.Fatalf("Unexpected db change.\nExpected:%s\nGot:%s", db, db1)
  1200. }
  1201. checkDBEquality(a, a1, t)
  1202. pid, _, _, err = a1.RequestPool(localAddressSpace, "172.25.0.0/16", "172.25.1.0/24", nil, false)
  1203. if err != nil {
  1204. t.Fatal(err)
  1205. }
  1206. for i := 0; i < num/2; i++ {
  1207. if _, _, err := a1.RequestAddress(pid, nil, nil); err != nil {
  1208. t.Fatal(err)
  1209. }
  1210. }
  1211. // Restore
  1212. a2, err := NewAllocator(ds, nil)
  1213. if err != nil {
  1214. t.Fatal(err)
  1215. }
  1216. a2.refresh(localAddressSpace)
  1217. checkDBEquality(a1, a2, t)
  1218. pid, _, _, err = a2.RequestPool(localAddressSpace, "172.25.0.0/16", "172.25.2.0/24", nil, false)
  1219. if err != nil {
  1220. t.Fatal(err)
  1221. }
  1222. for i := 0; i < num/2; i++ {
  1223. if _, _, err := a2.RequestAddress(pid, nil, nil); err != nil {
  1224. t.Fatal(err)
  1225. }
  1226. }
  1227. // Restore
  1228. a3, err := NewAllocator(ds, nil)
  1229. if err != nil {
  1230. t.Fatal(err)
  1231. }
  1232. a3.refresh(localAddressSpace)
  1233. checkDBEquality(a2, a3, t)
  1234. pid, _, _, err = a3.RequestPool(localAddressSpace, "172.26.0.0/16", "", nil, false)
  1235. if err != nil {
  1236. t.Fatal(err)
  1237. }
  1238. for i := 0; i < num/2; i++ {
  1239. if _, _, err := a3.RequestAddress(pid, nil, nil); err != nil {
  1240. t.Fatal(err)
  1241. }
  1242. }
  1243. // Restore
  1244. a4, err := NewAllocator(ds, nil)
  1245. if err != nil {
  1246. t.Fatal(err)
  1247. }
  1248. a4.refresh(localAddressSpace)
  1249. checkDBEquality(a3, a4, t)
  1250. }
  1251. func checkDBEquality(a1, a2 *Allocator, t *testing.T) {
  1252. for k, cnf1 := range a1.addrSpaces[localAddressSpace].subnets {
  1253. cnf2 := a2.addrSpaces[localAddressSpace].subnets[k]
  1254. if cnf1.String() != cnf2.String() {
  1255. t.Fatalf("%s\n%s", cnf1, cnf2)
  1256. }
  1257. if cnf1.Range == nil {
  1258. a2.retrieveBitmask(k, cnf1.Pool)
  1259. }
  1260. }
  1261. for k, bm1 := range a1.addresses {
  1262. bm2 := a2.addresses[k]
  1263. if bm1.String() != bm2.String() {
  1264. t.Fatalf("%s\n%s", bm1, bm2)
  1265. }
  1266. }
  1267. }
  1268. const (
  1269. numInstances = 5
  1270. first = 0
  1271. last = numInstances - 1
  1272. )
  1273. var (
  1274. allocator *Allocator
  1275. start = make(chan struct{})
  1276. done = make(chan chan struct{}, numInstances-1)
  1277. pools = make([]*net.IPNet, numInstances)
  1278. )
  1279. func runParallelTests(t *testing.T, instance int) {
  1280. var err error
  1281. t.Parallel()
  1282. pTest := flag.Lookup("test.parallel")
  1283. if pTest == nil {
  1284. t.Skip("Skipped because test.parallel flag not set;")
  1285. }
  1286. numParallel, err := strconv.Atoi(pTest.Value.String())
  1287. if err != nil {
  1288. t.Fatal(err)
  1289. }
  1290. if numParallel < numInstances {
  1291. t.Skip("Skipped because t.parallel was less than ", numInstances)
  1292. }
  1293. // The first instance creates the allocator, gives the start
  1294. // and finally checks the pools each instance was assigned
  1295. if instance == first {
  1296. allocator, err = getAllocator(true)
  1297. if err != nil {
  1298. t.Fatal(err)
  1299. }
  1300. close(start)
  1301. }
  1302. if instance != first {
  1303. <-start
  1304. instDone := make(chan struct{})
  1305. done <- instDone
  1306. defer close(instDone)
  1307. if instance == last {
  1308. defer close(done)
  1309. }
  1310. }
  1311. _, pools[instance], _, err = allocator.RequestPool(localAddressSpace, "", "", nil, false)
  1312. if err != nil {
  1313. t.Fatal(err)
  1314. }
  1315. if instance == first {
  1316. for instDone := range done {
  1317. <-instDone
  1318. }
  1319. // Now check each instance got a different pool
  1320. for i := 0; i < numInstances; i++ {
  1321. for j := i + 1; j < numInstances; j++ {
  1322. if types.CompareIPNet(pools[i], pools[j]) {
  1323. t.Fatalf("Instance %d and %d were given the same predefined pool: %v", i, j, pools)
  1324. }
  1325. }
  1326. }
  1327. }
  1328. }
  1329. func TestRequestReleaseAddressDuplicate(t *testing.T) {
  1330. a, err := getAllocator(false)
  1331. if err != nil {
  1332. t.Fatal(err)
  1333. }
  1334. type IP struct {
  1335. ip *net.IPNet
  1336. ref int
  1337. }
  1338. ips := []IP{}
  1339. allocatedIPs := []*net.IPNet{}
  1340. a.addrSpaces["rosso"] = &addrSpace{
  1341. id: dsConfigKey + "/" + "rosso",
  1342. ds: a.addrSpaces[localAddressSpace].ds,
  1343. alloc: a.addrSpaces[localAddressSpace].alloc,
  1344. scope: a.addrSpaces[localAddressSpace].scope,
  1345. subnets: map[SubnetKey]*PoolData{},
  1346. }
  1347. opts := map[string]string{
  1348. ipamapi.AllocSerialPrefix: "true",
  1349. }
  1350. var l sync.Mutex
  1351. poolID, _, _, err := a.RequestPool("rosso", "198.168.0.0/23", "", nil, false)
  1352. if err != nil {
  1353. t.Fatal(err)
  1354. }
  1355. group := new(errgroup.Group)
  1356. for err == nil {
  1357. var c *net.IPNet
  1358. if c, _, err = a.RequestAddress(poolID, nil, opts); err == nil {
  1359. l.Lock()
  1360. ips = append(ips, IP{c, 1})
  1361. l.Unlock()
  1362. allocatedIPs = append(allocatedIPs, c)
  1363. if len(allocatedIPs) > 500 {
  1364. i := rand.Intn(len(allocatedIPs) - 1)
  1365. ip := allocatedIPs[i]
  1366. group.Go(func() error {
  1367. if err = a.ReleaseAddress(poolID, ip.IP); err != nil {
  1368. return err
  1369. }
  1370. l.Lock()
  1371. ips = append(ips, IP{ip, -1})
  1372. l.Unlock()
  1373. return nil
  1374. })
  1375. allocatedIPs = append(allocatedIPs[:i], allocatedIPs[i+1:]...)
  1376. }
  1377. }
  1378. }
  1379. if err := group.Wait(); err != nil {
  1380. t.Fatal(err)
  1381. }
  1382. refMap := make(map[string]int)
  1383. for _, ip := range ips {
  1384. refMap[ip.ip.String()] = refMap[ip.ip.String()] + ip.ref
  1385. if refMap[ip.ip.String()] < 0 {
  1386. t.Fatalf("IP %s was previously released", ip.ip.String())
  1387. }
  1388. if refMap[ip.ip.String()] > 1 {
  1389. t.Fatalf("IP %s was previously allocated", ip.ip.String())
  1390. }
  1391. }
  1392. }
  1393. func TestParallelPredefinedRequest1(t *testing.T) {
  1394. runParallelTests(t, 0)
  1395. }
  1396. func TestParallelPredefinedRequest2(t *testing.T) {
  1397. runParallelTests(t, 1)
  1398. }
  1399. func TestParallelPredefinedRequest3(t *testing.T) {
  1400. runParallelTests(t, 2)
  1401. }
  1402. func TestParallelPredefinedRequest4(t *testing.T) {
  1403. runParallelTests(t, 3)
  1404. }
  1405. func TestParallelPredefinedRequest5(t *testing.T) {
  1406. runParallelTests(t, 4)
  1407. }