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.

PageChannel.java 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  1. /*
  2. Copyright (c) 2005 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.Flushable;
  15. import java.io.IOException;
  16. import java.nio.ByteBuffer;
  17. import java.nio.ByteOrder;
  18. import java.nio.channels.Channel;
  19. import java.nio.channels.FileChannel;
  20. /**
  21. * Reads and writes individual pages in a database file
  22. * @author Tim McCune
  23. */
  24. public class PageChannel implements Channel, Flushable {
  25. static final int INVALID_PAGE_NUMBER = -1;
  26. static final ByteOrder DEFAULT_BYTE_ORDER = ByteOrder.LITTLE_ENDIAN;
  27. /** invalid page header, used when deallocating old pages. data pages
  28. generally have 4 interesting bytes at the beginning which we want to
  29. reset. */
  30. private static final byte[] INVALID_PAGE_BYTE_HEADER =
  31. new byte[]{PageTypes.INVALID, (byte)0, (byte)0, (byte)0};
  32. /** Global usage map always lives on page 1 */
  33. static final int PAGE_GLOBAL_USAGE_MAP = 1;
  34. /** Global usage map always lives at row 0 */
  35. static final int ROW_GLOBAL_USAGE_MAP = 0;
  36. /** Channel containing the database */
  37. private final FileChannel _channel;
  38. /** whether or not the _channel should be closed by this class */
  39. private final boolean _closeChannel;
  40. /** Format of the database in the channel */
  41. private final JetFormat _format;
  42. /** whether or not to force all writes to disk immediately */
  43. private final boolean _autoSync;
  44. /** buffer used when deallocating old pages. data pages generally have 4
  45. interesting bytes at the beginning which we want to reset. */
  46. private final ByteBuffer _invalidPageBytes =
  47. ByteBuffer.wrap(INVALID_PAGE_BYTE_HEADER);
  48. /** dummy buffer used when allocating new pages */
  49. private final ByteBuffer _forceBytes = ByteBuffer.allocate(1);
  50. /** Tracks free pages in the database. */
  51. private UsageMap _globalUsageMap;
  52. /** handler for the current database encoding type */
  53. private CodecHandler _codecHandler = DefaultCodecProvider.DUMMY_HANDLER;
  54. /** temp page buffer used when pages cannot be partially encoded */
  55. private TempPageHolder _fullPageEncodeBufferH;
  56. private TempBufferHolder _tempDecodeBufferH;
  57. private int _writeCount;
  58. /**
  59. * Only used by unit tests
  60. */
  61. protected PageChannel(boolean testing) {
  62. if(!testing) {
  63. throw new IllegalArgumentException();
  64. }
  65. _channel = null;
  66. _closeChannel = false;
  67. _format = JetFormat.VERSION_4;
  68. _autoSync = false;
  69. }
  70. /**
  71. * @param channel Channel containing the database
  72. * @param format Format of the database in the channel
  73. */
  74. public PageChannel(FileChannel channel, boolean closeChannel,
  75. JetFormat format, boolean autoSync)
  76. throws IOException
  77. {
  78. _channel = channel;
  79. _closeChannel = closeChannel;
  80. _format = format;
  81. _autoSync = autoSync;
  82. }
  83. /**
  84. * Does second-stage initialization, must be called after construction.
  85. */
  86. public void initialize(DatabaseImpl database, CodecProvider codecProvider)
  87. throws IOException
  88. {
  89. // initialize page en/decoding support
  90. _codecHandler = codecProvider.createHandler(this, database.getCharset());
  91. if(!_codecHandler.canEncodePartialPage()) {
  92. _fullPageEncodeBufferH =
  93. TempPageHolder.newHolder(TempBufferHolder.Type.SOFT);
  94. }
  95. if(!_codecHandler.canDecodeInline()) {
  96. _tempDecodeBufferH = TempBufferHolder.newHolder(
  97. TempBufferHolder.Type.SOFT, true);
  98. }
  99. // note the global usage map is a special map where any page outside of
  100. // the current range is assumed to be "on"
  101. _globalUsageMap = UsageMap.read(database, PAGE_GLOBAL_USAGE_MAP,
  102. ROW_GLOBAL_USAGE_MAP, true);
  103. }
  104. public JetFormat getFormat() {
  105. return _format;
  106. }
  107. public boolean isAutoSync() {
  108. return _autoSync;
  109. }
  110. /**
  111. * Begins a "logical" write operation. See {@link #finishWrite} for more
  112. * details.
  113. */
  114. public void startWrite() {
  115. ++_writeCount;
  116. }
  117. /**
  118. * Begins an exclusive "logical" write operation (throws an exception if
  119. * another write operation is outstanding). See {@link #finishWrite} for
  120. * more details.
  121. */
  122. public void startExclusiveWrite() {
  123. if(_writeCount != 0) {
  124. throw new IllegalArgumentException(
  125. "Another write operation is currently in progress");
  126. }
  127. startWrite();
  128. }
  129. /**
  130. * Completes a "logical" write operation. This method should be called in
  131. * finally block which wraps a logical write operation (which is preceded by
  132. * a {@link #startWrite} call). Logical write operations may be nested. If
  133. * the database is configured for "auto-sync", the channel will be flushed
  134. * when the outermost operation is complete,
  135. */
  136. public void finishWrite() throws IOException {
  137. assertWriting();
  138. if((--_writeCount == 0) && _autoSync) {
  139. flush();
  140. }
  141. }
  142. /**
  143. * Returns {@code true} if a logical write operation is in progress, {@code
  144. * false} otherwise.
  145. */
  146. public boolean isWriting() {
  147. return(_writeCount > 0);
  148. }
  149. /**
  150. * Asserts that a write operation is in progress.
  151. */
  152. private void assertWriting() {
  153. if(!isWriting()) {
  154. throw new IllegalStateException("No write operation in progress");
  155. }
  156. }
  157. /**
  158. * Returns the next page number based on the given file size.
  159. */
  160. private int getNextPageNumber(long size) {
  161. return (int)(size / getFormat().PAGE_SIZE);
  162. }
  163. /**
  164. * Returns the offset for a page within the file.
  165. */
  166. private long getPageOffset(int pageNumber) {
  167. return((long) pageNumber * (long) getFormat().PAGE_SIZE);
  168. }
  169. /**
  170. * Validates that the given pageNumber is valid for this database.
  171. */
  172. private void validatePageNumber(int pageNumber)
  173. throws IOException
  174. {
  175. int nextPageNumber = getNextPageNumber(_channel.size());
  176. if((pageNumber <= INVALID_PAGE_NUMBER) || (pageNumber >= nextPageNumber)) {
  177. throw new IllegalStateException("invalid page number " + pageNumber);
  178. }
  179. }
  180. /**
  181. * @param buffer Buffer to read the page into
  182. * @param pageNumber Number of the page to read in (starting at 0)
  183. */
  184. public void readPage(ByteBuffer buffer, int pageNumber)
  185. throws IOException
  186. {
  187. validatePageNumber(pageNumber);
  188. ByteBuffer inPage = buffer;
  189. ByteBuffer outPage = buffer;
  190. if((pageNumber != 0) && !_codecHandler.canDecodeInline()) {
  191. inPage = _tempDecodeBufferH.getPageBuffer(this);
  192. outPage.clear();
  193. }
  194. inPage.clear();
  195. int bytesRead = _channel.read(
  196. inPage, (long) pageNumber * (long) getFormat().PAGE_SIZE);
  197. inPage.flip();
  198. if(bytesRead != getFormat().PAGE_SIZE) {
  199. throw new IOException("Failed attempting to read " +
  200. getFormat().PAGE_SIZE + " bytes from page " +
  201. pageNumber + ", only read " + bytesRead);
  202. }
  203. if(pageNumber == 0) {
  204. // de-mask header (note, page 0 never has additional encoding)
  205. applyHeaderMask(buffer);
  206. } else {
  207. _codecHandler.decodePage(inPage, outPage, pageNumber);
  208. }
  209. }
  210. /**
  211. * Write a page to disk
  212. * @param page Page to write
  213. * @param pageNumber Page number to write the page to
  214. */
  215. public void writePage(ByteBuffer page, int pageNumber) throws IOException {
  216. writePage(page, pageNumber, 0);
  217. }
  218. /**
  219. * Write a page (or part of a page) to disk
  220. * @param page Page to write
  221. * @param pageNumber Page number to write the page to
  222. * @param pageOffset offset within the page at which to start writing the
  223. * page data
  224. */
  225. public void writePage(ByteBuffer page, int pageNumber, int pageOffset)
  226. throws IOException
  227. {
  228. assertWriting();
  229. validatePageNumber(pageNumber);
  230. page.rewind().position(pageOffset);
  231. int writeLen = page.remaining();
  232. if((writeLen + pageOffset) > getFormat().PAGE_SIZE) {
  233. throw new IllegalArgumentException(
  234. "Page buffer is too large, size " + (writeLen + pageOffset));
  235. }
  236. ByteBuffer encodedPage = page;
  237. if(pageNumber == 0) {
  238. // re-mask header
  239. applyHeaderMask(page);
  240. } else {
  241. if(!_codecHandler.canEncodePartialPage()) {
  242. if((pageOffset > 0) && (writeLen < getFormat().PAGE_SIZE)) {
  243. // current codec handler cannot encode part of a page, so need to
  244. // copy the modified part into the current page contents in a temp
  245. // buffer so that we can encode the entire page
  246. ByteBuffer fullPage = _fullPageEncodeBufferH.setPage(
  247. this, pageNumber);
  248. // copy the modified part to the full page
  249. fullPage.position(pageOffset);
  250. fullPage.put(page);
  251. fullPage.rewind();
  252. // reset so we can write the whole page
  253. page = fullPage;
  254. pageOffset = 0;
  255. writeLen = getFormat().PAGE_SIZE;
  256. } else {
  257. _fullPageEncodeBufferH.possiblyInvalidate(pageNumber, null);
  258. }
  259. }
  260. // re-encode page
  261. encodedPage = _codecHandler.encodePage(page, pageNumber, pageOffset);
  262. // reset position/limit in case they were affected by encoding
  263. encodedPage.position(pageOffset).limit(pageOffset + writeLen);
  264. }
  265. try {
  266. _channel.write(encodedPage, (getPageOffset(pageNumber) + pageOffset));
  267. } finally {
  268. if(pageNumber == 0) {
  269. // de-mask header
  270. applyHeaderMask(page);
  271. }
  272. }
  273. }
  274. /**
  275. * Allocates a new page in the database. Data in the page is undefined
  276. * until it is written in a call to {@link #writePage(ByteBuffer,int)}.
  277. */
  278. public int allocateNewPage() throws IOException {
  279. assertWriting();
  280. // this will force the file to be extended with mostly undefined bytes
  281. long size = _channel.size();
  282. if(size >= getFormat().MAX_DATABASE_SIZE) {
  283. throw new IOException("Database is at maximum size " +
  284. getFormat().MAX_DATABASE_SIZE);
  285. }
  286. if((size % getFormat().PAGE_SIZE) != 0L) {
  287. throw new IOException("Database corrupted, file size " + size +
  288. " is not multiple of page size " +
  289. getFormat().PAGE_SIZE);
  290. }
  291. _forceBytes.rewind();
  292. // push the buffer to the end of the page, so that a full page's worth of
  293. // data is written
  294. int pageOffset = (getFormat().PAGE_SIZE - _forceBytes.remaining());
  295. long offset = size + pageOffset;
  296. int pageNumber = getNextPageNumber(size);
  297. // since we are just allocating page space at this point and not writing
  298. // meaningful data, we do _not_ encode the page.
  299. _channel.write(_forceBytes, offset);
  300. _globalUsageMap.removePageNumber(pageNumber);
  301. return pageNumber;
  302. }
  303. /**
  304. * Deallocate a previously used page in the database.
  305. */
  306. public void deallocatePage(int pageNumber) throws IOException {
  307. assertWriting();
  308. validatePageNumber(pageNumber);
  309. // don't write the whole page, just wipe out the header (which should be
  310. // enough to let us know if we accidentally try to use an invalid page)
  311. _invalidPageBytes.rewind();
  312. _channel.write(_invalidPageBytes, getPageOffset(pageNumber));
  313. _globalUsageMap.addPageNumber(pageNumber); //force is done here
  314. }
  315. /**
  316. * @return A newly-allocated buffer that can be passed to readPage
  317. */
  318. public ByteBuffer createPageBuffer() {
  319. return createBuffer(getFormat().PAGE_SIZE);
  320. }
  321. /**
  322. * @return A newly-allocated buffer of the given size and DEFAULT_BYTE_ORDER
  323. * byte order
  324. */
  325. public static ByteBuffer createBuffer(int size) {
  326. return createBuffer(size, DEFAULT_BYTE_ORDER);
  327. }
  328. /**
  329. * @return A newly-allocated buffer of the given size and byte order
  330. */
  331. public static ByteBuffer createBuffer(int size, ByteOrder order) {
  332. return ByteBuffer.allocate(size).order(order);
  333. }
  334. @Override
  335. public void flush() throws IOException {
  336. _channel.force(true);
  337. }
  338. @Override
  339. public void close() throws IOException {
  340. flush();
  341. if(_closeChannel) {
  342. _channel.close();
  343. }
  344. }
  345. @Override
  346. public boolean isOpen() {
  347. return _channel.isOpen();
  348. }
  349. /**
  350. * Applies the XOR mask to the database header in the given buffer.
  351. */
  352. private void applyHeaderMask(ByteBuffer buffer) {
  353. // de/re-obfuscate the header
  354. byte[] headerMask = _format.HEADER_MASK;
  355. for(int idx = 0; idx < headerMask.length; ++idx) {
  356. int pos = idx + _format.OFFSET_MASKED_HEADER;
  357. byte b = (byte)(buffer.get(pos) ^ headerMask[idx]);
  358. buffer.put(pos, b);
  359. }
  360. }
  361. /**
  362. * @return a duplicate of the current buffer narrowed to the given position
  363. * and limit. mark will be set at the current position.
  364. */
  365. public static ByteBuffer narrowBuffer(ByteBuffer buffer, int position,
  366. int limit)
  367. {
  368. return (ByteBuffer)buffer.duplicate()
  369. .order(buffer.order())
  370. .clear()
  371. .limit(limit)
  372. .position(position)
  373. .mark();
  374. }
  375. /**
  376. * Returns a ByteBuffer wrapping the given bytes and configured with the
  377. * default byte order.
  378. */
  379. public static ByteBuffer wrap(byte[] bytes) {
  380. return ByteBuffer.wrap(bytes).order(DEFAULT_BYTE_ORDER);
  381. }
  382. }