You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

IndexPageCache.java 48KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601
  1. /*
  2. Copyright (c) 2008 Health Market Science, Inc.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package com.healthmarketscience.jackcess.impl;
  14. import java.io.IOException;
  15. import java.lang.ref.Reference;
  16. import java.lang.ref.SoftReference;
  17. import java.util.AbstractList;
  18. import java.util.ArrayList;
  19. import java.util.Collections;
  20. import java.util.HashMap;
  21. import java.util.Iterator;
  22. import java.util.LinkedHashMap;
  23. import java.util.LinkedList;
  24. import java.util.List;
  25. import java.util.Map;
  26. import java.util.Queue;
  27. import java.util.RandomAccess;
  28. import static com.healthmarketscience.jackcess.impl.IndexData.*;
  29. import com.healthmarketscience.jackcess.impl.IndexData.DataPage;
  30. import org.apache.commons.lang3.builder.ToStringBuilder;
  31. /**
  32. * Manager of the index pages for a IndexData.
  33. * @author James Ahlborn
  34. */
  35. public class IndexPageCache
  36. {
  37. private enum UpdateType {
  38. ADD, REMOVE, REPLACE;
  39. }
  40. /** max number of pages to cache (unless a write operation is in
  41. progress) */
  42. private static final int MAX_CACHE_SIZE = 25;
  43. /** the index whose pages this cache is managing */
  44. private final IndexData _indexData;
  45. /** the root page for the index */
  46. private DataPageMain _rootPage;
  47. /** the currently loaded pages for this index, pageNumber -> page */
  48. private final Map<Integer, DataPageMain> _dataPages =
  49. new LinkedHashMap<Integer, DataPageMain>(16, 0.75f, true) {
  50. private static final long serialVersionUID = 0L;
  51. @Override
  52. protected boolean removeEldestEntry(Map.Entry<Integer, DataPageMain> e) {
  53. // only purge when the size is too big and a logical write operation is
  54. // not in progress (while an update is happening, the pages can be in
  55. // flux and removing pages from the cache can cause problems)
  56. if((size() > MAX_CACHE_SIZE) && !getPageChannel().isWriting()) {
  57. purgeOldPages();
  58. }
  59. return false;
  60. }
  61. };
  62. /** the currently modified index pages */
  63. private final List<CacheDataPage> _modifiedPages =
  64. new ArrayList<CacheDataPage>();
  65. public IndexPageCache(IndexData indexData) {
  66. _indexData = indexData;
  67. }
  68. public IndexData getIndexData() {
  69. return _indexData;
  70. }
  71. public PageChannel getPageChannel() {
  72. return getIndexData().getPageChannel();
  73. }
  74. /**
  75. * Sets the root page for this index, must be called before normal usage.
  76. *
  77. * @param pageNumber the root page number
  78. */
  79. public void setRootPageNumber(int pageNumber) throws IOException {
  80. _rootPage = getDataPage(pageNumber);
  81. // root page has no parent
  82. _rootPage.initParentPage(INVALID_INDEX_PAGE_NUMBER, false);
  83. }
  84. /**
  85. * Writes any outstanding changes for this index to the file.
  86. */
  87. public void write()
  88. throws IOException
  89. {
  90. // first discard any empty pages
  91. handleEmptyPages();
  92. // next, handle any necessary page splitting
  93. preparePagesForWriting();
  94. // finally, write all the modified pages (which are not being deleted)
  95. writeDataPages();
  96. // after we write everything, we can purge our cache if necessary
  97. if(_dataPages.size() > MAX_CACHE_SIZE) {
  98. purgeOldPages();
  99. }
  100. }
  101. /**
  102. * Handles any modified pages which are empty as the first pass during a
  103. * {@link #write} call. All empty pages are removed from the _modifiedPages
  104. * collection by this method.
  105. */
  106. private void handleEmptyPages() throws IOException
  107. {
  108. for(Iterator<CacheDataPage> iter = _modifiedPages.iterator();
  109. iter.hasNext(); ) {
  110. CacheDataPage cacheDataPage = iter.next();
  111. if(cacheDataPage._extra._entryView.isEmpty()) {
  112. if(!cacheDataPage._main.isRoot()) {
  113. deleteDataPage(cacheDataPage);
  114. } else {
  115. writeDataPage(cacheDataPage);
  116. }
  117. iter.remove();
  118. }
  119. }
  120. }
  121. /**
  122. * Prepares any non-empty modified pages for writing as the second pass
  123. * during a {@link #write} call. Updates entry prefixes, promotes/demotes
  124. * tail pages, and splits pages as needed.
  125. */
  126. private void preparePagesForWriting() throws IOException
  127. {
  128. boolean splitPages = false;
  129. int maxPageEntrySize = getIndexData().getMaxPageEntrySize();
  130. // we need to continue looping through all the pages until we do not split
  131. // any pages (because a split may cascade up the tree)
  132. do {
  133. splitPages = false;
  134. // we might be adding to this list while iterating, so we can't use an
  135. // iterator
  136. for(int i = 0; i < _modifiedPages.size(); ++i) {
  137. CacheDataPage cacheDataPage = _modifiedPages.get(i);
  138. if(!cacheDataPage.isLeaf()) {
  139. // see if we need to update any child tail status
  140. DataPageMain dpMain = cacheDataPage._main;
  141. int size = cacheDataPage._extra._entryView.size();
  142. if(dpMain.hasChildTail()) {
  143. if(size == 1) {
  144. demoteTail(cacheDataPage);
  145. }
  146. } else {
  147. if(size > 1) {
  148. promoteTail(cacheDataPage);
  149. }
  150. }
  151. }
  152. // look for pages with more entries than can fit on a page
  153. if(cacheDataPage.getTotalEntrySize() > maxPageEntrySize) {
  154. // make sure the prefix is up-to-date (this may have gotten
  155. // discarded by one of the update entry methods)
  156. cacheDataPage._extra.updateEntryPrefix();
  157. // now, see if the page will fit when compressed
  158. if(cacheDataPage.getCompressedEntrySize() > maxPageEntrySize) {
  159. // need to split this page
  160. splitPages = true;
  161. splitDataPage(cacheDataPage);
  162. }
  163. }
  164. }
  165. } while(splitPages);
  166. }
  167. /**
  168. * Writes any non-empty modified pages as the last pass during a
  169. * {@link #write} call. Clears the _modifiedPages collection when finised.
  170. */
  171. private void writeDataPages() throws IOException
  172. {
  173. for(CacheDataPage cacheDataPage : _modifiedPages) {
  174. if(cacheDataPage._extra._entryView.isEmpty()) {
  175. throw new IllegalStateException(withErrorContext(
  176. "Unexpected empty page " + cacheDataPage));
  177. }
  178. writeDataPage(cacheDataPage);
  179. }
  180. _modifiedPages.clear();
  181. }
  182. /**
  183. * Returns a CacheDataPage for the given page number, may be {@code null} if
  184. * the given page number is invalid. Loads the given page if necessary.
  185. */
  186. public CacheDataPage getCacheDataPage(Integer pageNumber)
  187. throws IOException
  188. {
  189. DataPageMain main = getDataPage(pageNumber);
  190. return((main != null) ? new CacheDataPage(main) : null);
  191. }
  192. /**
  193. * Returns a DataPageMain for the given page number, may be {@code null} if
  194. * the given page number is invalid. Loads the given page if necessary.
  195. */
  196. private DataPageMain getDataPage(Integer pageNumber)
  197. throws IOException
  198. {
  199. DataPageMain dataPage = _dataPages.get(pageNumber);
  200. if((dataPage == null) && (pageNumber > INVALID_INDEX_PAGE_NUMBER)) {
  201. dataPage = readDataPage(pageNumber)._main;
  202. _dataPages.put(pageNumber, dataPage);
  203. }
  204. return dataPage;
  205. }
  206. /**
  207. * Writes the given index page to the file.
  208. */
  209. private void writeDataPage(CacheDataPage cacheDataPage)
  210. throws IOException
  211. {
  212. getIndexData().writeDataPage(cacheDataPage);
  213. // lastly, mark the page as no longer modified
  214. cacheDataPage._extra._modified = false;
  215. }
  216. /**
  217. * Deletes the given index page from the file (clears the page).
  218. */
  219. private void deleteDataPage(CacheDataPage cacheDataPage)
  220. throws IOException
  221. {
  222. // free this database page
  223. getPageChannel().deallocatePage(cacheDataPage._main._pageNumber);
  224. // discard from our cache
  225. _dataPages.remove(cacheDataPage._main._pageNumber);
  226. // lastly, mark the page as no longer modified
  227. cacheDataPage._extra._modified = false;
  228. }
  229. /**
  230. * Reads the given index page from the file.
  231. */
  232. private CacheDataPage readDataPage(Integer pageNumber)
  233. throws IOException
  234. {
  235. DataPageMain dataPage = new DataPageMain(pageNumber);
  236. DataPageExtra extra = new DataPageExtra();
  237. CacheDataPage cacheDataPage = new CacheDataPage(dataPage, extra);
  238. getIndexData().readDataPage(cacheDataPage);
  239. // associate the extra info with the main data page
  240. dataPage.setExtra(extra);
  241. return cacheDataPage;
  242. }
  243. /**
  244. * Removes the entry with the given index from the given page.
  245. *
  246. * @param cacheDataPage the page from which to remove the entry
  247. * @param entryIdx the index of the entry to remove
  248. */
  249. private Entry removeEntry(CacheDataPage cacheDataPage, int entryIdx)
  250. throws IOException
  251. {
  252. return updateEntry(cacheDataPage, entryIdx, null, UpdateType.REMOVE);
  253. }
  254. /**
  255. * Adds the entry to the given page at the given index.
  256. *
  257. * @param cacheDataPage the page to which to add the entry
  258. * @param entryIdx the index at which to add the entry
  259. * @param newEntry the entry to add
  260. */
  261. private void addEntry(CacheDataPage cacheDataPage,
  262. int entryIdx,
  263. Entry newEntry)
  264. throws IOException
  265. {
  266. updateEntry(cacheDataPage, entryIdx, newEntry, UpdateType.ADD);
  267. }
  268. /**
  269. * Updates the entries on the given page according to the given updateType.
  270. *
  271. * @param cacheDataPage the page to update
  272. * @param entryIdx the index at which to add/remove/replace the entry
  273. * @param newEntry the entry to add/replace
  274. * @param upType the type of update to make
  275. */
  276. private Entry updateEntry(CacheDataPage cacheDataPage,
  277. int entryIdx,
  278. Entry newEntry,
  279. UpdateType upType)
  280. throws IOException
  281. {
  282. DataPageMain dpMain = cacheDataPage._main;
  283. DataPageExtra dpExtra = cacheDataPage._extra;
  284. if(newEntry != null) {
  285. validateEntryForPage(dpMain, newEntry);
  286. }
  287. // note, it's slightly ucky, but we need to load the parent page before we
  288. // start mucking with our entries because our parent may use our entries.
  289. CacheDataPage parentDataPage = (!dpMain.isRoot() ?
  290. new CacheDataPage(dpMain.getParentPage()) :
  291. null);
  292. Entry oldLastEntry = dpExtra._entryView.getLast();
  293. Entry oldEntry = null;
  294. int entrySizeDiff = 0;
  295. switch(upType) {
  296. case ADD:
  297. dpExtra._entryView.add(entryIdx, newEntry);
  298. entrySizeDiff += newEntry.size();
  299. break;
  300. case REPLACE:
  301. oldEntry = dpExtra._entryView.set(entryIdx, newEntry);
  302. entrySizeDiff += newEntry.size() - oldEntry.size();
  303. break;
  304. case REMOVE: {
  305. oldEntry = dpExtra._entryView.remove(entryIdx);
  306. entrySizeDiff -= oldEntry.size();
  307. break;
  308. }
  309. default:
  310. throw new RuntimeException(withErrorContext(
  311. "unknown update type " + upType));
  312. }
  313. boolean updateLast = (oldLastEntry != dpExtra._entryView.getLast());
  314. // child tail entry updates do not modify the page
  315. if(!updateLast || !dpMain.hasChildTail()) {
  316. dpExtra._totalEntrySize += entrySizeDiff;
  317. setModified(cacheDataPage);
  318. // for now, just clear the prefix, we'll fix it later
  319. dpExtra._entryPrefix = EMPTY_PREFIX;
  320. }
  321. if(dpExtra._entryView.isEmpty()) {
  322. // this page is dead
  323. removeDataPage(parentDataPage, cacheDataPage, oldLastEntry);
  324. return oldEntry;
  325. }
  326. // determine if we need to update our parent page
  327. if(!updateLast || dpMain.isRoot()) {
  328. // no parent
  329. return oldEntry;
  330. }
  331. // the update to the last entry needs to be propagated to our parent
  332. replaceParentEntry(parentDataPage, cacheDataPage, oldLastEntry);
  333. return oldEntry;
  334. }
  335. /**
  336. * Removes an index page which has become empty. If this page is the root
  337. * page, just clears it.
  338. *
  339. * @param parentDataPage the parent of the removed page
  340. * @param cacheDataPage the page to remove
  341. * @param oldLastEntry the last entry for this page (before it was removed)
  342. */
  343. private void removeDataPage(CacheDataPage parentDataPage,
  344. CacheDataPage cacheDataPage,
  345. Entry oldLastEntry)
  346. throws IOException
  347. {
  348. DataPageMain dpMain = cacheDataPage._main;
  349. DataPageExtra dpExtra = cacheDataPage._extra;
  350. if(dpMain.hasChildTail()) {
  351. throw new IllegalStateException(withErrorContext("Still has child tail?"));
  352. }
  353. if(dpExtra._totalEntrySize != 0) {
  354. throw new IllegalStateException(withErrorContext(
  355. "Empty page but size is not 0? " + dpExtra._totalEntrySize + ", " +
  356. cacheDataPage));
  357. }
  358. if(dpMain.isRoot()) {
  359. // clear out this page (we don't actually remove it)
  360. dpExtra._entryPrefix = EMPTY_PREFIX;
  361. // when the root page becomes empty, it becomes a leaf page again
  362. dpMain._leaf = true;
  363. return;
  364. }
  365. // remove this page from its parent page
  366. updateParentEntry(parentDataPage, cacheDataPage, oldLastEntry, null,
  367. UpdateType.REMOVE);
  368. // remove this page from any next/prev pages
  369. removeFromPeers(cacheDataPage);
  370. }
  371. /**
  372. * Removes a now empty index page from its next and previous peers.
  373. *
  374. * @param cacheDataPage the page to remove
  375. */
  376. private void removeFromPeers(CacheDataPage cacheDataPage)
  377. throws IOException
  378. {
  379. DataPageMain dpMain = cacheDataPage._main;
  380. Integer prevPageNumber = dpMain._prevPageNumber;
  381. Integer nextPageNumber = dpMain._nextPageNumber;
  382. DataPageMain prevMain = dpMain.getPrevPage();
  383. if(prevMain != null) {
  384. setModified(new CacheDataPage(prevMain));
  385. prevMain._nextPageNumber = nextPageNumber;
  386. }
  387. DataPageMain nextMain = dpMain.getNextPage();
  388. if(nextMain != null) {
  389. setModified(new CacheDataPage(nextMain));
  390. nextMain._prevPageNumber = prevPageNumber;
  391. }
  392. }
  393. /**
  394. * Adds an entry for the given child page to the given parent page.
  395. *
  396. * @param parentDataPage the parent page to which to add the entry
  397. * @param childDataPage the child from which to get the entry to add
  398. */
  399. private void addParentEntry(CacheDataPage parentDataPage,
  400. CacheDataPage childDataPage)
  401. throws IOException
  402. {
  403. DataPageExtra childExtra = childDataPage._extra;
  404. updateParentEntry(parentDataPage, childDataPage, null,
  405. childExtra._entryView.getLast(), UpdateType.ADD);
  406. }
  407. /**
  408. * Replaces the entry for the given child page in the given parent page.
  409. *
  410. * @param parentDataPage the parent page in which to replace the entry
  411. * @param childDataPage the child for which the entry is being replaced
  412. * @param oldEntry the old child entry for the child page
  413. */
  414. private void replaceParentEntry(CacheDataPage parentDataPage,
  415. CacheDataPage childDataPage,
  416. Entry oldEntry)
  417. throws IOException
  418. {
  419. DataPageExtra childExtra = childDataPage._extra;
  420. updateParentEntry(parentDataPage, childDataPage, oldEntry,
  421. childExtra._entryView.getLast(), UpdateType.REPLACE);
  422. }
  423. /**
  424. * Updates the entry for the given child page in the given parent page
  425. * according to the given updateType.
  426. *
  427. * @param parentDataPage the parent page in which to update the entry
  428. * @param childDataPage the child for which the entry is being updated
  429. * @param oldEntry the old child entry to remove/replace
  430. * @param newEntry the new child entry to replace/add
  431. * @param upType the type of update to make
  432. */
  433. private void updateParentEntry(CacheDataPage parentDataPage,
  434. CacheDataPage childDataPage,
  435. Entry oldEntry, Entry newEntry,
  436. UpdateType upType)
  437. throws IOException
  438. {
  439. DataPageMain childMain = childDataPage._main;
  440. DataPageExtra parentExtra = parentDataPage._extra;
  441. if(childMain.isTail() && (upType != UpdateType.REMOVE)) {
  442. // for add or replace, update the child tail info before updating the
  443. // parent entries
  444. updateParentTail(parentDataPage, childDataPage, upType);
  445. }
  446. if(oldEntry != null) {
  447. oldEntry = oldEntry.asNodeEntry(childMain._pageNumber);
  448. }
  449. if(newEntry != null) {
  450. newEntry = newEntry.asNodeEntry(childMain._pageNumber);
  451. }
  452. boolean expectFound = true;
  453. int idx = 0;
  454. switch(upType) {
  455. case ADD:
  456. expectFound = false;
  457. idx = parentExtra._entryView.find(newEntry);
  458. break;
  459. case REPLACE:
  460. case REMOVE:
  461. idx = parentExtra._entryView.find(oldEntry);
  462. break;
  463. default:
  464. throw new RuntimeException(withErrorContext(
  465. "unknown update type " + upType));
  466. }
  467. if(idx < 0) {
  468. if(expectFound) {
  469. throw new IllegalStateException(withErrorContext(
  470. "Could not find child entry in parent; childEntry " + oldEntry +
  471. "; parent " + parentDataPage));
  472. }
  473. idx = missingIndexToInsertionPoint(idx);
  474. } else {
  475. if(!expectFound) {
  476. throw new IllegalStateException(withErrorContext(
  477. "Unexpectedly found child entry in parent; childEntry " +
  478. newEntry + "; parent " + parentDataPage));
  479. }
  480. }
  481. updateEntry(parentDataPage, idx, newEntry, upType);
  482. if(childMain.isTail() && (upType == UpdateType.REMOVE)) {
  483. // for remove, update the child tail info after updating the parent
  484. // entries
  485. updateParentTail(parentDataPage, childDataPage, upType);
  486. }
  487. }
  488. /**
  489. * Updates the child tail info in the given parent page according to the
  490. * given updateType.
  491. *
  492. * @param parentDataPage the parent page in which to update the child tail
  493. * @param childDataPage the child to add/replace
  494. * @param upType the type of update to make
  495. */
  496. private void updateParentTail(CacheDataPage parentDataPage,
  497. CacheDataPage childDataPage,
  498. UpdateType upType)
  499. {
  500. DataPageMain parentMain = parentDataPage._main;
  501. int newChildTailPageNumber =
  502. ((upType == UpdateType.REMOVE) ?
  503. INVALID_INDEX_PAGE_NUMBER :
  504. childDataPage._main._pageNumber);
  505. if(!parentMain.isChildTailPageNumber(newChildTailPageNumber)) {
  506. setModified(parentDataPage);
  507. parentMain._childTailPageNumber = newChildTailPageNumber;
  508. }
  509. }
  510. /**
  511. * Verifies that the given entry type (node/leaf) is valid for the given
  512. * page (node/leaf).
  513. *
  514. * @param dpMain the page to which the entry will be added
  515. * @param entry the entry being added
  516. * @throws IllegalStateException if the entry type does not match the page
  517. * type
  518. */
  519. private void validateEntryForPage(DataPageMain dpMain, Entry entry) {
  520. if(dpMain._leaf != entry.isLeafEntry()) {
  521. throw new IllegalStateException(withErrorContext(
  522. "Trying to update page with wrong entry type; pageLeaf " +
  523. dpMain._leaf + ", entryLeaf " + entry.isLeafEntry()));
  524. }
  525. }
  526. /**
  527. * Splits an index page which has too many entries on it.
  528. *
  529. * @param origDataPage the page to split
  530. */
  531. private void splitDataPage(CacheDataPage origDataPage)
  532. throws IOException
  533. {
  534. DataPageMain origMain = origDataPage._main;
  535. DataPageExtra origExtra = origDataPage._extra;
  536. setModified(origDataPage);
  537. int numEntries = origExtra._entries.size();
  538. if(numEntries < 2) {
  539. throw new IllegalStateException(withErrorContext(
  540. "Cannot split page with less than 2 entries " + origDataPage));
  541. }
  542. if(origMain.isRoot()) {
  543. // we can't split the root page directly, so we need to put another page
  544. // between the root page and its sub-pages, and then split that page.
  545. CacheDataPage newDataPage = nestRootDataPage(origDataPage);
  546. // now, split this new page instead
  547. origDataPage = newDataPage;
  548. origMain = newDataPage._main;
  549. origExtra = newDataPage._extra;
  550. }
  551. // note, it's slightly ucky, but we need to load the parent page before we
  552. // start mucking with our entries because our parent may use our entries.
  553. DataPageMain parentMain = origMain.getParentPage();
  554. CacheDataPage parentDataPage = new CacheDataPage(parentMain);
  555. // note, there are many, many ways this could be improved/tweaked. for
  556. // now, we just want it to be functional...
  557. // so, we will naively move half the entries from one page to a new page.
  558. CacheDataPage newDataPage = allocateNewCacheDataPage(
  559. parentMain._pageNumber, origMain._leaf);
  560. DataPageMain newMain = newDataPage._main;
  561. DataPageExtra newExtra = newDataPage._extra;
  562. List<Entry> headEntries =
  563. origExtra._entries.subList(0, ((numEntries + 1) / 2));
  564. // move first half of the entries from old page to new page (so we do not
  565. // need to muck with any tail entries)
  566. for(Entry headEntry : headEntries) {
  567. newExtra._totalEntrySize += headEntry.size();
  568. newExtra._entries.add(headEntry);
  569. }
  570. newExtra.setEntryView(newMain);
  571. // remove the moved entries from the old page
  572. headEntries.clear();
  573. origExtra._entryPrefix = EMPTY_PREFIX;
  574. origExtra._totalEntrySize -= newExtra._totalEntrySize;
  575. // insert this new page between the old page and any previous page
  576. addToPeersBefore(newDataPage, origDataPage);
  577. if(!newMain._leaf) {
  578. // reparent the children pages of the new page
  579. reparentChildren(newDataPage);
  580. // if the children of this page are also node pages, then the next/prev
  581. // links should not cross parent boundaries (the leaf pages are linked
  582. // from beginning to end, but child node pages are only linked within
  583. // the same parent)
  584. DataPageMain childMain = newMain.getChildPage(
  585. newExtra._entryView.getLast());
  586. if(!childMain._leaf) {
  587. separateFromNextPeer(new CacheDataPage(childMain));
  588. }
  589. }
  590. // lastly, we need to add the new page to the parent page's entries
  591. addParentEntry(parentDataPage, newDataPage);
  592. }
  593. /**
  594. * Copies the current root page info into a new page and nests this page
  595. * under the root page. This must be done when the root page needs to be
  596. * split.
  597. *
  598. * @param rootDataPage the root data page
  599. *
  600. * @return the newly created page nested under the root page
  601. */
  602. private CacheDataPage nestRootDataPage(CacheDataPage rootDataPage)
  603. throws IOException
  604. {
  605. DataPageMain rootMain = rootDataPage._main;
  606. DataPageExtra rootExtra = rootDataPage._extra;
  607. if(!rootMain.isRoot()) {
  608. throw new IllegalArgumentException(withErrorContext(
  609. "should be called with root, duh"));
  610. }
  611. CacheDataPage newDataPage =
  612. allocateNewCacheDataPage(rootMain._pageNumber, rootMain._leaf);
  613. DataPageMain newMain = newDataPage._main;
  614. DataPageExtra newExtra = newDataPage._extra;
  615. // move entries to new page
  616. newMain._childTailPageNumber = rootMain._childTailPageNumber;
  617. newExtra._entries = rootExtra._entries;
  618. newExtra._entryPrefix = rootExtra._entryPrefix;
  619. newExtra._totalEntrySize = rootExtra._totalEntrySize;
  620. newExtra.setEntryView(newMain);
  621. if(!newMain._leaf) {
  622. // we need to re-parent all the child pages
  623. reparentChildren(newDataPage);
  624. }
  625. // clear the root page
  626. rootMain._leaf = false;
  627. rootMain._childTailPageNumber = INVALID_INDEX_PAGE_NUMBER;
  628. rootExtra._entries = new ArrayList<Entry>();
  629. rootExtra._entryPrefix = EMPTY_PREFIX;
  630. rootExtra._totalEntrySize = 0;
  631. rootExtra.setEntryView(rootMain);
  632. // add the new page as the first child of the root page
  633. addParentEntry(rootDataPage, newDataPage);
  634. return newDataPage;
  635. }
  636. /**
  637. * Allocates a new index page with the given parent page and type.
  638. *
  639. * @param parentPageNumber the parent page for the new page
  640. * @param isLeaf whether or not the new page is a leaf page
  641. *
  642. * @return the newly created page
  643. */
  644. private CacheDataPage allocateNewCacheDataPage(Integer parentPageNumber,
  645. boolean isLeaf)
  646. throws IOException
  647. {
  648. DataPageMain dpMain = new DataPageMain(getPageChannel().allocateNewPage());
  649. DataPageExtra dpExtra = new DataPageExtra();
  650. dpMain.initParentPage(parentPageNumber, false);
  651. dpMain._leaf = isLeaf;
  652. dpMain._prevPageNumber = INVALID_INDEX_PAGE_NUMBER;
  653. dpMain._nextPageNumber = INVALID_INDEX_PAGE_NUMBER;
  654. dpMain._childTailPageNumber = INVALID_INDEX_PAGE_NUMBER;
  655. dpExtra._entries = new ArrayList<Entry>();
  656. dpExtra._entryPrefix = EMPTY_PREFIX;
  657. dpMain.setExtra(dpExtra);
  658. // add to our page cache
  659. _dataPages.put(dpMain._pageNumber, dpMain);
  660. // update owned pages cache
  661. _indexData.addOwnedPage(dpMain._pageNumber);
  662. // needs to be written out
  663. CacheDataPage cacheDataPage = new CacheDataPage(dpMain, dpExtra);
  664. setModified(cacheDataPage);
  665. return cacheDataPage;
  666. }
  667. /**
  668. * Inserts the new page as a peer between the given original page and any
  669. * previous peer page.
  670. *
  671. * @param newDataPage the new index page
  672. * @param origDataPage the current index page
  673. */
  674. private void addToPeersBefore(CacheDataPage newDataPage,
  675. CacheDataPage origDataPage)
  676. throws IOException
  677. {
  678. DataPageMain origMain = origDataPage._main;
  679. DataPageMain newMain = newDataPage._main;
  680. DataPageMain prevMain = origMain.getPrevPage();
  681. newMain._nextPageNumber = origMain._pageNumber;
  682. newMain._prevPageNumber = origMain._prevPageNumber;
  683. origMain._prevPageNumber = newMain._pageNumber;
  684. if(prevMain != null) {
  685. setModified(new CacheDataPage(prevMain));
  686. prevMain._nextPageNumber = newMain._pageNumber;
  687. }
  688. }
  689. /**
  690. * Separates the given index page from any next peer page.
  691. *
  692. * @param cacheDataPage the index page to be separated
  693. */
  694. private void separateFromNextPeer(CacheDataPage cacheDataPage)
  695. throws IOException
  696. {
  697. DataPageMain dpMain = cacheDataPage._main;
  698. setModified(cacheDataPage);
  699. DataPageMain nextMain = dpMain.getNextPage();
  700. setModified(new CacheDataPage(nextMain));
  701. nextMain._prevPageNumber = INVALID_INDEX_PAGE_NUMBER;
  702. dpMain._nextPageNumber = INVALID_INDEX_PAGE_NUMBER;
  703. }
  704. /**
  705. * Sets the parent info for the children of the given page to the given
  706. * page.
  707. *
  708. * @param cacheDataPage the page whose children need to be updated
  709. */
  710. private void reparentChildren(CacheDataPage cacheDataPage)
  711. {
  712. DataPageMain dpMain = cacheDataPage._main;
  713. DataPageExtra dpExtra = cacheDataPage._extra;
  714. // note, the "parent" page number is not actually persisted, so we do not
  715. // need to mark any updated pages as modified. for the same reason, we
  716. // don't need to load the pages if not already loaded
  717. for(Entry entry : dpExtra._entryView) {
  718. Integer childPageNumber = entry.getSubPageNumber();
  719. DataPageMain childMain = _dataPages.get(childPageNumber);
  720. if(childMain != null) {
  721. childMain.setParentPage(dpMain._pageNumber,
  722. dpMain.isChildTailPageNumber(childPageNumber));
  723. }
  724. }
  725. }
  726. /**
  727. * Makes the tail entry of the given page a normal entry on that page, done
  728. * when there is only one entry left on a page, and it is the tail.
  729. *
  730. * @param cacheDataPage the page whose tail must be updated
  731. */
  732. private void demoteTail(CacheDataPage cacheDataPage)
  733. throws IOException
  734. {
  735. // there's only one entry on the page, and it's the tail. make it a
  736. // normal entry
  737. DataPageMain dpMain = cacheDataPage._main;
  738. DataPageExtra dpExtra = cacheDataPage._extra;
  739. setModified(cacheDataPage);
  740. DataPageMain tailMain = dpMain.getChildTailPage();
  741. CacheDataPage tailDataPage = new CacheDataPage(tailMain);
  742. // move the tail entry to the last normal entry
  743. updateParentTail(cacheDataPage, tailDataPage, UpdateType.REMOVE);
  744. Entry tailEntry = dpExtra._entryView.demoteTail();
  745. dpExtra._totalEntrySize += tailEntry.size();
  746. dpExtra._entryPrefix = EMPTY_PREFIX;
  747. tailMain.setParentPage(dpMain._pageNumber, false);
  748. }
  749. /**
  750. * Makes the last normal entry of the given page the tail entry on that
  751. * page, done when there are multiple entries on a page and no tail entry.
  752. *
  753. * @param cacheDataPage the page whose tail must be updated
  754. */
  755. private void promoteTail(CacheDataPage cacheDataPage)
  756. throws IOException
  757. {
  758. // there's not tail currently on this page, make last entry a tail
  759. DataPageMain dpMain = cacheDataPage._main;
  760. DataPageExtra dpExtra = cacheDataPage._extra;
  761. setModified(cacheDataPage);
  762. DataPageMain lastMain = dpMain.getChildPage(dpExtra._entryView.getLast());
  763. CacheDataPage lastDataPage = new CacheDataPage(lastMain);
  764. // move the "last" normal entry to the tail entry
  765. updateParentTail(cacheDataPage, lastDataPage, UpdateType.ADD);
  766. Entry lastEntry = dpExtra._entryView.promoteTail();
  767. dpExtra._totalEntrySize -= lastEntry.size();
  768. dpExtra._entryPrefix = EMPTY_PREFIX;
  769. lastMain.setParentPage(dpMain._pageNumber, true);
  770. }
  771. /**
  772. * Finds the index page on which the given entry does or should reside.
  773. *
  774. * @param e the entry to find
  775. */
  776. public CacheDataPage findCacheDataPage(Entry e)
  777. throws IOException
  778. {
  779. DataPageMain curPage = _rootPage;
  780. while(true) {
  781. if(curPage._leaf) {
  782. // nowhere to go from here
  783. return new CacheDataPage(curPage);
  784. }
  785. DataPageExtra extra = curPage.getExtra();
  786. // need to descend
  787. int idx = extra._entryView.find(e);
  788. if(idx < 0) {
  789. idx = missingIndexToInsertionPoint(idx);
  790. if(idx == extra._entryView.size()) {
  791. // just move to last child page
  792. --idx;
  793. }
  794. }
  795. Entry nodeEntry = extra._entryView.get(idx);
  796. curPage = curPage.getChildPage(nodeEntry);
  797. }
  798. }
  799. /**
  800. * Marks the given index page as modified and saves it for writing, if
  801. * necessary (if the page is already marked, does nothing).
  802. *
  803. * @param cacheDataPage the modified index page
  804. */
  805. private void setModified(CacheDataPage cacheDataPage)
  806. {
  807. if(!cacheDataPage._extra._modified) {
  808. _modifiedPages.add(cacheDataPage);
  809. cacheDataPage._extra._modified = true;
  810. }
  811. }
  812. /**
  813. * Finds the valid entry prefix given the first/last entries on an index
  814. * page.
  815. *
  816. * @param e1 the first entry on the page
  817. * @param e2 the last entry on the page
  818. *
  819. * @return a valid entry prefix for the page
  820. */
  821. private static byte[] findCommonPrefix(Entry e1, Entry e2)
  822. {
  823. byte[] b1 = e1.getEntryBytes();
  824. byte[] b2 = e2.getEntryBytes();
  825. int maxLen = b1.length;
  826. byte[] prefix = b1;
  827. if(b1.length > b2.length) {
  828. maxLen = b2.length;
  829. prefix = b2;
  830. }
  831. int len = 0;
  832. while((len < maxLen) && (b1[len] == b2[len])) {
  833. ++len;
  834. }
  835. if(len < prefix.length) {
  836. if(len == 0) {
  837. return EMPTY_PREFIX;
  838. }
  839. // need new prefix
  840. prefix = ByteUtil.copyOf(prefix, len);
  841. }
  842. return prefix;
  843. }
  844. /**
  845. * Used by unit tests to validate the internal status of the index.
  846. */
  847. void validate(boolean forceLoad) throws IOException {
  848. new Validator(forceLoad).validate();
  849. }
  850. /**
  851. * Collects all the cache pages in the cache.
  852. *
  853. * @param pages the List to update
  854. * @param dpMain the index page to collect
  855. */
  856. private List<Object> collectPages(List<Object> pages, DataPageMain dpMain) {
  857. try {
  858. CacheDataPage cacheDataPage = new CacheDataPage(dpMain);
  859. pages.add(cacheDataPage);
  860. if(!dpMain._leaf) {
  861. for(Entry e : cacheDataPage._extra._entryView) {
  862. DataPageMain childMain = dpMain.getChildPage(e);
  863. collectPages(pages, childMain);
  864. }
  865. }
  866. } catch(IOException e) {
  867. pages.add("DataPage[" + dpMain._pageNumber + "]: <" + e + ">");
  868. }
  869. return pages;
  870. }
  871. /**
  872. * Trims the size of the _dataPages cache appropriately (assuming caller has
  873. * already verified that the cache needs trimming).
  874. */
  875. private void purgeOldPages() {
  876. Iterator<DataPageMain> iter = _dataPages.values().iterator();
  877. while(iter.hasNext()) {
  878. DataPageMain dpMain = iter.next();
  879. // note, we never purge the root page
  880. if(dpMain != _rootPage) {
  881. iter.remove();
  882. if(_dataPages.size() <= MAX_CACHE_SIZE) {
  883. break;
  884. }
  885. }
  886. }
  887. }
  888. @Override
  889. public String toString() {
  890. ToStringBuilder sb = CustomToStringStyle.builder(this);
  891. if(_rootPage == null) {
  892. sb.append("pages", "(uninitialized)");
  893. } else {
  894. sb.append("pages", collectPages(new ArrayList<Object>(), _rootPage));
  895. }
  896. return sb.toString();
  897. }
  898. private String withErrorContext(String msg) {
  899. return _indexData.withErrorContext(msg);
  900. }
  901. /**
  902. * Keeps track of the main info for an index page.
  903. */
  904. private class DataPageMain
  905. {
  906. public final int _pageNumber;
  907. public Integer _prevPageNumber;
  908. public Integer _nextPageNumber;
  909. public Integer _childTailPageNumber;
  910. public Integer _parentPageNumber;
  911. public boolean _leaf;
  912. public boolean _tail;
  913. private Reference<DataPageExtra> _extra;
  914. private DataPageMain(int pageNumber) {
  915. _pageNumber = pageNumber;
  916. }
  917. public IndexPageCache getCache() {
  918. return IndexPageCache.this;
  919. }
  920. public boolean isRoot() {
  921. return(this == _rootPage);
  922. }
  923. public boolean isTail() throws IOException
  924. {
  925. resolveParent();
  926. return _tail;
  927. }
  928. public boolean hasChildTail() {
  929. return(_childTailPageNumber != INVALID_INDEX_PAGE_NUMBER);
  930. }
  931. public boolean isChildTailPageNumber(int pageNumber) {
  932. return(_childTailPageNumber == pageNumber);
  933. }
  934. public DataPageMain getParentPage() throws IOException
  935. {
  936. resolveParent();
  937. return IndexPageCache.this.getDataPage(_parentPageNumber);
  938. }
  939. public void initParentPage(Integer parentPageNumber, boolean isTail) {
  940. // only set if not already set
  941. if(_parentPageNumber == null) {
  942. setParentPage(parentPageNumber, isTail);
  943. }
  944. }
  945. public void setParentPage(Integer parentPageNumber, boolean isTail) {
  946. _parentPageNumber = parentPageNumber;
  947. _tail = isTail;
  948. }
  949. public DataPageMain getPrevPage() throws IOException
  950. {
  951. return IndexPageCache.this.getDataPage(_prevPageNumber);
  952. }
  953. public DataPageMain getNextPage() throws IOException
  954. {
  955. return IndexPageCache.this.getDataPage(_nextPageNumber);
  956. }
  957. public DataPageMain getChildPage(Entry e) throws IOException
  958. {
  959. Integer childPageNumber = e.getSubPageNumber();
  960. return getChildPage(childPageNumber,
  961. isChildTailPageNumber(childPageNumber));
  962. }
  963. public DataPageMain getChildTailPage() throws IOException
  964. {
  965. return getChildPage(_childTailPageNumber, true);
  966. }
  967. /**
  968. * Returns a child page for the given page number, updating its parent
  969. * info if necessary.
  970. */
  971. private DataPageMain getChildPage(Integer childPageNumber, boolean isTail)
  972. throws IOException
  973. {
  974. DataPageMain child = getDataPage(childPageNumber);
  975. if(child != null) {
  976. // set the parent info for this child (if necessary)
  977. child.initParentPage(_pageNumber, isTail);
  978. }
  979. return child;
  980. }
  981. public DataPageExtra getExtra() throws IOException
  982. {
  983. DataPageExtra extra = _extra.get();
  984. if(extra == null) {
  985. extra = readDataPage(_pageNumber)._extra;
  986. setExtra(extra);
  987. }
  988. return extra;
  989. }
  990. public void setExtra(DataPageExtra extra) throws IOException
  991. {
  992. extra.setEntryView(this);
  993. _extra = new SoftReference<DataPageExtra>(extra);
  994. }
  995. private void resolveParent() throws IOException {
  996. if(_parentPageNumber == null) {
  997. // the act of searching for the last entry should resolve any parent
  998. // pages along the path
  999. findCacheDataPage(getExtra()._entryView.getLast());
  1000. if(_parentPageNumber == null) {
  1001. throw new IllegalStateException(withErrorContext(
  1002. "Parent was not resolved"));
  1003. }
  1004. }
  1005. }
  1006. @Override
  1007. public String toString() {
  1008. return (_leaf ? "Leaf" : "Node") + "DPMain[" + _pageNumber +
  1009. "] " + _prevPageNumber + ", " + _nextPageNumber + ", (" +
  1010. _childTailPageNumber + ")";
  1011. }
  1012. }
  1013. /**
  1014. * Keeps track of the extra info for an index page. This info (if
  1015. * unmodified) may be re-read from disk as necessary.
  1016. */
  1017. private static class DataPageExtra
  1018. {
  1019. /** sorted collection of index entries. this is kept in a list instead of
  1020. a SortedSet because the SortedSet has lame traversal utilities */
  1021. public List<Entry> _entries;
  1022. public EntryListView _entryView;
  1023. public byte[] _entryPrefix;
  1024. public int _totalEntrySize;
  1025. public boolean _modified;
  1026. private DataPageExtra()
  1027. {
  1028. }
  1029. public void setEntryView(DataPageMain main) throws IOException {
  1030. _entryView = new EntryListView(main, this);
  1031. }
  1032. public void updateEntryPrefix() {
  1033. if(_entryPrefix.length == 0) {
  1034. // prefix is only related to *real* entries, tail not included
  1035. _entryPrefix = findCommonPrefix(_entries.get(0),
  1036. _entries.get(_entries.size() - 1));
  1037. }
  1038. }
  1039. @Override
  1040. public String toString() {
  1041. return CustomToStringStyle.builder("DPExtra")
  1042. .append(null, _entryView)
  1043. .toString();
  1044. }
  1045. }
  1046. /**
  1047. * IndexPageCache implementation of an Index {@link DataPage}.
  1048. */
  1049. private static final class CacheDataPage extends DataPage
  1050. {
  1051. public final DataPageMain _main;
  1052. public final DataPageExtra _extra;
  1053. private CacheDataPage(DataPageMain dataPage) throws IOException {
  1054. this(dataPage, dataPage.getExtra());
  1055. }
  1056. private CacheDataPage(DataPageMain dataPage, DataPageExtra extra) {
  1057. _main = dataPage;
  1058. _extra = extra;
  1059. }
  1060. @Override
  1061. public int getPageNumber() {
  1062. return _main._pageNumber;
  1063. }
  1064. @Override
  1065. public boolean isLeaf() {
  1066. return _main._leaf;
  1067. }
  1068. @Override
  1069. public void setLeaf(boolean isLeaf) {
  1070. _main._leaf = isLeaf;
  1071. }
  1072. @Override
  1073. public int getPrevPageNumber() {
  1074. return _main._prevPageNumber;
  1075. }
  1076. @Override
  1077. public void setPrevPageNumber(int pageNumber) {
  1078. _main._prevPageNumber = pageNumber;
  1079. }
  1080. @Override
  1081. public int getNextPageNumber() {
  1082. return _main._nextPageNumber;
  1083. }
  1084. @Override
  1085. public void setNextPageNumber(int pageNumber) {
  1086. _main._nextPageNumber = pageNumber;
  1087. }
  1088. @Override
  1089. public int getChildTailPageNumber() {
  1090. return _main._childTailPageNumber;
  1091. }
  1092. @Override
  1093. public void setChildTailPageNumber(int pageNumber) {
  1094. _main._childTailPageNumber = pageNumber;
  1095. }
  1096. @Override
  1097. public int getTotalEntrySize() {
  1098. return _extra._totalEntrySize;
  1099. }
  1100. @Override
  1101. public void setTotalEntrySize(int totalSize) {
  1102. _extra._totalEntrySize = totalSize;
  1103. }
  1104. @Override
  1105. public byte[] getEntryPrefix() {
  1106. return _extra._entryPrefix;
  1107. }
  1108. @Override
  1109. public void setEntryPrefix(byte[] entryPrefix) {
  1110. _extra._entryPrefix = entryPrefix;
  1111. }
  1112. @Override
  1113. public List<Entry> getEntries() {
  1114. return _extra._entries;
  1115. }
  1116. @Override
  1117. public void setEntries(List<Entry> entries) {
  1118. _extra._entries = entries;
  1119. }
  1120. @Override
  1121. public void addEntry(int idx, Entry entry) throws IOException {
  1122. _main.getCache().addEntry(this, idx, entry);
  1123. }
  1124. @Override
  1125. public Entry removeEntry(int idx) throws IOException {
  1126. return _main.getCache().removeEntry(this, idx);
  1127. }
  1128. }
  1129. /**
  1130. * A view of an index page's entries which combines the normal entries and
  1131. * tail entry into one collection.
  1132. */
  1133. private static class EntryListView extends AbstractList<Entry>
  1134. implements RandomAccess
  1135. {
  1136. private final DataPageExtra _extra;
  1137. private Entry _childTailEntry;
  1138. private EntryListView(DataPageMain main, DataPageExtra extra)
  1139. throws IOException
  1140. {
  1141. if(main.hasChildTail()) {
  1142. _childTailEntry = main.getChildTailPage().getExtra()._entryView
  1143. .getLast().asNodeEntry(main._childTailPageNumber);
  1144. }
  1145. _extra = extra;
  1146. }
  1147. private List<Entry> getEntries() {
  1148. return _extra._entries;
  1149. }
  1150. @Override
  1151. public int size() {
  1152. int size = getEntries().size();
  1153. if(hasChildTail()) {
  1154. ++size;
  1155. }
  1156. return size;
  1157. }
  1158. @Override
  1159. public Entry get(int idx) {
  1160. return (isCurrentChildTailIndex(idx) ?
  1161. _childTailEntry :
  1162. getEntries().get(idx));
  1163. }
  1164. @Override
  1165. public Entry set(int idx, Entry newEntry) {
  1166. return (isCurrentChildTailIndex(idx) ?
  1167. setChildTailEntry(newEntry) :
  1168. getEntries().set(idx, newEntry));
  1169. }
  1170. @Override
  1171. public void add(int idx, Entry newEntry) {
  1172. // note, we will never add to the "tail" entry, that will always be
  1173. // handled through promoteTail
  1174. getEntries().add(idx, newEntry);
  1175. }
  1176. @Override
  1177. public Entry remove(int idx) {
  1178. return (isCurrentChildTailIndex(idx) ?
  1179. setChildTailEntry(null) :
  1180. getEntries().remove(idx));
  1181. }
  1182. public Entry setChildTailEntry(Entry newEntry) {
  1183. Entry old = _childTailEntry;
  1184. _childTailEntry = newEntry;
  1185. return old;
  1186. }
  1187. private boolean hasChildTail() {
  1188. return(_childTailEntry != null);
  1189. }
  1190. private boolean isCurrentChildTailIndex(int idx) {
  1191. return(idx == getEntries().size());
  1192. }
  1193. public Entry getLast() {
  1194. return(hasChildTail() ? _childTailEntry :
  1195. (!getEntries().isEmpty() ?
  1196. getEntries().get(getEntries().size() - 1) : null));
  1197. }
  1198. public Entry demoteTail() {
  1199. Entry tail = _childTailEntry;
  1200. _childTailEntry = null;
  1201. getEntries().add(tail);
  1202. return tail;
  1203. }
  1204. public Entry promoteTail() {
  1205. Entry last = getEntries().remove(getEntries().size() - 1);
  1206. _childTailEntry = last;
  1207. return last;
  1208. }
  1209. public int find(Entry e) {
  1210. return Collections.binarySearch(this, e);
  1211. }
  1212. }
  1213. /**
  1214. * Utility class for running index validation.
  1215. */
  1216. private final class Validator {
  1217. private final boolean _forceLoad;
  1218. private final Map<Integer,DataPageMain> _knownPages = new HashMap<>();
  1219. private final Queue<DataPageMain> _pendingPages = new LinkedList<>();
  1220. private Validator(boolean forceLoad) {
  1221. _forceLoad = forceLoad;
  1222. _knownPages.putAll(_dataPages);
  1223. _pendingPages.addAll(_knownPages.values());
  1224. }
  1225. void validate() throws IOException {
  1226. DataPageMain dpMain = null;
  1227. while((dpMain = _pendingPages.poll()) != null) {
  1228. DataPageExtra dpExtra = dpMain.getExtra();
  1229. validateEntries(dpExtra);
  1230. validateChildren(dpMain, dpExtra);
  1231. validatePeers(dpMain);
  1232. }
  1233. }
  1234. /**
  1235. * Validates the entries for an index page
  1236. *
  1237. * @param dpExtra the entries to validate
  1238. */
  1239. private void validateEntries(DataPageExtra dpExtra) throws IOException {
  1240. int entrySize = 0;
  1241. Entry prevEntry = FIRST_ENTRY;
  1242. for(Entry e : dpExtra._entries) {
  1243. entrySize += e.size();
  1244. if(prevEntry.compareTo(e) >= 0) {
  1245. throw new IOException(withErrorContext(
  1246. "Unexpected order in index entries, " + prevEntry +
  1247. " >= " + e));
  1248. }
  1249. prevEntry = e;
  1250. }
  1251. if(entrySize != dpExtra._totalEntrySize) {
  1252. throw new IllegalStateException(withErrorContext(
  1253. "Expected size " + entrySize +
  1254. " but was " + dpExtra._totalEntrySize));
  1255. }
  1256. }
  1257. /**
  1258. * Validates the children for an index page
  1259. *
  1260. * @param dpMain the index page
  1261. * @param dpExtra the child entries to validate
  1262. */
  1263. private void validateChildren(DataPageMain dpMain,
  1264. DataPageExtra dpExtra) throws IOException {
  1265. int childTailPageNumber = dpMain._childTailPageNumber;
  1266. if(dpMain._leaf) {
  1267. if(childTailPageNumber != INVALID_INDEX_PAGE_NUMBER) {
  1268. throw new IllegalStateException(
  1269. withErrorContext("Leaf page has tail " + dpMain));
  1270. }
  1271. return;
  1272. }
  1273. if((dpExtra._entryView.size() == 1) && dpMain.hasChildTail()) {
  1274. throw new IllegalStateException(
  1275. withErrorContext("Single child is tail " + dpMain));
  1276. }
  1277. Integer prevPageNumber = null;
  1278. Integer nextPageNumber = null;
  1279. for(Entry e : dpExtra._entryView) {
  1280. validateEntryForPage(dpMain, e);
  1281. Integer subPageNumber = e.getSubPageNumber();
  1282. DataPageMain childMain = getPageForValidate(subPageNumber);
  1283. if(childMain != null) {
  1284. if((prevPageNumber != null) &&
  1285. ((int)childMain._prevPageNumber != prevPageNumber)) {
  1286. throw new IllegalStateException(withErrorContext(
  1287. "Child's prevPageNumber is not the previous child for " +
  1288. childMain + " " + dpExtra._entryView + " " +
  1289. prevPageNumber));
  1290. }
  1291. if((nextPageNumber != null) &&
  1292. (childMain._pageNumber != nextPageNumber)) {
  1293. throw new IllegalStateException(withErrorContext(
  1294. "Child's pageNumber is not the expected next child for " +
  1295. childMain));
  1296. }
  1297. if(childMain._parentPageNumber != null) {
  1298. if(childMain._parentPageNumber != dpMain._pageNumber) {
  1299. throw new IllegalStateException(
  1300. withErrorContext("Child's parent is incorrect " + childMain));
  1301. }
  1302. boolean expectTail = (subPageNumber == childTailPageNumber);
  1303. if(expectTail != childMain._tail) {
  1304. throw new IllegalStateException(withErrorContext(
  1305. "Child tail status incorrect " + childMain));
  1306. }
  1307. }
  1308. Entry lastEntry = childMain.getExtra()._entryView.getLast();
  1309. if(e.compareTo(lastEntry) != 0) {
  1310. throw new IllegalStateException(withErrorContext(
  1311. "Invalid entry " + e + " but child is " + lastEntry));
  1312. }
  1313. nextPageNumber = childMain._nextPageNumber;
  1314. prevPageNumber = childMain._pageNumber;
  1315. } else {
  1316. // if we aren't force loading, we may have gaps in the children so we
  1317. // can't validate these for the current child
  1318. nextPageNumber = null;
  1319. prevPageNumber = null;
  1320. }
  1321. }
  1322. }
  1323. /**
  1324. * Validates the peer pages for an index page.
  1325. *
  1326. * @param dpMain the index page
  1327. */
  1328. private void validatePeers(DataPageMain dpMain)
  1329. throws IOException {
  1330. DataPageMain prevMain = getPageForValidate(dpMain._prevPageNumber);
  1331. if(prevMain != null) {
  1332. if(prevMain._nextPageNumber != dpMain._pageNumber) {
  1333. throw new IllegalStateException(withErrorContext(
  1334. "Prev page " + prevMain + " does not ref " + dpMain));
  1335. }
  1336. validatePeerStatus(dpMain, prevMain);
  1337. }
  1338. DataPageMain nextMain =
  1339. getPageForValidate(dpMain._nextPageNumber);
  1340. if(nextMain != null) {
  1341. if(nextMain._prevPageNumber != dpMain._pageNumber) {
  1342. throw new IllegalStateException(withErrorContext(
  1343. "Next page " + nextMain + " does not ref " + dpMain));
  1344. }
  1345. validatePeerStatus(dpMain, nextMain);
  1346. }
  1347. }
  1348. /**
  1349. * Validates the given peer page against the given index page
  1350. *
  1351. * @param dpMain the index page
  1352. * @param peerMain the peer index page
  1353. */
  1354. private void validatePeerStatus(DataPageMain dpMain, DataPageMain peerMain)
  1355. {
  1356. if(dpMain._leaf != peerMain._leaf) {
  1357. throw new IllegalStateException(withErrorContext(
  1358. "Mismatched peer status " + dpMain._leaf + " " +
  1359. peerMain._leaf));
  1360. }
  1361. if(!dpMain._leaf) {
  1362. if((dpMain._parentPageNumber != null) &&
  1363. (peerMain._parentPageNumber != null) &&
  1364. ((int)dpMain._parentPageNumber != (int)peerMain._parentPageNumber)) {
  1365. throw new IllegalStateException(withErrorContext(
  1366. "Mismatched node parents " + dpMain._parentPageNumber + " " +
  1367. peerMain._parentPageNumber));
  1368. }
  1369. }
  1370. }
  1371. private DataPageMain getPageForValidate(
  1372. Integer pageNumber) throws IOException {
  1373. DataPageMain dpMain = _knownPages.get(pageNumber);
  1374. if((dpMain == null) && _forceLoad &&
  1375. (pageNumber != INVALID_INDEX_PAGE_NUMBER)) {
  1376. dpMain = getDataPage(pageNumber);
  1377. if(dpMain != null) {
  1378. _knownPages.put(pageNumber, dpMain);
  1379. _pendingPages.add(dpMain);
  1380. }
  1381. }
  1382. return dpMain;
  1383. }
  1384. }
  1385. }