2019-01-24 20:15:10 +00:00
|
|
|
// Copyright (C) 2019 Storj Labs, Inc.
|
2018-12-11 18:24:31 +00:00
|
|
|
// See LICENSE for copying information.
|
|
|
|
|
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bufio"
|
|
|
|
"encoding/gob"
|
|
|
|
"io"
|
|
|
|
"os"
|
|
|
|
"sync"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
|
|
|
// FileSource reads packets from a file
|
|
|
|
type FileSource struct {
|
2019-01-01 09:41:27 +00:00
|
|
|
path string
|
|
|
|
|
|
|
|
mu sync.Mutex
|
2018-12-11 18:24:31 +00:00
|
|
|
decoder *gob.Decoder
|
|
|
|
}
|
|
|
|
|
|
|
|
// NewFileSource creates a FileSource
|
|
|
|
func NewFileSource(path string) *FileSource {
|
|
|
|
return &FileSource{path: path}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Next implements the Source interface
|
|
|
|
func (f *FileSource) Next() ([]byte, time.Time, error) {
|
2019-01-01 09:41:27 +00:00
|
|
|
f.mu.Lock()
|
|
|
|
defer f.mu.Unlock()
|
2018-12-11 18:24:31 +00:00
|
|
|
if f.decoder == nil {
|
2019-01-01 09:41:27 +00:00
|
|
|
file, err := os.Open(f.path)
|
2018-12-11 18:24:31 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, time.Time{}, err
|
|
|
|
}
|
2019-01-01 09:41:27 +00:00
|
|
|
f.decoder = gob.NewDecoder(bufio.NewReader(file))
|
2018-12-11 18:24:31 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
var p Packet
|
|
|
|
err := f.decoder.Decode(&p)
|
|
|
|
if err != nil {
|
|
|
|
return nil, time.Time{}, err
|
|
|
|
}
|
|
|
|
return p.Data, p.TS, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// FileDest sends packets to a file for later processing. FileDest preserves
|
|
|
|
// the timestamps.
|
|
|
|
type FileDest struct {
|
2019-01-01 09:41:27 +00:00
|
|
|
path string
|
|
|
|
|
|
|
|
mu sync.Mutex
|
|
|
|
file io.Closer
|
2018-12-11 18:24:31 +00:00
|
|
|
encoder *gob.Encoder
|
|
|
|
}
|
|
|
|
|
|
|
|
// NewFileDest creates a FileDest
|
|
|
|
func NewFileDest(path string) *FileDest {
|
|
|
|
return &FileDest{path: path}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Packet implements PacketDest
|
|
|
|
func (f *FileDest) Packet(data []byte, ts time.Time) error {
|
2019-01-01 09:41:27 +00:00
|
|
|
f.mu.Lock()
|
|
|
|
defer f.mu.Unlock()
|
2018-12-11 18:24:31 +00:00
|
|
|
|
|
|
|
if f.encoder == nil {
|
2019-01-01 09:41:27 +00:00
|
|
|
file, err := os.Create(f.path)
|
2018-12-11 18:24:31 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2019-01-01 09:41:27 +00:00
|
|
|
f.file = file
|
|
|
|
f.encoder = gob.NewEncoder(bufio.NewWriter(file))
|
2018-12-11 18:24:31 +00:00
|
|
|
}
|
2019-01-01 09:41:27 +00:00
|
|
|
|
2018-12-11 18:24:31 +00:00
|
|
|
return f.encoder.Encode(Packet{Data: data, TS: ts})
|
|
|
|
}
|