github.com/jimmyx0x/go-ethereum@v1.10.28/core/rawdb/freezer_table.go (about)

     1  // Copyright 2019 The go-ethereum Authors
     2  // This file is part of the go-ethereum library.
     3  //
     4  // The go-ethereum library is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU Lesser General Public License as published by
     6  // the Free Software Foundation, either version 3 of the License, or
     7  // (at your option) any later version.
     8  //
     9  // The go-ethereum library is distributed in the hope that it will be useful,
    10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    12  // GNU Lesser General Public License for more details.
    13  //
    14  // You should have received a copy of the GNU Lesser General Public License
    15  // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package rawdb
    18  
    19  import (
    20  	"bytes"
    21  	"encoding/binary"
    22  	"errors"
    23  	"fmt"
    24  	"io"
    25  	"os"
    26  	"path/filepath"
    27  	"sync"
    28  	"sync/atomic"
    29  
    30  	"github.com/ethereum/go-ethereum/common"
    31  	"github.com/ethereum/go-ethereum/log"
    32  	"github.com/ethereum/go-ethereum/metrics"
    33  	"github.com/golang/snappy"
    34  )
    35  
    36  var (
    37  	// errClosed is returned if an operation attempts to read from or write to the
    38  	// freezer table after it has already been closed.
    39  	errClosed = errors.New("closed")
    40  
    41  	// errOutOfBounds is returned if the item requested is not contained within the
    42  	// freezer table.
    43  	errOutOfBounds = errors.New("out of bounds")
    44  
    45  	// errNotSupported is returned if the database doesn't support the required operation.
    46  	errNotSupported = errors.New("this operation is not supported")
    47  )
    48  
    49  // indexEntry contains the number/id of the file that the data resides in, as well as the
    50  // offset within the file to the end of the data.
    51  // In serialized form, the filenum is stored as uint16.
    52  type indexEntry struct {
    53  	filenum uint32 // stored as uint16 ( 2 bytes )
    54  	offset  uint32 // stored as uint32 ( 4 bytes )
    55  }
    56  
    57  const indexEntrySize = 6
    58  
    59  // unmarshalBinary deserializes binary b into the rawIndex entry.
    60  func (i *indexEntry) unmarshalBinary(b []byte) {
    61  	i.filenum = uint32(binary.BigEndian.Uint16(b[:2]))
    62  	i.offset = binary.BigEndian.Uint32(b[2:6])
    63  }
    64  
    65  // append adds the encoded entry to the end of b.
    66  func (i *indexEntry) append(b []byte) []byte {
    67  	offset := len(b)
    68  	out := append(b, make([]byte, indexEntrySize)...)
    69  	binary.BigEndian.PutUint16(out[offset:], uint16(i.filenum))
    70  	binary.BigEndian.PutUint32(out[offset+2:], i.offset)
    71  	return out
    72  }
    73  
    74  // bounds returns the start- and end- offsets, and the file number of where to
    75  // read there data item marked by the two index entries. The two entries are
    76  // assumed to be sequential.
    77  func (i *indexEntry) bounds(end *indexEntry) (startOffset, endOffset, fileId uint32) {
    78  	if i.filenum != end.filenum {
    79  		// If a piece of data 'crosses' a data-file,
    80  		// it's actually in one piece on the second data-file.
    81  		// We return a zero-indexEntry for the second file as start
    82  		return 0, end.offset, end.filenum
    83  	}
    84  	return i.offset, end.offset, end.filenum
    85  }
    86  
    87  // freezerTable represents a single chained data table within the freezer (e.g. blocks).
    88  // It consists of a data file (snappy encoded arbitrary data blobs) and an indexEntry
    89  // file (uncompressed 64 bit indices into the data file).
    90  type freezerTable struct {
    91  	// WARNING: The `items` field is accessed atomically. On 32 bit platforms, only
    92  	// 64-bit aligned fields can be atomic. The struct is guaranteed to be so aligned,
    93  	// so take advantage of that (https://golang.org/pkg/sync/atomic/#pkg-note-BUG).
    94  	items      uint64 // Number of items stored in the table (including items removed from tail)
    95  	itemOffset uint64 // Number of items removed from the table
    96  
    97  	// itemHidden is the number of items marked as deleted. Tail deletion is
    98  	// only supported at file level which means the actual deletion will be
    99  	// delayed until the entire data file is marked as deleted. Before that
   100  	// these items will be hidden to prevent being visited again. The value
   101  	// should never be lower than itemOffset.
   102  	itemHidden uint64
   103  
   104  	noCompression bool // if true, disables snappy compression. Note: does not work retroactively
   105  	readonly      bool
   106  	maxFileSize   uint32 // Max file size for data-files
   107  	name          string
   108  	path          string
   109  
   110  	head   *os.File            // File descriptor for the data head of the table
   111  	index  *os.File            // File descriptor for the indexEntry file of the table
   112  	meta   *os.File            // File descriptor for metadata of the table
   113  	files  map[uint32]*os.File // open files
   114  	headId uint32              // number of the currently active head file
   115  	tailId uint32              // number of the earliest file
   116  
   117  	headBytes  int64         // Number of bytes written to the head file
   118  	readMeter  metrics.Meter // Meter for measuring the effective amount of data read
   119  	writeMeter metrics.Meter // Meter for measuring the effective amount of data written
   120  	sizeGauge  metrics.Gauge // Gauge for tracking the combined size of all freezer tables
   121  
   122  	logger log.Logger   // Logger with database path and table name embedded
   123  	lock   sync.RWMutex // Mutex protecting the data file descriptors
   124  }
   125  
   126  // newFreezerTable opens the given path as a freezer table.
   127  func newFreezerTable(path, name string, disableSnappy, readonly bool) (*freezerTable, error) {
   128  	return newTable(path, name, metrics.NilMeter{}, metrics.NilMeter{}, metrics.NilGauge{}, freezerTableSize, disableSnappy, readonly)
   129  }
   130  
   131  // newTable opens a freezer table, creating the data and index files if they are
   132  // non-existent. Both files are truncated to the shortest common length to ensure
   133  // they don't go out of sync.
   134  func newTable(path string, name string, readMeter metrics.Meter, writeMeter metrics.Meter, sizeGauge metrics.Gauge, maxFilesize uint32, noCompression, readonly bool) (*freezerTable, error) {
   135  	// Ensure the containing directory exists and open the indexEntry file
   136  	if err := os.MkdirAll(path, 0755); err != nil {
   137  		return nil, err
   138  	}
   139  	var idxName string
   140  	if noCompression {
   141  		idxName = fmt.Sprintf("%s.ridx", name) // raw index file
   142  	} else {
   143  		idxName = fmt.Sprintf("%s.cidx", name) // compressed index file
   144  	}
   145  	var (
   146  		err   error
   147  		index *os.File
   148  		meta  *os.File
   149  	)
   150  	if readonly {
   151  		// Will fail if table index file or meta file is not existent
   152  		index, err = openFreezerFileForReadOnly(filepath.Join(path, idxName))
   153  		if err != nil {
   154  			return nil, err
   155  		}
   156  		meta, err = openFreezerFileForReadOnly(filepath.Join(path, fmt.Sprintf("%s.meta", name)))
   157  		if err != nil {
   158  			return nil, err
   159  		}
   160  	} else {
   161  		index, err = openFreezerFileForAppend(filepath.Join(path, idxName))
   162  		if err != nil {
   163  			return nil, err
   164  		}
   165  		meta, err = openFreezerFileForAppend(filepath.Join(path, fmt.Sprintf("%s.meta", name)))
   166  		if err != nil {
   167  			return nil, err
   168  		}
   169  	}
   170  	// Create the table and repair any past inconsistency
   171  	tab := &freezerTable{
   172  		index:         index,
   173  		meta:          meta,
   174  		files:         make(map[uint32]*os.File),
   175  		readMeter:     readMeter,
   176  		writeMeter:    writeMeter,
   177  		sizeGauge:     sizeGauge,
   178  		name:          name,
   179  		path:          path,
   180  		logger:        log.New("database", path, "table", name),
   181  		noCompression: noCompression,
   182  		readonly:      readonly,
   183  		maxFileSize:   maxFilesize,
   184  	}
   185  	if err := tab.repair(); err != nil {
   186  		tab.Close()
   187  		return nil, err
   188  	}
   189  	// Initialize the starting size counter
   190  	size, err := tab.sizeNolock()
   191  	if err != nil {
   192  		tab.Close()
   193  		return nil, err
   194  	}
   195  	tab.sizeGauge.Inc(int64(size))
   196  
   197  	return tab, nil
   198  }
   199  
   200  // repair cross-checks the head and the index file and truncates them to
   201  // be in sync with each other after a potential crash / data loss.
   202  func (t *freezerTable) repair() error {
   203  	// Create a temporary offset buffer to init files with and read indexEntry into
   204  	buffer := make([]byte, indexEntrySize)
   205  
   206  	// If we've just created the files, initialize the index with the 0 indexEntry
   207  	stat, err := t.index.Stat()
   208  	if err != nil {
   209  		return err
   210  	}
   211  	if stat.Size() == 0 {
   212  		if _, err := t.index.Write(buffer); err != nil {
   213  			return err
   214  		}
   215  	}
   216  	// Ensure the index is a multiple of indexEntrySize bytes
   217  	if overflow := stat.Size() % indexEntrySize; overflow != 0 {
   218  		truncateFreezerFile(t.index, stat.Size()-overflow) // New file can't trigger this path
   219  	}
   220  	// Retrieve the file sizes and prepare for truncation
   221  	if stat, err = t.index.Stat(); err != nil {
   222  		return err
   223  	}
   224  	offsetsSize := stat.Size()
   225  
   226  	// Open the head file
   227  	var (
   228  		firstIndex  indexEntry
   229  		lastIndex   indexEntry
   230  		contentSize int64
   231  		contentExp  int64
   232  	)
   233  	// Read index zero, determine what file is the earliest
   234  	// and what item offset to use
   235  	t.index.ReadAt(buffer, 0)
   236  	firstIndex.unmarshalBinary(buffer)
   237  
   238  	// Assign the tail fields with the first stored index.
   239  	// The total removed items is represented with an uint32,
   240  	// which is not enough in theory but enough in practice.
   241  	// TODO: use uint64 to represent total removed items.
   242  	t.tailId = firstIndex.filenum
   243  	t.itemOffset = uint64(firstIndex.offset)
   244  
   245  	// Load metadata from the file
   246  	meta, err := loadMetadata(t.meta, t.itemOffset)
   247  	if err != nil {
   248  		return err
   249  	}
   250  	t.itemHidden = meta.VirtualTail
   251  
   252  	// Read the last index, use the default value in case the freezer is empty
   253  	if offsetsSize == indexEntrySize {
   254  		lastIndex = indexEntry{filenum: t.tailId, offset: 0}
   255  	} else {
   256  		t.index.ReadAt(buffer, offsetsSize-indexEntrySize)
   257  		lastIndex.unmarshalBinary(buffer)
   258  	}
   259  	if t.readonly {
   260  		t.head, err = t.openFile(lastIndex.filenum, openFreezerFileForReadOnly)
   261  	} else {
   262  		t.head, err = t.openFile(lastIndex.filenum, openFreezerFileForAppend)
   263  	}
   264  	if err != nil {
   265  		return err
   266  	}
   267  	if stat, err = t.head.Stat(); err != nil {
   268  		return err
   269  	}
   270  	contentSize = stat.Size()
   271  
   272  	// Keep truncating both files until they come in sync
   273  	contentExp = int64(lastIndex.offset)
   274  	for contentExp != contentSize {
   275  		// Truncate the head file to the last offset pointer
   276  		if contentExp < contentSize {
   277  			t.logger.Warn("Truncating dangling head", "indexed", common.StorageSize(contentExp), "stored", common.StorageSize(contentSize))
   278  			if err := truncateFreezerFile(t.head, contentExp); err != nil {
   279  				return err
   280  			}
   281  			contentSize = contentExp
   282  		}
   283  		// Truncate the index to point within the head file
   284  		if contentExp > contentSize {
   285  			t.logger.Warn("Truncating dangling indexes", "indexed", common.StorageSize(contentExp), "stored", common.StorageSize(contentSize))
   286  			if err := truncateFreezerFile(t.index, offsetsSize-indexEntrySize); err != nil {
   287  				return err
   288  			}
   289  			offsetsSize -= indexEntrySize
   290  
   291  			// Read the new head index, use the default value in case
   292  			// the freezer is already empty.
   293  			var newLastIndex indexEntry
   294  			if offsetsSize == indexEntrySize {
   295  				newLastIndex = indexEntry{filenum: t.tailId, offset: 0}
   296  			} else {
   297  				t.index.ReadAt(buffer, offsetsSize-indexEntrySize)
   298  				newLastIndex.unmarshalBinary(buffer)
   299  			}
   300  			// We might have slipped back into an earlier head-file here
   301  			if newLastIndex.filenum != lastIndex.filenum {
   302  				// Release earlier opened file
   303  				t.releaseFile(lastIndex.filenum)
   304  				if t.head, err = t.openFile(newLastIndex.filenum, openFreezerFileForAppend); err != nil {
   305  					return err
   306  				}
   307  				if stat, err = t.head.Stat(); err != nil {
   308  					// TODO, anything more we can do here?
   309  					// A data file has gone missing...
   310  					return err
   311  				}
   312  				contentSize = stat.Size()
   313  			}
   314  			lastIndex = newLastIndex
   315  			contentExp = int64(lastIndex.offset)
   316  		}
   317  	}
   318  	// Sync() fails for read-only files on windows.
   319  	if !t.readonly {
   320  		// Ensure all reparation changes have been written to disk
   321  		if err := t.index.Sync(); err != nil {
   322  			return err
   323  		}
   324  		if err := t.head.Sync(); err != nil {
   325  			return err
   326  		}
   327  		if err := t.meta.Sync(); err != nil {
   328  			return err
   329  		}
   330  	}
   331  	// Update the item and byte counters and return
   332  	t.items = t.itemOffset + uint64(offsetsSize/indexEntrySize-1) // last indexEntry points to the end of the data file
   333  	t.headBytes = contentSize
   334  	t.headId = lastIndex.filenum
   335  
   336  	// Delete the leftover files because of head deletion
   337  	t.releaseFilesAfter(t.headId, true)
   338  
   339  	// Delete the leftover files because of tail deletion
   340  	t.releaseFilesBefore(t.tailId, true)
   341  
   342  	// Close opened files and preopen all files
   343  	if err := t.preopen(); err != nil {
   344  		return err
   345  	}
   346  	t.logger.Debug("Chain freezer table opened", "items", t.items, "size", common.StorageSize(t.headBytes))
   347  	return nil
   348  }
   349  
   350  // preopen opens all files that the freezer will need. This method should be called from an init-context,
   351  // since it assumes that it doesn't have to bother with locking
   352  // The rationale for doing preopen is to not have to do it from within Retrieve, thus not needing to ever
   353  // obtain a write-lock within Retrieve.
   354  func (t *freezerTable) preopen() (err error) {
   355  	// The repair might have already opened (some) files
   356  	t.releaseFilesAfter(0, false)
   357  
   358  	// Open all except head in RDONLY
   359  	for i := t.tailId; i < t.headId; i++ {
   360  		if _, err = t.openFile(i, openFreezerFileForReadOnly); err != nil {
   361  			return err
   362  		}
   363  	}
   364  	if t.readonly {
   365  		t.head, err = t.openFile(t.headId, openFreezerFileForReadOnly)
   366  	} else {
   367  		// Open head in read/write
   368  		t.head, err = t.openFile(t.headId, openFreezerFileForAppend)
   369  	}
   370  	return err
   371  }
   372  
   373  // truncateHead discards any recent data above the provided threshold number.
   374  func (t *freezerTable) truncateHead(items uint64) error {
   375  	t.lock.Lock()
   376  	defer t.lock.Unlock()
   377  
   378  	// Ensure the given truncate target falls in the correct range
   379  	existing := atomic.LoadUint64(&t.items)
   380  	if existing <= items {
   381  		return nil
   382  	}
   383  	if items < atomic.LoadUint64(&t.itemHidden) {
   384  		return errors.New("truncation below tail")
   385  	}
   386  	// We need to truncate, save the old size for metrics tracking
   387  	oldSize, err := t.sizeNolock()
   388  	if err != nil {
   389  		return err
   390  	}
   391  	// Something's out of sync, truncate the table's offset index
   392  	log := t.logger.Debug
   393  	if existing > items+1 {
   394  		log = t.logger.Warn // Only loud warn if we delete multiple items
   395  	}
   396  	log("Truncating freezer table", "items", existing, "limit", items)
   397  
   398  	// Truncate the index file first, the tail position is also considered
   399  	// when calculating the new freezer table length.
   400  	length := items - atomic.LoadUint64(&t.itemOffset)
   401  	if err := truncateFreezerFile(t.index, int64(length+1)*indexEntrySize); err != nil {
   402  		return err
   403  	}
   404  	// Calculate the new expected size of the data file and truncate it
   405  	var expected indexEntry
   406  	if length == 0 {
   407  		expected = indexEntry{filenum: t.tailId, offset: 0}
   408  	} else {
   409  		buffer := make([]byte, indexEntrySize)
   410  		if _, err := t.index.ReadAt(buffer, int64(length*indexEntrySize)); err != nil {
   411  			return err
   412  		}
   413  		expected.unmarshalBinary(buffer)
   414  	}
   415  	// We might need to truncate back to older files
   416  	if expected.filenum != t.headId {
   417  		// If already open for reading, force-reopen for writing
   418  		t.releaseFile(expected.filenum)
   419  		newHead, err := t.openFile(expected.filenum, openFreezerFileForAppend)
   420  		if err != nil {
   421  			return err
   422  		}
   423  		// Release any files _after the current head -- both the previous head
   424  		// and any files which may have been opened for reading
   425  		t.releaseFilesAfter(expected.filenum, true)
   426  		// Set back the historic head
   427  		t.head = newHead
   428  		t.headId = expected.filenum
   429  	}
   430  	if err := truncateFreezerFile(t.head, int64(expected.offset)); err != nil {
   431  		return err
   432  	}
   433  	// All data files truncated, set internal counters and return
   434  	t.headBytes = int64(expected.offset)
   435  	atomic.StoreUint64(&t.items, items)
   436  
   437  	// Retrieve the new size and update the total size counter
   438  	newSize, err := t.sizeNolock()
   439  	if err != nil {
   440  		return err
   441  	}
   442  	t.sizeGauge.Dec(int64(oldSize - newSize))
   443  	return nil
   444  }
   445  
   446  // truncateTail discards any recent data before the provided threshold number.
   447  func (t *freezerTable) truncateTail(items uint64) error {
   448  	t.lock.Lock()
   449  	defer t.lock.Unlock()
   450  
   451  	// Ensure the given truncate target falls in the correct range
   452  	if atomic.LoadUint64(&t.itemHidden) >= items {
   453  		return nil
   454  	}
   455  	if atomic.LoadUint64(&t.items) < items {
   456  		return errors.New("truncation above head")
   457  	}
   458  	// Load the new tail index by the given new tail position
   459  	var (
   460  		newTailId uint32
   461  		buffer    = make([]byte, indexEntrySize)
   462  	)
   463  	if atomic.LoadUint64(&t.items) == items {
   464  		newTailId = t.headId
   465  	} else {
   466  		offset := items - atomic.LoadUint64(&t.itemOffset)
   467  		if _, err := t.index.ReadAt(buffer, int64((offset+1)*indexEntrySize)); err != nil {
   468  			return err
   469  		}
   470  		var newTail indexEntry
   471  		newTail.unmarshalBinary(buffer)
   472  		newTailId = newTail.filenum
   473  	}
   474  	// Update the virtual tail marker and hidden these entries in table.
   475  	atomic.StoreUint64(&t.itemHidden, items)
   476  	if err := writeMetadata(t.meta, newMetadata(items)); err != nil {
   477  		return err
   478  	}
   479  	// Hidden items still fall in the current tail file, no data file
   480  	// can be dropped.
   481  	if t.tailId == newTailId {
   482  		return nil
   483  	}
   484  	// Hidden items fall in the incorrect range, returns the error.
   485  	if t.tailId > newTailId {
   486  		return fmt.Errorf("invalid index, tail-file %d, item-file %d", t.tailId, newTailId)
   487  	}
   488  	// Hidden items exceed the current tail file, drop the relevant
   489  	// data files. We need to truncate, save the old size for metrics
   490  	// tracking.
   491  	oldSize, err := t.sizeNolock()
   492  	if err != nil {
   493  		return err
   494  	}
   495  	// Count how many items can be deleted from the file.
   496  	var (
   497  		newDeleted = items
   498  		deleted    = atomic.LoadUint64(&t.itemOffset)
   499  	)
   500  	for current := items - 1; current >= deleted; current -= 1 {
   501  		if _, err := t.index.ReadAt(buffer, int64((current-deleted+1)*indexEntrySize)); err != nil {
   502  			return err
   503  		}
   504  		var pre indexEntry
   505  		pre.unmarshalBinary(buffer)
   506  		if pre.filenum != newTailId {
   507  			break
   508  		}
   509  		newDeleted = current
   510  	}
   511  	// Commit the changes of metadata file first before manipulating
   512  	// the indexes file.
   513  	if err := t.meta.Sync(); err != nil {
   514  		return err
   515  	}
   516  	// Truncate the deleted index entries from the index file.
   517  	err = copyFrom(t.index.Name(), t.index.Name(), indexEntrySize*(newDeleted-deleted+1), func(f *os.File) error {
   518  		tailIndex := indexEntry{
   519  			filenum: newTailId,
   520  			offset:  uint32(newDeleted),
   521  		}
   522  		_, err := f.Write(tailIndex.append(nil))
   523  		return err
   524  	})
   525  	if err != nil {
   526  		return err
   527  	}
   528  	// Reopen the modified index file to load the changes
   529  	if err := t.index.Close(); err != nil {
   530  		return err
   531  	}
   532  	t.index, err = openFreezerFileForAppend(t.index.Name())
   533  	if err != nil {
   534  		return err
   535  	}
   536  	// Release any files before the current tail
   537  	t.tailId = newTailId
   538  	atomic.StoreUint64(&t.itemOffset, newDeleted)
   539  	t.releaseFilesBefore(t.tailId, true)
   540  
   541  	// Retrieve the new size and update the total size counter
   542  	newSize, err := t.sizeNolock()
   543  	if err != nil {
   544  		return err
   545  	}
   546  	t.sizeGauge.Dec(int64(oldSize - newSize))
   547  	return nil
   548  }
   549  
   550  // Close closes all opened files.
   551  func (t *freezerTable) Close() error {
   552  	t.lock.Lock()
   553  	defer t.lock.Unlock()
   554  
   555  	var errs []error
   556  	if err := t.index.Close(); err != nil {
   557  		errs = append(errs, err)
   558  	}
   559  	t.index = nil
   560  
   561  	if err := t.meta.Close(); err != nil {
   562  		errs = append(errs, err)
   563  	}
   564  	t.meta = nil
   565  
   566  	for _, f := range t.files {
   567  		if err := f.Close(); err != nil {
   568  			errs = append(errs, err)
   569  		}
   570  	}
   571  	t.head = nil
   572  
   573  	if errs != nil {
   574  		return fmt.Errorf("%v", errs)
   575  	}
   576  	return nil
   577  }
   578  
   579  // openFile assumes that the write-lock is held by the caller
   580  func (t *freezerTable) openFile(num uint32, opener func(string) (*os.File, error)) (f *os.File, err error) {
   581  	var exist bool
   582  	if f, exist = t.files[num]; !exist {
   583  		var name string
   584  		if t.noCompression {
   585  			name = fmt.Sprintf("%s.%04d.rdat", t.name, num)
   586  		} else {
   587  			name = fmt.Sprintf("%s.%04d.cdat", t.name, num)
   588  		}
   589  		f, err = opener(filepath.Join(t.path, name))
   590  		if err != nil {
   591  			return nil, err
   592  		}
   593  		t.files[num] = f
   594  	}
   595  	return f, err
   596  }
   597  
   598  // releaseFile closes a file, and removes it from the open file cache.
   599  // Assumes that the caller holds the write lock
   600  func (t *freezerTable) releaseFile(num uint32) {
   601  	if f, exist := t.files[num]; exist {
   602  		delete(t.files, num)
   603  		f.Close()
   604  	}
   605  }
   606  
   607  // releaseFilesAfter closes all open files with a higher number, and optionally also deletes the files
   608  func (t *freezerTable) releaseFilesAfter(num uint32, remove bool) {
   609  	for fnum, f := range t.files {
   610  		if fnum > num {
   611  			delete(t.files, fnum)
   612  			f.Close()
   613  			if remove {
   614  				os.Remove(f.Name())
   615  			}
   616  		}
   617  	}
   618  }
   619  
   620  // releaseFilesBefore closes all open files with a lower number, and optionally also deletes the files
   621  func (t *freezerTable) releaseFilesBefore(num uint32, remove bool) {
   622  	for fnum, f := range t.files {
   623  		if fnum < num {
   624  			delete(t.files, fnum)
   625  			f.Close()
   626  			if remove {
   627  				os.Remove(f.Name())
   628  			}
   629  		}
   630  	}
   631  }
   632  
   633  // getIndices returns the index entries for the given from-item, covering 'count' items.
   634  // N.B: The actual number of returned indices for N items will always be N+1 (unless an
   635  // error is returned).
   636  // OBS: This method assumes that the caller has already verified (and/or trimmed) the range
   637  // so that the items are within bounds. If this method is used to read out of bounds,
   638  // it will return error.
   639  func (t *freezerTable) getIndices(from, count uint64) ([]*indexEntry, error) {
   640  	// Apply the table-offset
   641  	from = from - t.itemOffset
   642  	// For reading N items, we need N+1 indices.
   643  	buffer := make([]byte, (count+1)*indexEntrySize)
   644  	if _, err := t.index.ReadAt(buffer, int64(from*indexEntrySize)); err != nil {
   645  		return nil, err
   646  	}
   647  	var (
   648  		indices []*indexEntry
   649  		offset  int
   650  	)
   651  	for i := from; i <= from+count; i++ {
   652  		index := new(indexEntry)
   653  		index.unmarshalBinary(buffer[offset:])
   654  		offset += indexEntrySize
   655  		indices = append(indices, index)
   656  	}
   657  	if from == 0 {
   658  		// Special case if we're reading the first item in the freezer. We assume that
   659  		// the first item always start from zero(regarding the deletion, we
   660  		// only support deletion by files, so that the assumption is held).
   661  		// This means we can use the first item metadata to carry information about
   662  		// the 'global' offset, for the deletion-case
   663  		indices[0].offset = 0
   664  		indices[0].filenum = indices[1].filenum
   665  	}
   666  	return indices, nil
   667  }
   668  
   669  // Retrieve looks up the data offset of an item with the given number and retrieves
   670  // the raw binary blob from the data file.
   671  func (t *freezerTable) Retrieve(item uint64) ([]byte, error) {
   672  	items, err := t.RetrieveItems(item, 1, 0)
   673  	if err != nil {
   674  		return nil, err
   675  	}
   676  	return items[0], nil
   677  }
   678  
   679  // RetrieveItems returns multiple items in sequence, starting from the index 'start'.
   680  // It will return at most 'max' items, but will abort earlier to respect the
   681  // 'maxBytes' argument. However, if the 'maxBytes' is smaller than the size of one
   682  // item, it _will_ return one element and possibly overflow the maxBytes.
   683  func (t *freezerTable) RetrieveItems(start, count, maxBytes uint64) ([][]byte, error) {
   684  	// First we read the 'raw' data, which might be compressed.
   685  	diskData, sizes, err := t.retrieveItems(start, count, maxBytes)
   686  	if err != nil {
   687  		return nil, err
   688  	}
   689  	var (
   690  		output     = make([][]byte, 0, count)
   691  		offset     int // offset for reading
   692  		outputSize int // size of uncompressed data
   693  	)
   694  	// Now slice up the data and decompress.
   695  	for i, diskSize := range sizes {
   696  		item := diskData[offset : offset+diskSize]
   697  		offset += diskSize
   698  		decompressedSize := diskSize
   699  		if !t.noCompression {
   700  			decompressedSize, _ = snappy.DecodedLen(item)
   701  		}
   702  		if i > 0 && uint64(outputSize+decompressedSize) > maxBytes {
   703  			break
   704  		}
   705  		if !t.noCompression {
   706  			data, err := snappy.Decode(nil, item)
   707  			if err != nil {
   708  				return nil, err
   709  			}
   710  			output = append(output, data)
   711  		} else {
   712  			output = append(output, item)
   713  		}
   714  		outputSize += decompressedSize
   715  	}
   716  	return output, nil
   717  }
   718  
   719  // retrieveItems reads up to 'count' items from the table. It reads at least
   720  // one item, but otherwise avoids reading more than maxBytes bytes.
   721  // It returns the (potentially compressed) data, and the sizes.
   722  func (t *freezerTable) retrieveItems(start, count, maxBytes uint64) ([]byte, []int, error) {
   723  	t.lock.RLock()
   724  	defer t.lock.RUnlock()
   725  
   726  	// Ensure the table and the item are accessible
   727  	if t.index == nil || t.head == nil {
   728  		return nil, nil, errClosed
   729  	}
   730  	var (
   731  		items  = atomic.LoadUint64(&t.items)      // the total items(head + 1)
   732  		hidden = atomic.LoadUint64(&t.itemHidden) // the number of hidden items
   733  	)
   734  	// Ensure the start is written, not deleted from the tail, and that the
   735  	// caller actually wants something
   736  	if items <= start || hidden > start || count == 0 {
   737  		return nil, nil, errOutOfBounds
   738  	}
   739  	if start+count > items {
   740  		count = items - start
   741  	}
   742  	var (
   743  		output     = make([]byte, maxBytes) // Buffer to read data into
   744  		outputSize int                      // Used size of that buffer
   745  	)
   746  	// readData is a helper method to read a single data item from disk.
   747  	readData := func(fileId, start uint32, length int) error {
   748  		// In case a small limit is used, and the elements are large, may need to
   749  		// realloc the read-buffer when reading the first (and only) item.
   750  		if len(output) < length {
   751  			output = make([]byte, length)
   752  		}
   753  		dataFile, exist := t.files[fileId]
   754  		if !exist {
   755  			return fmt.Errorf("missing data file %d", fileId)
   756  		}
   757  		if _, err := dataFile.ReadAt(output[outputSize:outputSize+length], int64(start)); err != nil {
   758  			return err
   759  		}
   760  		outputSize += length
   761  		return nil
   762  	}
   763  	// Read all the indexes in one go
   764  	indices, err := t.getIndices(start, count)
   765  	if err != nil {
   766  		return nil, nil, err
   767  	}
   768  	var (
   769  		sizes      []int               // The sizes for each element
   770  		totalSize  = 0                 // The total size of all data read so far
   771  		readStart  = indices[0].offset // Where, in the file, to start reading
   772  		unreadSize = 0                 // The size of the as-yet-unread data
   773  	)
   774  
   775  	for i, firstIndex := range indices[:len(indices)-1] {
   776  		secondIndex := indices[i+1]
   777  		// Determine the size of the item.
   778  		offset1, offset2, _ := firstIndex.bounds(secondIndex)
   779  		size := int(offset2 - offset1)
   780  		// Crossing a file boundary?
   781  		if secondIndex.filenum != firstIndex.filenum {
   782  			// If we have unread data in the first file, we need to do that read now.
   783  			if unreadSize > 0 {
   784  				if err := readData(firstIndex.filenum, readStart, unreadSize); err != nil {
   785  					return nil, nil, err
   786  				}
   787  				unreadSize = 0
   788  			}
   789  			readStart = 0
   790  		}
   791  		if i > 0 && uint64(totalSize+size) > maxBytes {
   792  			// About to break out due to byte limit being exceeded. We don't
   793  			// read this last item, but we need to do the deferred reads now.
   794  			if unreadSize > 0 {
   795  				if err := readData(secondIndex.filenum, readStart, unreadSize); err != nil {
   796  					return nil, nil, err
   797  				}
   798  			}
   799  			break
   800  		}
   801  		// Defer the read for later
   802  		unreadSize += size
   803  		totalSize += size
   804  		sizes = append(sizes, size)
   805  		if i == len(indices)-2 || uint64(totalSize) > maxBytes {
   806  			// Last item, need to do the read now
   807  			if err := readData(secondIndex.filenum, readStart, unreadSize); err != nil {
   808  				return nil, nil, err
   809  			}
   810  			break
   811  		}
   812  	}
   813  	return output[:outputSize], sizes, nil
   814  }
   815  
   816  // has returns an indicator whether the specified number data is still accessible
   817  // in the freezer table.
   818  func (t *freezerTable) has(number uint64) bool {
   819  	return atomic.LoadUint64(&t.items) > number && atomic.LoadUint64(&t.itemHidden) <= number
   820  }
   821  
   822  // size returns the total data size in the freezer table.
   823  func (t *freezerTable) size() (uint64, error) {
   824  	t.lock.RLock()
   825  	defer t.lock.RUnlock()
   826  
   827  	return t.sizeNolock()
   828  }
   829  
   830  // sizeNolock returns the total data size in the freezer table without obtaining
   831  // the mutex first.
   832  func (t *freezerTable) sizeNolock() (uint64, error) {
   833  	stat, err := t.index.Stat()
   834  	if err != nil {
   835  		return 0, err
   836  	}
   837  	total := uint64(t.maxFileSize)*uint64(t.headId-t.tailId) + uint64(t.headBytes) + uint64(stat.Size())
   838  	return total, nil
   839  }
   840  
   841  // advanceHead should be called when the current head file would outgrow the file limits,
   842  // and a new file must be opened. The caller of this method must hold the write-lock
   843  // before calling this method.
   844  func (t *freezerTable) advanceHead() error {
   845  	t.lock.Lock()
   846  	defer t.lock.Unlock()
   847  
   848  	// We open the next file in truncated mode -- if this file already
   849  	// exists, we need to start over from scratch on it.
   850  	nextID := t.headId + 1
   851  	newHead, err := t.openFile(nextID, openFreezerFileTruncated)
   852  	if err != nil {
   853  		return err
   854  	}
   855  
   856  	// Close old file, and reopen in RDONLY mode.
   857  	t.releaseFile(t.headId)
   858  	t.openFile(t.headId, openFreezerFileForReadOnly)
   859  
   860  	// Swap out the current head.
   861  	t.head = newHead
   862  	t.headBytes = 0
   863  	t.headId = nextID
   864  	return nil
   865  }
   866  
   867  // Sync pushes any pending data from memory out to disk. This is an expensive
   868  // operation, so use it with care.
   869  func (t *freezerTable) Sync() error {
   870  	t.lock.Lock()
   871  	defer t.lock.Unlock()
   872  
   873  	var err error
   874  	trackError := func(e error) {
   875  		if e != nil && err == nil {
   876  			err = e
   877  		}
   878  	}
   879  
   880  	trackError(t.index.Sync())
   881  	trackError(t.meta.Sync())
   882  	trackError(t.head.Sync())
   883  	return err
   884  }
   885  
   886  func (t *freezerTable) dumpIndexStdout(start, stop int64) {
   887  	t.dumpIndex(os.Stdout, start, stop)
   888  }
   889  
   890  func (t *freezerTable) dumpIndexString(start, stop int64) string {
   891  	var out bytes.Buffer
   892  	out.WriteString("\n")
   893  	t.dumpIndex(&out, start, stop)
   894  	return out.String()
   895  }
   896  
   897  func (t *freezerTable) dumpIndex(w io.Writer, start, stop int64) {
   898  	meta, err := readMetadata(t.meta)
   899  	if err != nil {
   900  		fmt.Fprintf(w, "Failed to decode freezer table %v\n", err)
   901  		return
   902  	}
   903  	fmt.Fprintf(w, "Version %d deleted %d, hidden %d\n", meta.Version, atomic.LoadUint64(&t.itemOffset), atomic.LoadUint64(&t.itemHidden))
   904  
   905  	buf := make([]byte, indexEntrySize)
   906  
   907  	fmt.Fprintf(w, "| number | fileno | offset |\n")
   908  	fmt.Fprintf(w, "|--------|--------|--------|\n")
   909  
   910  	for i := uint64(start); ; i++ {
   911  		if _, err := t.index.ReadAt(buf, int64((i+1)*indexEntrySize)); err != nil {
   912  			break
   913  		}
   914  		var entry indexEntry
   915  		entry.unmarshalBinary(buf)
   916  		fmt.Fprintf(w, "|  %03d   |  %03d   |  %03d   | \n", i, entry.filenum, entry.offset)
   917  		if stop > 0 && i >= uint64(stop) {
   918  			break
   919  		}
   920  	}
   921  	fmt.Fprintf(w, "|--------------------------|\n")
   922  }