containerd/journal.go

62 lines
986 B
Go
Raw Normal View History

2015-11-10 22:24:34 +00:00
package containerd
import (
"encoding/json"
"os"
"path/filepath"
"sync"
2015-11-13 22:09:35 +00:00
"github.com/Sirupsen/logrus"
2015-11-10 22:24:34 +00:00
)
type entry struct {
Event *Event `json:"event"`
}
func newJournal(path string) (*journal, error) {
if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
return nil, err
}
f, err := os.OpenFile(path, os.O_CREATE|os.O_RDWR|os.O_APPEND, 0755)
if err != nil {
return nil, err
}
2015-11-13 22:09:35 +00:00
j := &journal{
2015-11-10 22:24:34 +00:00
f: f,
enc: json.NewEncoder(f),
2015-11-13 22:09:35 +00:00
wc: make(chan *Event, 2048),
}
j.wg.Add(1)
2015-11-13 22:09:35 +00:00
go j.start()
return j, nil
2015-11-10 22:24:34 +00:00
}
type journal struct {
f *os.File
enc *json.Encoder
2015-11-13 22:09:35 +00:00
wc chan *Event
wg sync.WaitGroup
2015-11-10 22:24:34 +00:00
}
2015-11-13 22:09:35 +00:00
func (j *journal) start() {
defer j.wg.Done()
2015-11-13 22:09:35 +00:00
for e := range j.wc {
et := &entry{
Event: e,
}
if err := j.enc.Encode(et); err != nil {
logrus.WithField("error", err).Error("write event to journal")
}
2015-11-10 22:24:34 +00:00
}
2015-11-13 22:09:35 +00:00
}
func (j *journal) write(e *Event) {
j.wc <- e
2015-11-10 22:24:34 +00:00
}
func (j *journal) Close() error {
2015-11-13 22:09:35 +00:00
close(j.wc)
j.wg.Wait()
2015-11-10 22:24:34 +00:00
return j.f.Close()
}