1package engine
2
3import (
4	"bytes"
5	"os"
6	"path/filepath"
7
8	"github.com/rogpeppe/go-internal/lockedfile"
9)
10
11// KVStore is a simple, atomic key-value store. The user of
12// probe-engine should supply an implementation of this interface,
13// which will be used by probe-engine to store specific data.
14type KVStore interface {
15	Get(key string) (value []byte, err error)
16	Set(key string, value []byte) (err error)
17}
18
19// FileSystemKVStore is a directory based KVStore
20type FileSystemKVStore struct {
21	basedir string
22}
23
24// NewFileSystemKVStore creates a new FileSystemKVStore.
25func NewFileSystemKVStore(basedir string) (kvs *FileSystemKVStore, err error) {
26	if err = os.MkdirAll(basedir, 0700); err == nil {
27		kvs = &FileSystemKVStore{basedir: basedir}
28	}
29	return
30}
31
32func (kvs *FileSystemKVStore) filename(key string) string {
33	return filepath.Join(kvs.basedir, key)
34}
35
36// Get returns the specified key's value
37func (kvs *FileSystemKVStore) Get(key string) ([]byte, error) {
38	return lockedfile.Read(kvs.filename(key))
39}
40
41// Set sets the value of a specific key
42func (kvs *FileSystemKVStore) Set(key string, value []byte) error {
43	return lockedfile.Write(kvs.filename(key), bytes.NewReader(value), 0600)
44}
45