Debian Codegraph @

jdbm1/src/main/java/jdbm/recman/TransactionManager.java

raw
1 /**
2 * JDBM LICENSE v1.00
3 *
4 * Redistribution and use of this software and associated documentation
5 * ("Software"), with or without modification, are permitted provided
6 * that the following conditions are met:
7 *
8 * 1. Redistributions of source code must retain copyright
9 * statements and notices. Redistributions must also contain a
10 * copy of this document.
11 *
12 * 2. Redistributions in binary form must reproduce the
13 * above copyright notice, this list of conditions and the
14 * following disclaimer in the documentation and/or other
15 * materials provided with the distribution.
16 *
17 * 3. The name "JDBM" must not be used to endorse or promote
18 * products derived from this Software without prior written
19 * permission of Cees de Groot. For written permission,
20 * please contact [email protected].
21 *
22 * 4. Products derived from this Software may not be called "JDBM"
23 * nor may "JDBM" appear in their names without prior written
24 * permission of Cees de Groot.
25 *
26 * 5. Due credit should be given to the JDBM Project
27 * (http://jdbm.sourceforge.net/).
28 *
29 * THIS SOFTWARE IS PROVIDED BY THE JDBM PROJECT AND CONTRIBUTORS
30 * ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT
31 * NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
32 * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
33 * CEES DE GROOT OR ANY CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
34 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
35 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
36 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
37 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
38 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
39 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
40 * OF THE POSSIBILITY OF SUCH DAMAGE.
41 *
42 * Copyright 2000 (C) Cees de Groot. All Rights Reserved.
43 * Contributions are Copyright (C) 2000 by their associated contributors.
44 *
45 * $Id: TransactionManager.java,v 1.7 2005/06/25 23:12:32 doomdark Exp $
46 */
47
48 package jdbm.recman;
49
50
51 import java.io.File;
52 import java.io.FileInputStream;
53 import java.io.FileOutputStream;
54 import java.io.IOException;
55 import java.io.ObjectInputStream;
56 import java.io.ObjectOutputStream;
57 import java.util.ArrayList;
58 import java.util.Comparator;
59 import java.util.Iterator;
60 import java.util.TreeSet;
61
62 import jdbm.I18n;
63
64
65 /**
66 * This class manages the transaction log that belongs to every
67 * {@link RecordFile}. The transaction log is either clean, or
68 * in progress. In the latter case, the transaction manager
69 * takes care of a roll forward.
70 *<p>
71 * Implementation note: this is a proof-of-concept implementation
72 * which hasn't been optimized for speed. For instance, all sorts
73 * of streams are created for every transaction.
74 */
75 // TODO: Handle the case where we are recovering lg9 and lg0, were we
76 // should start with lg9 instead of lg0!
77
78 public final class TransactionManager
79 {
80 private RecordFile owner;
81
82 // streams for transaction log.
83 private FileOutputStream fos;
84 private ObjectOutputStream oos;
85
86 /**
87 * By default, we keep 10 transactions in the log file before
88 * synchronizing it with the main database file.
89 */
90 static final int DEFAULT_TXNS_IN_LOG = 10;
91
92 /**
93 * Maximum number of transactions before the log file is
94 * synchronized with the main database file.
95 */
96 private int _maxTxns = DEFAULT_TXNS_IN_LOG;
97
98 /**
99 * In-core copy of transactions. We could read everything back from
100 * the log file, but the RecordFile needs to keep the dirty blocks in
101 * core anyway, so we might as well point to them and spare us a lot
102 * of hassle.
103 */
104 private ArrayList[] txns = new ArrayList[DEFAULT_TXNS_IN_LOG];
105 private int curTxn = -1;
106
107 /** Extension of a log file. */
108 static final String extension = ".lg";
109
110
111 /**
112 * Instantiates a transaction manager instance. If recovery
113 * needs to be performed, it is done.
114 *
115 * @param owner the RecordFile instance that owns this transaction mgr.
116 */
117 TransactionManager( RecordFile owner ) throws IOException
118 {
119 this.owner = owner;
120 recover();
121 open();
122 }
123
124
125 /**
126 * Synchronize log file data with the main database file.
127 * <p>
128 * After this call, the main database file is guaranteed to be
129 * consistent and guaranteed to be the only file needed for
130 * backup purposes.
131 */
132 public void synchronizeLog()
133 throws IOException
134 {
135 synchronizeLogFromMemory();
136 }
137
138
139 /**
140 * Set the maximum number of transactions to record in
141 * the log (and keep in memory) before the log is
142 * synchronized with the main database file.
143 * <p>
144 * This method must be called while there are no
145 * pending transactions in the log.
146 */
147 public void setMaximumTransactionsInLog( int maxTxns )
148 throws IOException
149 {
150 if ( maxTxns <= 0 )
151 {
152 throw new IllegalArgumentException( I18n.err( I18n.ERR_563 ) );
153 }
154 if ( curTxn != -1 )
155 {
156 throw new IllegalStateException( I18n.err( I18n.ERR_564 ) );
157 }
158 _maxTxns = maxTxns;
159 txns = new ArrayList[maxTxns];
160 }
161
162
163 /** Builds logfile name */
164 private String makeLogName()
165 {
166 return owner.getFileName() + extension;
167 }
168
169
170 /** Synchs in-core transactions to data file and opens a fresh log */
171 private void synchronizeLogFromMemory() throws IOException
172 {
173 close();
174
175 TreeSet blockList = new TreeSet( new BlockIoComparator() );
176
177 for ( int i = 0; i < _maxTxns; i++ )
178 {
179 if ( txns[i] == null )
180 continue;
181 // Add each block to the blockList, replacing the old copy of this
182 // block if necessary, thus avoiding writing the same block twice
183 for ( Iterator k = txns[i].iterator(); k.hasNext(); )
184 {
185 BlockIo block = ( BlockIo ) k.next();
186 if ( blockList.contains( block ) )
187 {
188 block.decrementTransactionCount();
189 }
190 else
191 {
192 blockList.add( block );
193 }
194 }
195
196 txns[i] = null;
197 }
198 // Write the blocks from the blockList to disk
199 synchronizeBlocks( blockList.iterator(), true );
200
201 owner.sync();
202 open();
203 }
204
205
206 /** Opens the log file */
207 private void open() throws IOException
208 {
209 fos = new FileOutputStream( makeLogName() );
210 oos = new ObjectOutputStream( fos );
211 oos.writeShort( Magic.LOGFILE_HEADER );
212 oos.flush();
213 curTxn = -1;
214 }
215
216
217 /** Startup recovery on all files */
218 private void recover() throws IOException
219 {
220 String logName = makeLogName();
221 File logFile = new File( logName );
222 if ( !logFile.exists() )
223 return;
224 if ( logFile.length() == 0 )
225 {
226 logFile.delete();
227 return;
228 }
229
230 FileInputStream fis = new FileInputStream( logFile );
231 ObjectInputStream ois = new ObjectInputStream( fis );
232
233 try
234 {
235 if ( ois.readShort() != Magic.LOGFILE_HEADER )
236 {
237 ois.close();
238 throw new Error( I18n.err( I18n.ERR_565 ) );
239 }
240 }
241 catch ( IOException e )
242 {
243 // corrupted/empty logfile
244 ois.close();
245 logFile.delete();
246 return;
247 }
248
249 while ( true )
250 {
251 ArrayList blocks = null;
252 try
253 {
254 blocks = ( ArrayList ) ois.readObject();
255 }
256 catch ( ClassNotFoundException e )
257 {
258 ois.close();
259 throw new Error( I18n.err( I18n.ERR_566, e ) );
260 }
261 catch ( IOException e )
262 {
263 // corrupted logfile, ignore rest of transactions
264 break;
265 }
266 synchronizeBlocks( blocks.iterator(), false );
267
268 // ObjectInputStream must match exactly each
269 // ObjectOutputStream created during writes
270 try
271 {
272 ois = new ObjectInputStream( fis );
273 }
274 catch ( IOException e )
275 {
276 // corrupted logfile, ignore rest of transactions
277 break;
278 }
279 }
280 owner.sync();
281 ois.close();
282 logFile.delete();
283 }
284
285
286 /** Synchronizes the indicated blocks with the owner. */
287 private void synchronizeBlocks( Iterator blockIterator, boolean fromCore )
288 throws IOException
289 {
290 // write block vector elements to the data file.
291 while ( blockIterator.hasNext() )
292 {
293 BlockIo cur = ( BlockIo ) blockIterator.next();
294 owner.synch( cur );
295 if ( fromCore )
296 {
297 cur.decrementTransactionCount();
298 if ( !cur.isInTransaction() )
299 {
300 owner.releaseFromTransaction( cur, true );
301 }
302 }
303 }
304 }
305
306
307 /** Set clean flag on the blocks. */
308 private void setClean( ArrayList blocks )
309 throws IOException
310 {
311 for ( Iterator k = blocks.iterator(); k.hasNext(); )
312 {
313 BlockIo cur = ( BlockIo ) k.next();
314 cur.setClean();
315 }
316 }
317
318
319 /** Discards the indicated blocks and notify the owner. */
320 private void discardBlocks( ArrayList blocks )
321 throws IOException
322 {
323 for ( Iterator k = blocks.iterator(); k.hasNext(); )
324 {
325 BlockIo cur = ( BlockIo ) k.next();
326 cur.decrementTransactionCount();
327 if ( !cur.isInTransaction() )
328 {
329 owner.releaseFromTransaction( cur, false );
330 }
331 }
332 }
333
334
335 /**
336 * Starts a transaction. This can block if all slots have been filled
337 * with full transactions, waiting for the synchronization thread to
338 * clean out slots.
339 */
340 void start() throws IOException
341 {
342 curTxn++;
343 if ( curTxn == _maxTxns )
344 {
345 synchronizeLogFromMemory();
346 curTxn = 0;
347 }
348 txns[curTxn] = new ArrayList();
349 }
350
351
352 /**
353 * Indicates the block is part of the transaction.
354 */
355 void add( BlockIo block ) throws IOException
356 {
357 block.incrementTransactionCount();
358 txns[curTxn].add( block );
359 }
360
361
362 /**
363 * Commits the transaction to the log file.
364 */
365 void commit() throws IOException
366 {
367 oos.writeObject( txns[curTxn] );
368 sync();
369
370 // set clean flag to indicate blocks have been written to log
371 setClean( txns[curTxn] );
372
373 // reset ObjectOutputStream in order to store
374 // newer states of BlockIo
375 oos = new ObjectOutputStream( fos );
376 oos.reset();
377 }
378
379
380 /** Flushes and syncs */
381 private void sync() throws IOException
382 {
383 oos.flush();
384 fos.flush();
385 fos.getFD().sync();
386 }
387
388
389 /**
390 * Shutdowns the transaction manager. Resynchronizes outstanding
391 * logs.
392 */
393 void shutdown() throws IOException
394 {
395 synchronizeLogFromMemory();
396 close();
397 }
398
399
400 /**
401 * Closes open files.
402 */
403 private void close() throws IOException
404 {
405 sync();
406 oos.close();
407 fos.close();
408 oos = null;
409 fos = null;
410 }
411
412
413 /**
414 * Force closing the file without synchronizing pending transaction data.
415 * Used for testing purposes only.
416 */
417 void forceClose() throws IOException
418 {
419 oos.close();
420 fos.close();
421 oos = null;
422 fos = null;
423 }
424
425
426 /**
427 * Use the disk-based transaction log to synchronize the data file.
428 * Outstanding memory logs are discarded because they are believed
429 * to be inconsistent.
430 */
431 void synchronizeLogFromDisk() throws IOException
432 {
433 close();
434
435 for ( int i = 0; i < _maxTxns; i++ )
436 {
437 if ( txns[i] == null )
438 continue;
439 discardBlocks( txns[i] );
440 txns[i] = null;
441 }
442
443 recover();
444 open();
445 }
446
447 /** INNER CLASS.
448 * Comparator class for use by the tree set used to store the blocks
449 * to write for this transaction. The BlockIo objects are ordered by
450 * their blockIds.
451 */
452 public static class BlockIoComparator
453 implements Comparator
454 {
455
456 public int compare( Object o1, Object o2 )
457 {
458 BlockIo block1 = ( BlockIo ) o1;
459 BlockIo block2 = ( BlockIo ) o2;
460 int result = 0;
461 if ( block1.getBlockId() == block2.getBlockId() )
462 {
463 result = 0;
464 }
465 else if ( block1.getBlockId() < block2.getBlockId() )
466 {
467 result = -1;
468 }
469 else
470 {
471 result = 1;
472 }
473 return result;
474 }
475
476
477 public boolean equals( Object obj )
478 {
479 return super.equals( obj );
480 }
481 } // class BlockIOComparator
482
483 }