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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  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. * Completes a "logical" write operation. This method should be called in
  119. * finally block which wraps a logical write operation (which is preceded by
  120. * a {@link #startWrite} call). Logical write operations may be nested. If
  121. * the database is configured for "auto-sync", the channel will be flushed
  122. * when the outermost operation is complete,
  123. */
  124. public void finishWrite() throws IOException {
  125. assertWriting();
  126. if((--_writeCount == 0) && _autoSync) {
  127. flush();
  128. }
  129. }
  130. /**
  131. * Returns {@code true} if a logical write operation is in progress, {@code
  132. * false} otherwise.
  133. */
  134. public boolean isWriting() {
  135. return(_writeCount > 0);
  136. }
  137. /**
  138. * Asserts that a write operation is in progress.
  139. */
  140. private void assertWriting() {
  141. if(!isWriting()) {
  142. throw new IllegalStateException("No write operation in progress");
  143. }
  144. }
  145. /**
  146. * Returns the next page number based on the given file size.
  147. */
  148. private int getNextPageNumber(long size) {
  149. return (int)(size / getFormat().PAGE_SIZE);
  150. }
  151. /**
  152. * Returns the offset for a page within the file.
  153. */
  154. private long getPageOffset(int pageNumber) {
  155. return((long) pageNumber * (long) getFormat().PAGE_SIZE);
  156. }
  157. /**
  158. * Validates that the given pageNumber is valid for this database.
  159. */
  160. private void validatePageNumber(int pageNumber)
  161. throws IOException
  162. {
  163. int nextPageNumber = getNextPageNumber(_channel.size());
  164. if((pageNumber <= INVALID_PAGE_NUMBER) || (pageNumber >= nextPageNumber)) {
  165. throw new IllegalStateException("invalid page number " + pageNumber);
  166. }
  167. }
  168. /**
  169. * @param buffer Buffer to read the page into
  170. * @param pageNumber Number of the page to read in (starting at 0)
  171. */
  172. public void readPage(ByteBuffer buffer, int pageNumber)
  173. throws IOException
  174. {
  175. validatePageNumber(pageNumber);
  176. ByteBuffer inPage = buffer;
  177. ByteBuffer outPage = buffer;
  178. if((pageNumber != 0) && !_codecHandler.canDecodeInline()) {
  179. inPage = _tempDecodeBufferH.getPageBuffer(this);
  180. outPage.clear();
  181. }
  182. inPage.clear();
  183. int bytesRead = _channel.read(
  184. inPage, (long) pageNumber * (long) getFormat().PAGE_SIZE);
  185. inPage.flip();
  186. if(bytesRead != getFormat().PAGE_SIZE) {
  187. throw new IOException("Failed attempting to read " +
  188. getFormat().PAGE_SIZE + " bytes from page " +
  189. pageNumber + ", only read " + bytesRead);
  190. }
  191. if(pageNumber == 0) {
  192. // de-mask header (note, page 0 never has additional encoding)
  193. applyHeaderMask(buffer);
  194. } else {
  195. _codecHandler.decodePage(inPage, outPage, pageNumber);
  196. }
  197. }
  198. /**
  199. * Write a page to disk
  200. * @param page Page to write
  201. * @param pageNumber Page number to write the page to
  202. */
  203. public void writePage(ByteBuffer page, int pageNumber) throws IOException {
  204. writePage(page, pageNumber, 0);
  205. }
  206. /**
  207. * Write a page (or part of a page) to disk
  208. * @param page Page to write
  209. * @param pageNumber Page number to write the page to
  210. * @param pageOffset offset within the page at which to start writing the
  211. * page data
  212. */
  213. public void writePage(ByteBuffer page, int pageNumber, int pageOffset)
  214. throws IOException
  215. {
  216. assertWriting();
  217. validatePageNumber(pageNumber);
  218. page.rewind().position(pageOffset);
  219. int writeLen = page.remaining();
  220. if((writeLen + pageOffset) > getFormat().PAGE_SIZE) {
  221. throw new IllegalArgumentException(
  222. "Page buffer is too large, size " + (writeLen + pageOffset));
  223. }
  224. ByteBuffer encodedPage = page;
  225. if(pageNumber == 0) {
  226. // re-mask header
  227. applyHeaderMask(page);
  228. } else {
  229. if(!_codecHandler.canEncodePartialPage()) {
  230. if((pageOffset > 0) && (writeLen < getFormat().PAGE_SIZE)) {
  231. // current codec handler cannot encode part of a page, so need to
  232. // copy the modified part into the current page contents in a temp
  233. // buffer so that we can encode the entire page
  234. ByteBuffer fullPage = _fullPageEncodeBufferH.setPage(
  235. this, pageNumber);
  236. // copy the modified part to the full page
  237. fullPage.position(pageOffset);
  238. fullPage.put(page);
  239. fullPage.rewind();
  240. // reset so we can write the whole page
  241. page = fullPage;
  242. pageOffset = 0;
  243. writeLen = getFormat().PAGE_SIZE;
  244. } else {
  245. _fullPageEncodeBufferH.possiblyInvalidate(pageNumber, null);
  246. }
  247. }
  248. // re-encode page
  249. encodedPage = _codecHandler.encodePage(page, pageNumber, pageOffset);
  250. // reset position/limit in case they were affected by encoding
  251. encodedPage.position(pageOffset).limit(pageOffset + writeLen);
  252. }
  253. try {
  254. _channel.write(encodedPage, (getPageOffset(pageNumber) + pageOffset));
  255. } finally {
  256. if(pageNumber == 0) {
  257. // de-mask header
  258. applyHeaderMask(page);
  259. }
  260. }
  261. }
  262. /**
  263. * Allocates a new page in the database. Data in the page is undefined
  264. * until it is written in a call to {@link #writePage(ByteBuffer,int)}.
  265. */
  266. public int allocateNewPage() throws IOException {
  267. assertWriting();
  268. // this will force the file to be extended with mostly undefined bytes
  269. long size = _channel.size();
  270. if(size >= getFormat().MAX_DATABASE_SIZE) {
  271. throw new IOException("Database is at maximum size " +
  272. getFormat().MAX_DATABASE_SIZE);
  273. }
  274. if((size % getFormat().PAGE_SIZE) != 0L) {
  275. throw new IOException("Database corrupted, file size " + size +
  276. " is not multiple of page size " +
  277. getFormat().PAGE_SIZE);
  278. }
  279. _forceBytes.rewind();
  280. // push the buffer to the end of the page, so that a full page's worth of
  281. // data is written
  282. int pageOffset = (getFormat().PAGE_SIZE - _forceBytes.remaining());
  283. long offset = size + pageOffset;
  284. int pageNumber = getNextPageNumber(size);
  285. // since we are just allocating page space at this point and not writing
  286. // meaningful data, we do _not_ encode the page.
  287. _channel.write(_forceBytes, offset);
  288. // note, we "force" page removal because we know that this is an unused
  289. // page (since we just added it to the file)
  290. _globalUsageMap.removePageNumber(pageNumber, true);
  291. return pageNumber;
  292. }
  293. /**
  294. * Deallocate a previously used page in the database.
  295. */
  296. public void deallocatePage(int pageNumber) throws IOException {
  297. assertWriting();
  298. validatePageNumber(pageNumber);
  299. // don't write the whole page, just wipe out the header (which should be
  300. // enough to let us know if we accidentally try to use an invalid page)
  301. _invalidPageBytes.rewind();
  302. _channel.write(_invalidPageBytes, getPageOffset(pageNumber));
  303. _globalUsageMap.addPageNumber(pageNumber); //force is done here
  304. }
  305. /**
  306. * @return A newly-allocated buffer that can be passed to readPage
  307. */
  308. public ByteBuffer createPageBuffer() {
  309. return createBuffer(getFormat().PAGE_SIZE);
  310. }
  311. /**
  312. * @return A newly-allocated buffer of the given size and DEFAULT_BYTE_ORDER
  313. * byte order
  314. */
  315. public static ByteBuffer createBuffer(int size) {
  316. return createBuffer(size, DEFAULT_BYTE_ORDER);
  317. }
  318. /**
  319. * @return A newly-allocated buffer of the given size and byte order
  320. */
  321. public static ByteBuffer createBuffer(int size, ByteOrder order) {
  322. return ByteBuffer.allocate(size).order(order);
  323. }
  324. public void flush() throws IOException {
  325. _channel.force(true);
  326. }
  327. public void close() throws IOException {
  328. flush();
  329. if(_closeChannel) {
  330. _channel.close();
  331. }
  332. }
  333. public boolean isOpen() {
  334. return _channel.isOpen();
  335. }
  336. /**
  337. * Applies the XOR mask to the database header in the given buffer.
  338. */
  339. private void applyHeaderMask(ByteBuffer buffer) {
  340. // de/re-obfuscate the header
  341. byte[] headerMask = _format.HEADER_MASK;
  342. for(int idx = 0; idx < headerMask.length; ++idx) {
  343. int pos = idx + _format.OFFSET_MASKED_HEADER;
  344. byte b = (byte)(buffer.get(pos) ^ headerMask[idx]);
  345. buffer.put(pos, b);
  346. }
  347. }
  348. /**
  349. * @return a duplicate of the current buffer narrowed to the given position
  350. * and limit. mark will be set at the current position.
  351. */
  352. public static ByteBuffer narrowBuffer(ByteBuffer buffer, int position,
  353. int limit)
  354. {
  355. return (ByteBuffer)buffer.duplicate()
  356. .order(buffer.order())
  357. .clear()
  358. .limit(limit)
  359. .position(position)
  360. .mark();
  361. }
  362. /**
  363. * Returns a ByteBuffer wrapping the given bytes and configured with the
  364. * default byte order.
  365. */
  366. public static ByteBuffer wrap(byte[] bytes) {
  367. return ByteBuffer.wrap(bytes).order(DEFAULT_BYTE_ORDER);
  368. }
  369. }