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 46KB

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