tendermint/libs/autofile/autofile.go

143 lines
2.3 KiB
Go
Raw Normal View History

2016-10-26 16:23:19 -07:00
package autofile
import (
"os"
"sync"
"time"
cmn "github.com/tendermint/tmlibs/common"
2016-10-26 16:23:19 -07:00
)
/* AutoFile usage
// Create/Append to ./autofile_test
af, err := OpenAutoFile("autofile_test")
if err != nil {
panic(err)
}
// Stream of writes.
// During this time, the file may be moved e.g. by logRotate.
for i := 0; i < 60; i++ {
af.Write([]byte(Fmt("LOOP(%v)", i)))
time.Sleep(time.Second)
}
// Close the AutoFile
err = af.Close()
if err != nil {
panic(err)
}
*/
const autoFileOpenDuration = 1000 * time.Millisecond
// Automatically closes and re-opens file for writing.
// This is useful for using a log file with the logrotate tool.
type AutoFile struct {
ID string
Path string
ticker *time.Ticker
mtx sync.Mutex
file *os.File
}
func OpenAutoFile(path string) (af *AutoFile, err error) {
af = &AutoFile{
ID: cmn.RandStr(12) + ":" + path,
2016-10-26 16:23:19 -07:00
Path: path,
ticker: time.NewTicker(autoFileOpenDuration),
}
if err = af.openFile(); err != nil {
return
}
go af.processTicks()
sighupWatchers.addAutoFile(af)
return
}
func (af *AutoFile) Close() error {
af.ticker.Stop()
err := af.closeFile()
sighupWatchers.removeAutoFile(af)
return err
}
func (af *AutoFile) processTicks() {
for {
_, ok := <-af.ticker.C
if !ok {
return // Done.
}
af.closeFile()
}
}
func (af *AutoFile) closeFile() (err error) {
af.mtx.Lock()
defer af.mtx.Unlock()
file := af.file
if file == nil {
return nil
}
af.file = nil
return file.Close()
}
func (af *AutoFile) Write(b []byte) (n int, err error) {
af.mtx.Lock()
defer af.mtx.Unlock()
2016-10-26 16:23:19 -07:00
if af.file == nil {
if err = af.openFile(); err != nil {
return
}
}
n, err = af.file.Write(b)
return
2016-10-26 16:23:19 -07:00
}
2016-11-05 17:58:50 -07:00
func (af *AutoFile) Sync() error {
2016-11-21 20:26:47 -08:00
af.mtx.Lock()
defer af.mtx.Unlock()
2017-10-02 11:17:16 -07:00
if af.file == nil {
if err := af.openFile(); err != nil {
return err
}
}
2016-11-05 17:58:50 -07:00
return af.file.Sync()
}
2016-10-26 16:23:19 -07:00
func (af *AutoFile) openFile() error {
file, err := os.OpenFile(af.Path, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0600)
if err != nil {
return err
}
af.file = file
return nil
}
func (af *AutoFile) Size() (int64, error) {
af.mtx.Lock()
defer af.mtx.Unlock()
2016-11-21 20:26:47 -08:00
2016-10-28 14:50:46 -07:00
if af.file == nil {
err := af.openFile()
if err != nil {
if err == os.ErrNotExist {
return 0, nil
}
return -1, err
2016-10-28 14:50:46 -07:00
}
}
2016-10-26 16:23:19 -07:00
stat, err := af.file.Stat()
if err != nil {
return -1, err
}
return stat.Size(), nil
}