-
Notifications
You must be signed in to change notification settings - Fork 33
/
write.go
387 lines (335 loc) · 11.6 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
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
package labelmap
import (
"fmt"
"sync"
"github.com/janelia-flyem/dvid/datastore"
"github.com/janelia-flyem/dvid/datatype/common/downres"
"github.com/janelia-flyem/dvid/datatype/common/labels"
"github.com/janelia-flyem/dvid/datatype/imageblk"
"github.com/janelia-flyem/dvid/dvid"
"github.com/janelia-flyem/dvid/server"
"github.com/janelia-flyem/dvid/storage"
)
type putOperation struct {
data []byte // the full label volume sent to PUT
scale uint8
subvol *dvid.Subvolume
indexZYX dvid.IndexZYX
version dvid.VersionID
mutate bool // if false, we just ingest without needing to GET previous value
mutID uint64 // should be unique within a server's uptime.
downresMut *downres.Mutation
blockCh chan blockChange
}
// PutLabels persists voxels from a subvolume into the storage engine. This involves transforming
// a supplied volume of uint64 with known geometry into many labels.Block that tiles the subvolume.
// Messages are sent to subscribers for ingest events.
func (d *Data) PutLabels(v dvid.VersionID, subvol *dvid.Subvolume, data []byte, roiname dvid.InstanceName, mutate bool) error {
if subvol.DataShape().ShapeDimensions() != 3 {
return fmt.Errorf("cannot store labels for data %q in non 3D format", d.DataName())
}
// Make sure data is block-aligned
if !dvid.BlockAligned(subvol, d.BlockSize()) {
return fmt.Errorf("cannot store labels for data %q in non-block aligned geometry %s -> %s", d.DataName(), subvol.StartPoint(), subvol.EndPoint())
}
// Make sure the received data buffer is of appropriate size.
labelBytes := subvol.Size().Prod() * 8
if labelBytes != int64(len(data)) {
return fmt.Errorf("expected %d bytes for data %q label PUT but only received %d bytes", labelBytes, d.DataName(), len(data))
}
r, err := imageblk.GetROI(v, roiname, subvol)
if err != nil {
return err
}
// Only do voxel-based mutations one at a time. This lets us remove handling for block-level concurrency.
d.voxelMu.Lock()
defer d.voxelMu.Unlock()
// Keep track of changing extents, labels and mark repo as dirty if changed.
var extentChanged bool
defer func() {
if extentChanged {
err := datastore.SaveDataByVersion(v, d)
if err != nil {
dvid.Infof("Error in trying to save repo on change: %v\n", err)
}
}
}()
// Track point extents
ctx := datastore.NewVersionedCtx(d, v)
extents := d.Extents()
if extents.AdjustPoints(subvol.StartPoint(), subvol.EndPoint()) {
extentChanged = true
if err := d.PostExtents(ctx, extents.MinPoint, extents.MaxPoint); err != nil {
return err
}
}
// extract buffer interface if it exists
var putbuffer storage.RequestBuffer
store, err := datastore.GetOrderedKeyValueDB(d)
if err != nil {
return fmt.Errorf("Data type imageblk had error initializing store: %v\n", err)
}
if req, ok := store.(storage.KeyValueRequester); ok {
putbuffer = req.NewBuffer(ctx)
}
// Iterate through index space for this data.
mutID := d.NewMutationID()
downresMut := downres.NewMutation(d, v, mutID)
wg := new(sync.WaitGroup)
blockCh := make(chan blockChange, 100)
svmap, err := getMapping(d, v)
if err != nil {
return fmt.Errorf("PutLabels couldn't get mapping for data %q, version %d: %v", d.DataName(), v, err)
}
go d.aggregateBlockChanges(v, svmap, blockCh)
blocks := 0
for it, err := subvol.NewIndexZYXIterator(d.BlockSize()); err == nil && it.Valid(); it.NextSpan() {
i0, i1, err := it.IndexSpan()
if err != nil {
close(blockCh)
return err
}
ptBeg := i0.Duplicate().(dvid.ChunkIndexer)
ptEnd := i1.Duplicate().(dvid.ChunkIndexer)
begX := ptBeg.Value(0)
endX := ptEnd.Value(0)
if extents.AdjustIndices(ptBeg, ptEnd) {
extentChanged = true
}
wg.Add(int(endX-begX) + 1)
c := dvid.ChunkPoint3d{begX, ptBeg.Value(1), ptBeg.Value(2)}
for x := begX; x <= endX; x++ {
c[0] = x
curIndex := dvid.IndexZYX(c)
// Don't PUT if this index is outside a specified ROI
if r != nil && r.Iter != nil && !r.Iter.InsideFast(curIndex) {
wg.Done()
continue
}
putOp := &putOperation{
data: data,
subvol: subvol,
indexZYX: curIndex,
version: v,
mutate: mutate,
mutID: mutID,
downresMut: downresMut,
blockCh: blockCh,
}
<-server.HandlerToken
go d.putChunk(putOp, wg, putbuffer)
blocks++
}
}
wg.Wait()
close(blockCh)
// if a bufferable op, flush
if putbuffer != nil {
putbuffer.Flush()
}
return downresMut.Execute()
}
// Puts a chunk of data as part of a mapped operation.
// Only some multiple of the # of CPU cores can be used for chunk handling before
// it waits for chunk processing to abate via the buffered server.HandlerToken channel.
func (d *Data) putChunk(op *putOperation, wg *sync.WaitGroup, putbuffer storage.RequestBuffer) {
defer func() {
// After processing a chunk, return the token.
server.HandlerToken <- 1
// Notify the requestor that this chunk is done.
wg.Done()
}()
bcoord := op.indexZYX.ToIZYXString()
ctx := datastore.NewVersionedCtx(d, op.version)
// If we are mutating, get the previous label Block
var scale uint8
var oldBlock *labels.PositionedBlock
if op.mutate {
var err error
if oldBlock, err = d.getLabelBlock(ctx, scale, bcoord); err != nil {
dvid.Errorf("Unable to load previous block in %q, key %v: %v\n", d.DataName(), bcoord, err)
return
}
}
// Get the current label Block from the received label array
blockSize, ok := d.BlockSize().(dvid.Point3d)
if !ok {
dvid.Errorf("can't putChunk() on data %q with non-3d block size: %s", d.DataName(), d.BlockSize())
return
}
curBlock, err := labels.SubvolumeToBlock(op.subvol, op.data, op.indexZYX, blockSize)
if err != nil {
dvid.Errorf("error creating compressed block from label array at %s", op.subvol)
return
}
go d.updateBlockMaxLabel(op.version, curBlock)
blockData, _ := curBlock.MarshalBinary()
serialization, err := dvid.SerializeData(blockData, d.Compression(), d.Checksum())
if err != nil {
dvid.Errorf("Unable to serialize block in %q: %v\n", d.DataName(), err)
return
}
store, err := datastore.GetOrderedKeyValueDB(d)
if err != nil {
dvid.Errorf("Data type imageblk had error initializing store: %v\n", err)
return
}
callback := func(ready chan error) {
if ready != nil {
if resperr := <-ready; resperr != nil {
dvid.Errorf("Unable to PUT voxel data for block %v: %v\n", bcoord, resperr)
return
}
}
var event string
var delta interface{}
if oldBlock != nil && op.mutate {
event = labels.MutateBlockEvent
block := MutatedBlock{op.mutID, bcoord, &(oldBlock.Block), curBlock}
d.handleBlockMutate(op.version, op.blockCh, block)
delta = block
} else {
event = labels.IngestBlockEvent
block := IngestedBlock{op.mutID, bcoord, curBlock}
d.handleBlockIndexing(op.version, op.blockCh, block)
delta = block
}
if err := op.downresMut.BlockMutated(bcoord, curBlock); err != nil {
dvid.Errorf("data %q publishing downres: %v\n", d.DataName(), err)
}
evt := datastore.SyncEvent{d.DataUUID(), event}
msg := datastore.SyncMessage{event, op.version, delta}
if err := datastore.NotifySubscribers(evt, msg); err != nil {
dvid.Errorf("Unable to notify subscribers of event %s in %s\n", event, d.DataName())
}
}
// put data -- use buffer if available
tk := NewBlockTKeyByCoord(op.scale, bcoord)
if putbuffer != nil {
ready := make(chan error, 1)
go callback(ready)
putbuffer.PutCallback(ctx, tk, serialization, ready)
} else {
if err := store.Put(ctx, tk, serialization); err != nil {
dvid.Errorf("Unable to PUT voxel data for block %s: %v\n", bcoord, err)
return
}
callback(nil)
}
}
// Writes a XY image into the blocks that intersect it. This function assumes the
// blocks have been allocated and if necessary, filled with old data.
func (d *Data) writeXYImage(v dvid.VersionID, vox *imageblk.Voxels, b storage.TKeyValues) (extentChanged bool, err error) {
// Setup concurrency in image -> block transfers.
var wg sync.WaitGroup
defer wg.Wait()
// Iterate through index space for this data using ZYX ordering.
blockSize := d.BlockSize()
var startingBlock int32
for it, err := vox.NewIndexIterator(blockSize); err == nil && it.Valid(); it.NextSpan() {
indexBeg, indexEnd, err := it.IndexSpan()
if err != nil {
return extentChanged, err
}
ptBeg := indexBeg.Duplicate().(dvid.ChunkIndexer)
ptEnd := indexEnd.Duplicate().(dvid.ChunkIndexer)
// Track point extents
if d.Extents().AdjustIndices(ptBeg, ptEnd) {
extentChanged = true
}
// Do image -> block transfers in concurrent goroutines.
begX := ptBeg.Value(0)
endX := ptEnd.Value(0)
<-server.HandlerToken
wg.Add(1)
go func(blockNum int32) {
c := dvid.ChunkPoint3d{begX, ptBeg.Value(1), ptBeg.Value(2)}
for x := begX; x <= endX; x++ {
c[0] = x
curIndex := dvid.IndexZYX(c)
b[blockNum].K = NewBlockTKey(0, &curIndex)
// Write this slice data into the block.
vox.WriteBlock(&(b[blockNum]), blockSize)
blockNum++
}
server.HandlerToken <- 1
wg.Done()
}(startingBlock)
startingBlock += (endX - begX + 1)
}
return
}
// KVWriteSize is the # of key-value pairs we will write as one atomic batch write.
const KVWriteSize = 500
// TODO -- Clean up all the writing and simplify now that we have block-aligned writes.
// writeBlocks ingests blocks of voxel data asynchronously using batch writes.
func (d *Data) writeBlocks(v dvid.VersionID, b storage.TKeyValues, wg1, wg2 *sync.WaitGroup) error {
batcher, err := datastore.GetKeyValueBatcher(d)
if err != nil {
return err
}
preCompress, postCompress := 0, 0
blockSize := d.BlockSize().(dvid.Point3d)
ctx := datastore.NewVersionedCtx(d, v)
evt := datastore.SyncEvent{d.DataUUID(), labels.IngestBlockEvent}
<-server.HandlerToken
blockCh := make(chan blockChange, 100)
svmap, err := getMapping(d, v)
if err != nil {
return fmt.Errorf("writeBlocks couldn't get mapping for data %q, version %d: %v", d.DataName(), v, err)
}
go d.aggregateBlockChanges(v, svmap, blockCh)
go func() {
defer func() {
wg1.Done()
wg2.Done()
dvid.Debugf("Wrote voxel blocks. Before %s: %d bytes. After: %d bytes\n", d.Compression(), preCompress, postCompress)
close(blockCh)
server.HandlerToken <- 1
}()
mutID := d.NewMutationID()
batch := batcher.NewBatch(ctx)
for i, block := range b {
preCompress += len(block.V)
lblBlock, err := labels.MakeBlock(block.V, blockSize)
if err != nil {
dvid.Errorf("unable to compute dvid block compression in %q: %v\n", d.DataName(), err)
return
}
go d.updateBlockMaxLabel(v, lblBlock)
compressed, _ := lblBlock.MarshalBinary()
serialization, err := dvid.SerializeData(compressed, d.Compression(), d.Checksum())
if err != nil {
dvid.Errorf("Unable to serialize block in %q: %v\n", d.DataName(), err)
return
}
postCompress += len(serialization)
batch.Put(block.K, serialization)
_, indexZYX, err := DecodeBlockTKey(block.K)
if err != nil {
dvid.Errorf("Unable to recover index from block key: %v\n", block.K)
return
}
block := IngestedBlock{mutID, indexZYX.ToIZYXString(), lblBlock}
d.handleBlockIndexing(v, blockCh, block)
msg := datastore.SyncMessage{labels.IngestBlockEvent, v, block}
if err := datastore.NotifySubscribers(evt, msg); err != nil {
dvid.Errorf("Unable to notify subscribers of ChangeBlockEvent in %s\n", d.DataName())
return
}
// Check if we should commit
if i%KVWriteSize == KVWriteSize-1 {
if err := batch.Commit(); err != nil {
dvid.Errorf("Error on trying to write batch: %v\n", err)
return
}
batch = batcher.NewBatch(ctx)
}
}
if err := batch.Commit(); err != nil {
dvid.Errorf("Error on trying to write batch: %v\n", err)
return
}
}()
return nil
}