blockfile_rw.go 1.81 KB
Newer Older
manish's avatar
manish committed
1
/*
2
Copyright IBM Corp. All Rights Reserved.
manish's avatar
manish committed
3

4
SPDX-License-Identifier: Apache-2.0
manish's avatar
manish committed
5
6
7
8
9
10
*/

package fsblkstorage

import (
	"os"
11
12

	"github.com/pkg/errors"
manish's avatar
manish committed
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
)

////  WRITER ////
type blockfileWriter struct {
	filePath string
	file     *os.File
}

func newBlockfileWriter(filePath string) (*blockfileWriter, error) {
	writer := &blockfileWriter{filePath: filePath}
	return writer, writer.open()
}

func (w *blockfileWriter) truncateFile(targetSize int) error {
	fileStat, err := w.file.Stat()
	if err != nil {
		return err
	}
	if fileStat.Size() > int64(targetSize) {
		w.file.Truncate(int64(targetSize))
	}
	return nil
}

manish's avatar
manish committed
37
func (w *blockfileWriter) append(b []byte, sync bool) error {
manish's avatar
manish committed
38
39
40
41
	_, err := w.file.Write(b)
	if err != nil {
		return err
	}
manish's avatar
manish committed
42
43
44
	if sync {
		return w.file.Sync()
	}
manish's avatar
manish committed
45
46
47
48
49
50
	return nil
}

func (w *blockfileWriter) open() error {
	file, err := os.OpenFile(w.filePath, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0660)
	if err != nil {
51
		return errors.Wrapf(err, "error opening block file writer for file %s", w.filePath)
manish's avatar
manish committed
52
53
54
55
56
57
	}
	w.file = file
	return nil
}

func (w *blockfileWriter) close() error {
58
	return errors.WithStack(w.file.Close())
manish's avatar
manish committed
59
60
61
62
63
64
65
66
67
68
}

////  READER ////
type blockfileReader struct {
	file *os.File
}

func newBlockfileReader(filePath string) (*blockfileReader, error) {
	file, err := os.OpenFile(filePath, os.O_RDONLY, 0600)
	if err != nil {
69
		return nil, errors.Wrapf(err, "error opening block file reader for file %s", filePath)
manish's avatar
manish committed
70
71
72
73
74
75
76
77
78
	}
	reader := &blockfileReader{file}
	return reader, nil
}

func (r *blockfileReader) read(offset int, length int) ([]byte, error) {
	b := make([]byte, length)
	_, err := r.file.ReadAt(b, int64(offset))
	if err != nil {
79
		return nil, errors.Wrapf(err, "error reading block file for offset %d and length %d", offset, length)
manish's avatar
manish committed
80
81
82
83
84
	}
	return b, nil
}

func (r *blockfileReader) close() error {
85
	return errors.WithStack(r.file.Close())
manish's avatar
manish committed
86
}