github.com/sykesm/fabric@v1.1.0-preview.0.20200129034918-2aa12b1a0181/common/ledger/blkstorage/fsblkstorage/blockfile_rw.go (about)

     1  /*
     2  Copyright IBM Corp. All Rights Reserved.
     3  
     4  SPDX-License-Identifier: Apache-2.0
     5  */
     6  
     7  package fsblkstorage
     8  
     9  import (
    10  	"os"
    11  
    12  	"github.com/pkg/errors"
    13  )
    14  
    15  ////  WRITER ////
    16  type blockfileWriter struct {
    17  	filePath string
    18  	file     *os.File
    19  }
    20  
    21  func newBlockfileWriter(filePath string) (*blockfileWriter, error) {
    22  	writer := &blockfileWriter{filePath: filePath}
    23  	return writer, writer.open()
    24  }
    25  
    26  func (w *blockfileWriter) truncateFile(targetSize int) error {
    27  	fileStat, err := w.file.Stat()
    28  	if err != nil {
    29  		return errors.Wrapf(err, "error truncating the file [%s] to size [%d]", w.filePath, targetSize)
    30  	}
    31  	if fileStat.Size() > int64(targetSize) {
    32  		w.file.Truncate(int64(targetSize))
    33  	}
    34  	return nil
    35  }
    36  
    37  func (w *blockfileWriter) append(b []byte, sync bool) error {
    38  	_, err := w.file.Write(b)
    39  	if err != nil {
    40  		return err
    41  	}
    42  	if sync {
    43  		return w.file.Sync()
    44  	}
    45  	return nil
    46  }
    47  
    48  func (w *blockfileWriter) open() error {
    49  	file, err := os.OpenFile(w.filePath, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0660)
    50  	if err != nil {
    51  		return errors.Wrapf(err, "error opening block file writer for file %s", w.filePath)
    52  	}
    53  	w.file = file
    54  	return nil
    55  }
    56  
    57  func (w *blockfileWriter) close() error {
    58  	return errors.WithStack(w.file.Close())
    59  }
    60  
    61  ////  READER ////
    62  type blockfileReader struct {
    63  	file *os.File
    64  }
    65  
    66  func newBlockfileReader(filePath string) (*blockfileReader, error) {
    67  	file, err := os.OpenFile(filePath, os.O_RDONLY, 0600)
    68  	if err != nil {
    69  		return nil, errors.Wrapf(err, "error opening block file reader for file %s", filePath)
    70  	}
    71  	reader := &blockfileReader{file}
    72  	return reader, nil
    73  }
    74  
    75  func (r *blockfileReader) read(offset int, length int) ([]byte, error) {
    76  	b := make([]byte, length)
    77  	_, err := r.file.ReadAt(b, int64(offset))
    78  	if err != nil {
    79  		return nil, errors.Wrapf(err, "error reading block file for offset %d and length %d", offset, length)
    80  	}
    81  	return b, nil
    82  }
    83  
    84  func (r *blockfileReader) close() error {
    85  	return errors.WithStack(r.file.Close())
    86  }