-
Notifications
You must be signed in to change notification settings - Fork 0
/
env.go
496 lines (440 loc) · 10.2 KB
/
env.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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
package ssdb
import (
"io"
"log"
"os"
"path"
"runtime"
"ssdb/util"
"strings"
"sync"
"sync/atomic"
"syscall"
"time"
"unsafe"
)
type Env interface {
NewSequentialFile(name string) (SequentialFile, error)
NewRandomAccessFile(name string) (RandomAccessFile, error)
NewWritableFile(name string) (WritableFile, error)
NewAppendableFile(name string) (WritableFile, error)
FileExists(name string) bool
GetChildren(dir string) ([]string, error)
DeleteFile(name string) error
CreateDir(name string) error
DeleteDir(name string) error
GetFileSize(name string) (int, error)
RenameFile(from, to string) error
LockFile(name string) (FileLock, error)
UnlockFile(lock FileLock) error
Schedule(function func(interface{}), arg interface{})
StartThread(function func(interface{}), arg interface{})
GetTestDirectory() (string, error)
NewLogger(name string) (*log.Logger, func(), error)
NowMicros() uint64
SleepForMicroseconds(micros int)
}
type SequentialFile interface {
// Read up to "n" bytes from the file. "scratch[0..n-1]" may be
// written by this routine. Sets "*result" to the data that was
// read (including if fewer than "n" bytes were successfully read).
// May set "*result" to point at data in "scratch[0..n-1]", so
// "scratch[0..n-1]" must be live when "*result" is used.
// If an error was encountered, returns a non-OK status.
//
// REQUIRES: External synchronization
Read(b []byte) ([]byte, int, error)
Skip(n uint64) error
Closer
}
type RandomAccessFile interface {
// Read up to "n" bytes from the file starting at "offset".
// "scratch[0..n-1]" may be written by this routine. Sets "*result"
// to the data that was read (including if fewer than "n" bytes were
// successfully read). May set "*result" to point at data in
// "scratch[0..n-1]", so "scratch[0..n-1]" must be live when
// "*result" is used. If an error was encountered, returns a non-OK
// status.
//
// Safe for concurrent use by multiple threads.
Read(b []byte, offset int64) ([]byte, int, error)
Closer
}
type WritableFile interface {
Append(data []byte) error
Close() error
Flush() error
Sync() error
}
type FileLock interface {
}
func WriteStringToFile(env Env, data string, name string) error {
return doWriteBytesToFile(env, data, name, false)
}
func WriteStringToFileSync(env Env, data string, name string) error {
return doWriteBytesToFile(env, data, name, true)
}
func doWriteBytesToFile(env Env, data string, name string, shouldSync bool) error {
file, err := env.NewWritableFile(name)
if err != nil {
return err
}
err = file.Append([]byte(data))
if err == nil && shouldSync {
err = file.Sync()
}
if err == nil {
err = file.Close()
} else {
_ = file.Close()
}
if err != nil {
_ = env.DeleteFile(name)
}
return err
}
func ReadFileToString(env Env, name string) (string, error) {
file, err := env.NewSequentialFile(name)
if err != nil {
return "", err
}
const bufferSize = 8192
space := make([]byte, bufferSize)
var data strings.Builder
var r []byte
var n int
for {
r, n, err = file.Read(space)
if err != nil || n == 0 {
break
}
data.Write(r)
}
file.Close()
return data.String(), err
}
type EnvWrapper struct {
Env
}
func (w *EnvWrapper) Target() Env {
return w.Env
}
const (
writableFileBufferSize = 65536
)
var openReadOnlyFileLimit = -1
var defaultMmapLimit int
var mmapLimit int
type limiter struct {
acquiresAllowed int64
}
func newLimiter(maxAcquires int) limiter {
return limiter{acquiresAllowed: int64(maxAcquires)}
}
func (l *limiter) acquire() bool {
n := atomic.AddInt64(&l.acquiresAllowed, -1)
if n >= 0 {
return true
}
atomic.AddInt64(&l.acquiresAllowed, 1)
return false
}
func (l *limiter) release() {
atomic.AddInt64(&l.acquiresAllowed, 1)
}
type env struct {
bgStarted int32
workItemCh chan *backgroundWorkItem
stopped chan struct{}
wg sync.WaitGroup
mmapLimiter limiter
}
func (e *env) NewSequentialFile(name string) (SequentialFile, error) {
return newSequentialFile(name)
}
func (e *env) NewWritableFile(name string) (f WritableFile, err error) {
var file *os.File
if file, err = os.OpenFile(name, os.O_TRUNC|os.O_WRONLY|os.O_CREATE, 0644); err != nil {
err = envError(name, err)
return
}
f = newWritableFile(file)
return
}
func (e *env) NewAppendableFile(name string) (f WritableFile, err error) {
var file *os.File
if file, err = os.OpenFile(name, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0644); err != nil {
err = envError(name, err)
return
}
f = newWritableFile(file)
return
}
func (e *env) FileExists(name string) bool {
_, err := os.Stat(name)
return err == nil
}
func (e *env) GetChildren(dir string) (result []string, err error) {
var file *os.File
if file, err = os.Open(dir); err != nil {
err = envError(dir, err)
return
}
if result, err = file.Readdirnames(-1); err != nil {
err = envError(dir, err)
}
return
}
func (e *env) DeleteFile(name string) (err error) {
if err = os.Remove(name); err != nil {
err = envError(name, err)
}
return
}
func (e *env) CreateDir(name string) (err error) {
if err = os.Mkdir(name, 0755); err != nil {
err = envError(name, err)
}
return
}
func (e *env) DeleteDir(name string) (err error) {
if err = os.Remove(name); err != nil {
err = envError(name, err)
}
return
}
func (e *env) GetFileSize(name string) (size int, err error) {
var info os.FileInfo
if info, err = os.Stat(name); err != nil {
err = envError(name, err)
return
}
size = int(info.Size())
return
}
func (e *env) RenameFile(from, to string) (err error) {
if err = os.Rename(from, to); err != nil {
err = envError(from, err)
}
return
}
func (e *env) Schedule(function func(interface{}), arg interface{}) {
if atomic.CompareAndSwapInt32(&e.bgStarted, 0, 1) {
go e.backgroundRoutine()
runtime.SetFinalizer(e, func(e *env) {
e.stopped <- struct{}{}
e.wg.Wait()
})
}
i := &backgroundWorkItem{
function: function,
arg: arg,
}
e.workItemCh <- i
}
func (e *env) backgroundRoutine() {
e.wg.Add(1)
defer e.wg.Done()
for {
select {
case <-e.stopped:
return
case i := <-e.workItemCh:
i.function(i.arg)
}
}
}
func (e *env) StartThread(function func(interface{}), arg interface{}) {
go function(arg)
}
func (e *env) NewLogger(name string) (l *log.Logger, close func(), err error) {
var f *os.File
if f, err = os.OpenFile(name, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0644); err != nil {
close = func() {}
return
}
l = log.New(f, "", log.LstdFlags)
close = func() {
_ = f.Close()
}
return
}
func (e *env) NowMicros() uint64 {
return uint64(time.Now().UnixNano() / int64(time.Microsecond/time.Nanosecond))
}
func (e *env) SleepForMicroseconds(micros int) {
time.Sleep(time.Microsecond * time.Duration(micros))
}
type backgroundWorkItem struct {
function func(interface{})
arg interface{}
}
var e Env
var once sync.Once
func init() {
if unsafe.Sizeof(uintptr(0)) >= 8 {
defaultMmapLimit = 1000
} else {
defaultMmapLimit = 0
}
mmapLimit = defaultMmapLimit
}
func maxMmap() int {
return mmapLimit
}
type sequentialFile struct {
filename string
file *os.File
}
func (f *sequentialFile) Read(b []byte) (result []byte, n int, err error) {
for {
n, err = f.file.Read(b)
if n < 0 {
if err == syscall.EINTR {
continue
}
err = envError(f.filename, err)
break
}
result = b[:n]
break
}
if n == 0 && err == io.EOF {
err = nil
}
return
}
func (f *sequentialFile) Skip(n uint64) error {
if ret, err := f.file.Seek(int64(n), io.SeekCurrent); err != nil {
return envError(f.filename, err)
} else if ret == -1 {
return envError(f.filename, nil)
}
return nil
}
func (f *sequentialFile) Close() {
_ = f.file.Close()
}
func envError(filename string, err error) error {
if err == nil {
return util.IOError1(filename)
} else if os.IsNotExist(err) {
return util.NotFoundError2(filename, err.Error())
} else {
return util.IOError2(filename, err.Error())
}
}
func newSequentialFile(filename string) (SequentialFile, error) {
file, err := os.OpenFile(filename, os.O_RDONLY, 0)
if err != nil {
return nil, envError(filename, err)
}
f := &sequentialFile{
filename: filename,
file: file,
}
return f, nil
}
func isManifest(filename string) bool {
return strings.HasPrefix(path.Base(filename), "MANIFEST")
}
type writableFile struct {
buf [writableFileBufferSize]byte
pos int
file *os.File
isManifest bool
filename string
dirname string
}
func newWritableFile(file *os.File) *writableFile {
filename := file.Name()
f := &writableFile{
buf: [65536]byte{},
pos: 0,
file: file,
isManifest: isManifest(filename),
filename: filename,
dirname: path.Dir(filename),
}
return f
}
func (f *writableFile) Append(data []byte) (err error) {
writeSize := len(data)
copySize := writableFileBufferSize - f.pos
if copySize > writeSize {
copySize = writeSize
}
copy(f.buf[f.pos:], data[:copySize])
writeSize -= copySize
f.pos += copySize
if writeSize == 0 {
return
}
if err = f.flushBuffer(); err != nil {
return
}
if writeSize < writableFileBufferSize {
copy(f.buf[:], data[copySize:])
f.pos = writeSize
return
}
err = f.writeUnbuffered(data[copySize:])
return
}
func (f *writableFile) Close() (err error) {
if f.file != nil {
err = f.flushBuffer()
if e := f.file.Close(); e != nil && err == nil {
err = envError(f.filename, e)
}
f.file = nil
}
return
}
func (f *writableFile) Flush() error {
return f.flushBuffer()
}
//func (f *writableFile) Finalize() {
// if f.file != nil {
// _ = f.Close()
// }
//}
func (f *writableFile) flushBuffer() error {
err := f.writeUnbuffered(f.buf[:f.pos])
f.pos = 0
return err
}
func (f *writableFile) writeUnbuffered(data []byte) error {
size := len(data)
start := 0
for size > 0 {
n, err := f.file.Write(data[start:])
if n <= 0 {
if err == syscall.EINTR {
continue
}
return envError(f.filename, err)
}
start += n
size -= n
}
return nil
}
func (f *writableFile) syncDirIfManifest() error {
if !f.isManifest {
return nil
}
file, err := os.OpenFile(f.dirname, os.O_RDONLY, 0)
if err != nil {
return envError(f.filename, err)
}
defer file.Close()
return syncFD(file, f.dirname)
}
func syncFD(file *os.File, path string) (err error) {
//todo: call fdatasync
if err = file.Sync(); err != nil {
err = envError(path, err)
}
return
}