forked from elastic/go-txfile
-
Notifications
You must be signed in to change notification settings - Fork 0
/
write.go
322 lines (263 loc) · 6.92 KB
/
write.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
// Licensed to Elasticsearch B.V. under one or more contributor
// license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright
// ownership. Elasticsearch B.V. licenses this file to you under
// the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package txfile
import (
"io"
"sort"
"sync"
"github.com/elastic/go-txfile/internal/vfs"
)
type writer struct {
target writable
pageSize uint
mux sync.Mutex
cond *sync.Cond
done bool
scheduled []writeMsg
scheduled0 [64]writeMsg
fsync []syncMsg
fsync0 [8]syncMsg
syncMode SyncMode
pending int // number of scheduled writes since last sync
published int // number of writes executed since last sync
}
type writeMsg struct {
sync *txWriteSync
id PageID
buf []byte
fsync bool
}
type syncMsg struct {
sync *txWriteSync
count int // number of pages to process, before fsyncing
flags syncFlag
}
type txWriteSync struct {
err reason
wg sync.WaitGroup
}
type writable interface {
io.WriterAt
Sync(vfs.SyncFlag) error
}
// command as is consumer by the writers run loop
type command struct {
n int // number of buffered write message to be consumed
fsync *txWriteSync // set if fsync is to be executed after writing all messages
syncFlags syncFlag // additional fsync flags
}
type syncFlag uint8
const (
// On IO error, the writer will ignore any write/sync attempts, but return
// the first error encountered.
// Passing the syncResetErr notifies the writer that the current transaction
// is about to fail and all subsequent writes will belong to a new
// transaction. So to not stall any writes/operations forever, the writer
// will attempt write/sync any future requests, by resetting the internal
// error state to 'no error'.
syncResetErr syncFlag = 1 << iota
// syncDataOnly tells the writer that we don't care about metadata updates like
// access/modification timestamps (given the file size didn't change).
// Some filesystems profit from data only syncs, as meta data or journals
// don't need to be flushed, reducing the overall amount of on disk IO ops.
syncDataOnly
)
func (w *writer) Init(target writable, pageSize uint, syncMode SyncMode) {
if syncMode == SyncDefault {
syncMode = SyncData
}
w.target = target
w.syncMode = syncMode
w.pageSize = pageSize
w.cond = sync.NewCond(&w.mux)
w.scheduled = w.scheduled0[:0]
w.fsync = w.fsync[:0]
}
func (w *writer) Stop() {
w.mux.Lock()
w.done = true
w.mux.Unlock()
w.cond.Signal()
}
func (w *writer) Schedule(sync *txWriteSync, id PageID, buf []byte) {
sync.Retain()
traceln("schedule write")
w.mux.Lock()
defer w.mux.Unlock()
w.scheduled = append(w.scheduled, writeMsg{
sync: sync,
id: id,
buf: buf,
})
w.pending++
w.cond.Signal()
}
func (w *writer) Sync(sync *txWriteSync, flags syncFlag) {
sync.Retain()
traceln("schedule sync")
w.mux.Lock()
defer w.mux.Unlock()
w.fsync = append(w.fsync, syncMsg{
sync: sync,
count: w.pending,
flags: flags,
})
w.pending = 0
w.cond.Signal()
}
func (w *writer) Run() (bool, reason) {
var (
err reason
done bool
cmd command
buf [1024]writeMsg
)
for {
cmd, done = w.nextCommand(buf[:])
if done {
return done, nil
}
traceln("writer message: ", cmd.n, cmd.fsync != nil, done)
// TODO: use vector IO if possible (linux: pwritev)
msgs := buf[:cmd.n]
sort.Slice(msgs, func(i, j int) bool {
return msgs[i].id < msgs[j].id
})
for _, msg := range msgs {
const op = "txfile/write-page"
if err == nil {
// execute actual write on the page it's file offset:
off := uint64(msg.id) * uint64(w.pageSize)
tracef("write at(id=%v, off=%v, len=%v)\n", msg.id, off, len(msg.buf))
err = writeAt(op, w.target, msg.buf, int64(off))
}
msg.sync.err = err
msg.sync.Release()
}
// execute pending fsync:
if fsync := cmd.fsync; fsync != nil {
if err == nil {
err = w.execSync(cmd)
}
fsync.err = err
traceln("done fsync")
fsync.Release()
resetErr := cmd.syncFlags.Test(syncResetErr)
if resetErr {
err = nil
}
}
}
}
func (w *writer) execSync(cmd command) reason {
const op = "txfile/write-sync"
syncFlag := vfs.SyncAll
switch w.syncMode {
case SyncNone:
return nil
case SyncData:
if cmd.syncFlags.Test(syncDataOnly) {
syncFlag = vfs.SyncDataOnly
}
}
if err := w.target.Sync(syncFlag); err != nil {
return errOp(op).causedBy(err)
}
return nil
}
func (w *writer) nextCommand(buf []writeMsg) (command, bool) {
w.mux.Lock()
defer w.mux.Unlock()
traceln("async writer: wait next command")
defer traceln("async writer: received next command")
for {
if w.done {
return command{}, true
}
max := len(w.scheduled)
if max == 0 && len(w.fsync) == 0 { // no messages
w.cond.Wait()
continue
}
if l := len(buf); l < max {
max = l
}
// Check if we need to fsync and adjust `max` number of pages of required.
var sync *txWriteSync
var syncFlags syncFlag
traceln("check fsync: ", len(w.fsync))
if len(w.fsync) > 0 {
msg := w.fsync[0]
// number of outstanding scheduled writes before fsync
outstanding := msg.count - w.published
traceln("outstanding:", outstanding)
if outstanding <= max { // -> fsync
max, sync, syncFlags = outstanding, msg.sync, msg.flags
// advance fsync state
w.fsync[0] = syncMsg{} // clear entry, so to potentially clean references from w.fsync0
w.fsync = w.fsync[1:]
if len(w.fsync) == 0 {
w.fsync = w.fsync0[:0]
}
}
}
// return buffers to be processed
var n int
scheduled := w.scheduled[:max]
if len(scheduled) > 0 {
n = copy(buf, scheduled)
w.scheduled = w.scheduled[n:]
if len(w.scheduled) == 0 {
w.scheduled = w.scheduled0[:0]
}
}
if sync == nil {
w.published += n
} else {
w.published = 0
}
return command{n: n, fsync: sync, syncFlags: syncFlags}, false
}
}
func newTxWriteSync() *txWriteSync {
return &txWriteSync{}
}
func (s *txWriteSync) Retain() {
s.wg.Add(1)
}
func (s *txWriteSync) Release() {
s.wg.Done()
}
func (s *txWriteSync) Wait() reason {
s.wg.Wait()
return s.err
}
func writeAt(op string, out io.WriterAt, buf []byte, off int64) reason {
for len(buf) > 0 {
n, err := out.WriteAt(buf, off)
if err != nil {
return errOp(op).causedBy(err).
reportf("writing %v bytes to off=%v failed", len(buf), off)
}
off += int64(n)
buf = buf[n:]
}
return nil
}
func (f syncFlag) Test(other syncFlag) bool {
return (f & other) == other
}