-
Notifications
You must be signed in to change notification settings - Fork 534
/
filestore.go
266 lines (238 loc) · 6.46 KB
/
filestore.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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
/*
* Copyright (c) 2021 IBM Corp and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v2.0
* and Eclipse Distribution License v1.0 which accompany this distribution.
*
* The Eclipse Public License is available at
* https://www.eclipse.org/legal/epl-2.0/
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Seth Hoenig
* Allan Stockdill-Mander
* Mike Robertson
*/
package mqtt
import (
"io/fs"
"os"
"path"
"sort"
"sync"
"github.com/eclipse/paho.mqtt.golang/packets"
)
const (
msgExt = ".msg"
tmpExt = ".tmp"
corruptExt = ".CORRUPT"
)
// FileStore implements the store interface using the filesystem to provide
// true persistence, even across client failure. This is designed to use a
// single directory per running client. If you are running multiple clients
// on the same filesystem, you will need to be careful to specify unique
// store directories for each.
type FileStore struct {
sync.RWMutex
directory string
opened bool
}
// NewFileStore will create a new FileStore which stores its messages in the
// directory provided.
func NewFileStore(directory string) *FileStore {
store := &FileStore{
directory: directory,
opened: false,
}
return store
}
// Open will allow the FileStore to be used.
func (store *FileStore) Open() {
store.Lock()
defer store.Unlock()
// if no store directory was specified in ClientOpts, by default use the
// current working directory
if store.directory == "" {
store.directory, _ = os.Getwd()
}
// if store dir exists, great, otherwise, create it
if !exists(store.directory) {
perms := os.FileMode(0770)
merr := os.MkdirAll(store.directory, perms)
chkerr(merr)
}
store.opened = true
DEBUG.Println(STR, "store is opened at", store.directory)
}
// Close will disallow the FileStore from being used.
func (store *FileStore) Close() {
store.Lock()
defer store.Unlock()
store.opened = false
DEBUG.Println(STR, "store is closed")
}
// Put will put a message into the store, associated with the provided
// key value.
func (store *FileStore) Put(key string, m packets.ControlPacket) {
store.Lock()
defer store.Unlock()
if !store.opened {
ERROR.Println(STR, "Trying to use file store, but not open")
return
}
full := fullpath(store.directory, key)
write(store.directory, key, m)
if !exists(full) {
ERROR.Println(STR, "file not created:", full)
}
}
// Get will retrieve a message from the store, the one associated with
// the provided key value.
func (store *FileStore) Get(key string) packets.ControlPacket {
store.RLock()
defer store.RUnlock()
if !store.opened {
ERROR.Println(STR, "trying to use file store, but not open")
return nil
}
filepath := fullpath(store.directory, key)
if !exists(filepath) {
return nil
}
mfile, oerr := os.Open(filepath)
chkerr(oerr)
msg, rerr := packets.ReadPacket(mfile)
chkerr(mfile.Close())
// Message was unreadable, return nil
if rerr != nil {
newpath := corruptpath(store.directory, key)
WARN.Println(STR, "corrupted file detected:", rerr.Error(), "archived at:", newpath)
if err := os.Rename(filepath, newpath); err != nil {
ERROR.Println(STR, err)
}
return nil
}
return msg
}
// All will provide a list of all of the keys associated with messages
// currently residing in the FileStore.
func (store *FileStore) All() []string {
store.RLock()
defer store.RUnlock()
return store.all()
}
// Del will remove the persisted message associated with the provided
// key from the FileStore.
func (store *FileStore) Del(key string) {
store.Lock()
defer store.Unlock()
store.del(key)
}
// Reset will remove all persisted messages from the FileStore.
func (store *FileStore) Reset() {
store.Lock()
defer store.Unlock()
WARN.Println(STR, "FileStore Reset")
for _, key := range store.all() {
store.del(key)
}
}
// lockless
func (store *FileStore) all() []string {
var err error
var keys []string
if !store.opened {
ERROR.Println(STR, "trying to use file store, but not open")
return nil
}
entries, err := os.ReadDir(store.directory)
chkerr(err)
files := make(fileInfos, 0, len(entries))
for _, entry := range entries {
info, err := entry.Info()
chkerr(err)
files = append(files, info)
}
sort.Sort(files)
for _, f := range files {
DEBUG.Println(STR, "file in All():", f.Name())
name := f.Name()
if len(name) < len(msgExt) || name[len(name)-len(msgExt):] != msgExt {
DEBUG.Println(STR, "skipping file, doesn't have right extension: ", name)
continue
}
key := name[0 : len(name)-4] // remove file extension
keys = append(keys, key)
}
return keys
}
// lockless
func (store *FileStore) del(key string) {
if !store.opened {
ERROR.Println(STR, "trying to use file store, but not open")
return
}
DEBUG.Println(STR, "store del filepath:", store.directory)
DEBUG.Println(STR, "store delete key:", key)
filepath := fullpath(store.directory, key)
DEBUG.Println(STR, "path of deletion:", filepath)
if !exists(filepath) {
WARN.Println(STR, "store could not delete key:", key)
return
}
rerr := os.Remove(filepath)
chkerr(rerr)
DEBUG.Println(STR, "del msg:", key)
if exists(filepath) {
ERROR.Println(STR, "file not deleted:", filepath)
}
}
func fullpath(store string, key string) string {
p := path.Join(store, key+msgExt)
return p
}
func tmppath(store string, key string) string {
p := path.Join(store, key+tmpExt)
return p
}
func corruptpath(store string, key string) string {
p := path.Join(store, key+corruptExt)
return p
}
// create file called "X.[messageid].tmp" located in the store
// the contents of the file is the bytes of the message, then
// rename it to "X.[messageid].msg", overwriting any existing
// message with the same id
// X will be 'i' for inbound messages, and O for outbound messages
func write(store, key string, m packets.ControlPacket) {
temppath := tmppath(store, key)
f, err := os.Create(temppath)
chkerr(err)
werr := m.Write(f)
chkerr(werr)
cerr := f.Close()
chkerr(cerr)
rerr := os.Rename(temppath, fullpath(store, key))
chkerr(rerr)
}
func exists(file string) bool {
if _, err := os.Stat(file); err != nil {
if os.IsNotExist(err) {
return false
}
chkerr(err)
}
return true
}
type fileInfos []fs.FileInfo
func (f fileInfos) Len() int {
return len(f)
}
func (f fileInfos) Swap(i, j int) {
f[i], f[j] = f[j], f[i]
}
func (f fileInfos) Less(i, j int) bool {
return f[i].ModTime().Before(f[j].ModTime())
}