forked from hashicorp/vault
-
Notifications
You must be signed in to change notification settings - Fork 2
/
wal.go
100 lines (86 loc) · 2.41 KB
/
wal.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
package framework
import (
"encoding/json"
"strings"
"time"
"github.com/hashicorp/go-uuid"
"github.com/hashicorp/vault/helper/jsonutil"
"github.com/hashicorp/vault/logical"
)
// WALPrefix is the prefix within Storage where WAL entries will be written.
const WALPrefix = "wal/"
type WALEntry struct {
ID string `json:"-"`
Kind string `json:"type"`
Data interface{} `json:"data"`
CreatedAt int64 `json:"created_at"`
}
// PutWAL writes some data to the WAL.
//
// The kind parameter is used by the framework to allow users to store
// multiple kinds of WAL data and to easily disambiguate what data they're
// expecting.
//
// Data within the WAL that is uncommitted (CommitWAL hasn't be called)
// will be given to the rollback callback when an rollback operation is
// received, allowing the backend to clean up some partial states.
//
// The data must be JSON encodable.
//
// This returns a unique ID that can be used to reference this WAL data.
// WAL data cannot be modified. You can only add to the WAL and commit existing
// WAL entries.
func PutWAL(s logical.Storage, kind string, data interface{}) (string, error) {
value, err := json.Marshal(&WALEntry{
Kind: kind,
Data: data,
CreatedAt: time.Now().UTC().Unix(),
})
if err != nil {
return "", err
}
id, err := uuid.GenerateUUID()
if err != nil {
return "", err
}
return id, s.Put(&logical.StorageEntry{
Key: WALPrefix + id,
Value: value,
})
}
// GetWAL reads a specific entry from the WAL. If the entry doesn't exist,
// then nil value is returned.
//
// The kind, value, and error are returned.
func GetWAL(s logical.Storage, id string) (*WALEntry, error) {
entry, err := s.Get(WALPrefix + id)
if err != nil {
return nil, err
}
if entry == nil {
return nil, nil
}
var raw WALEntry
if err := jsonutil.DecodeJSON(entry.Value, &raw); err != nil {
return nil, err
}
raw.ID = id
return &raw, nil
}
// DeleteWAL commits the WAL entry with the given ID. Once committed,
// it is assumed that the operation was a success and doesn't need to
// be rolled back.
func DeleteWAL(s logical.Storage, id string) error {
return s.Delete(WALPrefix + id)
}
// ListWAL lists all the entries in the WAL.
func ListWAL(s logical.Storage) ([]string, error) {
keys, err := s.List(WALPrefix)
if err != nil {
return nil, err
}
for i, k := range keys {
keys[i] = strings.TrimPrefix(k, WALPrefix)
}
return keys, nil
}