File: mmap_test.go

package info (click to toggle)
golang-github-couchbase-moss 0.0~git20170914.0.07c86e8-4
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, buster, sid
  • size: 664 kB
  • sloc: python: 230; makefile: 37
file content (460 lines) | stat: -rw-r--r-- 9,336 bytes parent folder | download
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
//  Copyright (c) 2016 Couchbase, Inc.
//  Licensed 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 moss

import (
	"fmt"
	"io/ioutil"
	"os"
	"sync"
	"testing"
	"time"

	"github.com/edsrzf/mmap-go"
)

func TestMultipleMMapsOnSameFile(t *testing.T) {
	tmpDir, _ := ioutil.TempDir("", "mossMMap")
	defer os.RemoveAll(tmpDir)

	f, err := os.Create(tmpDir + string(os.PathSeparator) + "test.file")
	if err != nil {
		t.Errorf("expected open file to work, err: %v", err)
	}

	offset := 1024 * 1024 * 1024 // 1 GB.

	f.WriteAt([]byte("hello"), int64(offset))

	var mms []mmap.MMap

	for i := 0; i < 100; i++ { // Re-mmap the file.
		mm, err := mmap.Map(f, mmap.RDONLY, 0)
		if err != nil {
			t.Errorf("expected mmap to work, err: %v", err)
		}

		if string(mm[offset:offset+5]) != "hello" {
			t.Errorf("expected hello")
		}

		mms = append(mms, mm)
	}

	for _, mm := range mms {
		if string(mm[offset:offset+5]) != "hello" {
			t.Errorf("expected hello")
		}

		for j := 0; j < offset; j += 1024 * 1024 {
			if mm[j] != 0 {
				t.Errorf("expected 0")
			}
		}
	}

	for _, mm := range mms {
		mm.Unmap()
	}

	f.Close()
}

func TestMMapRef(t *testing.T) {
	tmpDir, _ := ioutil.TempDir("", "mossStore")
	defer os.RemoveAll(tmpDir)

	var mu sync.Mutex
	counts := map[EventKind]int{}
	eventWaiters := map[EventKind]chan bool{}

	co := CollectionOptions{
		MergeOperator: &MergeOperatorStringAppend{Sep: ":"},
		OnEvent: func(event Event) {
			mu.Lock()
			counts[event.Kind]++
			eventWaiter := eventWaiters[event.Kind]
			mu.Unlock()
			if eventWaiter != nil {
				eventWaiter <- true
			}
		},
	}

	store, m, err := OpenStoreCollection(tmpDir, StoreOptions{
		CollectionOptions: co,
	}, StorePersistOptions{})
	if err != nil || m == nil || store == nil {
		t.Errorf("expected open empty store collection to work")
	}

	b, _ := m.NewBatch(0, 0)
	for i := 0; i < 1000; i++ {
		xs := fmt.Sprintf("%d", i)
		x := []byte(xs)
		b.Set(x, x)
	}
	err = m.ExecuteBatch(b, WriteOptions{})
	if err != nil {
		t.Errorf("expected exec batch to work")
	}
	b.Close()

	waitUntilClean := func() error {
		for {
			stats, err := m.Stats()
			if err != nil {
				return err
			}

			if stats.CurDirtyOps <= 0 &&
				stats.CurDirtyBytes <= 0 &&
				stats.CurDirtySegments <= 0 {
				break
			}

			time.Sleep(200 * time.Millisecond)
		}

		return nil
	}

	waitUntilClean()

	store.m.Lock()

	if store.refs != 1 {
		t.Errorf("expected 1 store ref, got: %d", store.refs)
	}

	footer := store.footer
	if footer == nil {
		t.Errorf("expected footer")
	}

	footer.m.Lock()
	if footer.refs != 2 {
		t.Errorf("expected 2 footer ref, : got: %d", footer.refs)
	}

	mref := footer.SegmentLocs[0].mref
	if mref == nil {
		t.Errorf("expected mref")
	}

	mrefsCheck := func(expected int) {
		mref.m.Lock()
		if mref.refs != expected {
			t.Errorf("expected mref.refs to be %d, got: %d", expected, mref.refs)
		}
		mref.m.Unlock()
	}

	mrefsCheck(1)

	rv := mref.AddRef()

	mrefsCheck(2)

	if rv != mref {
		t.Errorf("expected rv == mref")
	}

	if mref.DecRef() != nil {
		t.Errorf("expected mref.DecRef to be nil")
	}

	mrefsCheck(1)

	footer.m.Unlock()

	store.m.Unlock()

	m.Close()

	store.Close()

	footer.m.Lock()
	if footer.refs != 0 {
		t.Errorf("expected footer refs to be 0, got: %d", footer.refs)
	}
	footer.m.Unlock()

	store.m.Lock()
	if store.refs != 0 {
		t.Errorf("expected store refs to be 0, got: %d", footer.refs)
	}
	store.m.Unlock()

	mrefsCheck(0)
}

func TestRefCounting(t *testing.T) {
	tmpDir, _ := ioutil.TempDir("", "mossStore")
	defer os.RemoveAll(tmpDir)

	var mu sync.Mutex
	counts := map[EventKind]int{}
	eventWaiters := map[EventKind]chan bool{}

	co := CollectionOptions{
		OnEvent: func(event Event) {
			mu.Lock()
			counts[event.Kind]++
			eventWaiter := eventWaiters[event.Kind]
			mu.Unlock()
			if eventWaiter != nil {
				eventWaiter <- true
			}
		},
	}

	store, m, err := OpenStoreCollection(tmpDir,
		StoreOptions{CollectionOptions: co},
		StorePersistOptions{CompactionConcern: CompactionDisable})
	if err != nil || m == nil || store == nil {
		t.Errorf("expected open empty store collection to work")
	}

	// ---------------------------------------------

	checkRefs := func(f *Footer, frefs, mrefs int, cb func(), msg string) {
		f.m.Lock()

		if f.refs != frefs {
			t.Errorf("%s - expected footer.refs to be %d, got: %d",
				msg, frefs, f.refs)
		}

		n := len(f.SegmentLocs)
		if n > 0 &&
			f.SegmentLocs[n-1].mref != nil {
			f.SegmentLocs[n-1].mref.m.Lock()

			if f.SegmentLocs[n-1].mref.refs != mrefs {
				t.Errorf("%s - expected mrefs to be %d, got: %d",
					msg, mrefs, f.SegmentLocs[n-1].mref.refs)
			}

			if cb != nil {
				cb()
			}

			f.SegmentLocs[n-1].mref.m.Unlock()
		} else if mrefs > 0 {
			t.Errorf("%s - expected footer.mref to be %d, but nil mref",
				msg, mrefs)
		}

		f.m.Unlock()
	}

	writeHello := func() {
		b, _ := m.NewBatch(0, 0)
		b.Set([]byte("hello"), []byte("world"))
		err = m.ExecuteBatch(b, WriteOptions{})
		if err != nil {
			t.Errorf("expected exec batch to work")
		}
		b.Close()
	}

	waitUntilClean := func() error {
		for {
			var stats *CollectionStats
			stats, err = m.Stats()
			if err != nil {
				return err
			}

			if stats.CurDirtyOps <= 0 &&
				stats.CurDirtyBytes <= 0 &&
				stats.CurDirtySegments <= 0 {
				break
			}

			time.Sleep(time.Millisecond)
		}

		return nil
	}

	// ---------------------------------------------

	store.m.Lock()

	checkRefs(store.footer, 2, 0, nil, "new, empty store")

	store.m.Unlock()

	// ---------------------------------------------

	writeHello()

	waitUntilClean()

	// ---------------------------------------------

	store.m.Lock()

	checkRefs(store.footer, 2, 1, nil, "after 1st batch persisted")

	store.m.Unlock()

	// ---------------------------------------------

	ss0, err := store.Snapshot()
	if err != nil {
		t.Errorf("expected no err on snapshot")
	}

	f0, ok := ss0.(*Footer)
	if !ok {
		t.Errorf("expected Footer")
	}

	store.m.Lock()

	checkRefs(store.footer, 3, 1, nil, "after 1st batch persisted")

	checkRefs(f0, 3, 1, nil, "after 1st batch persisted, against f0")

	store.m.Unlock()

	for i := 0; i < 10; i++ {
		writeHello()
		waitUntilClean()
	}

	store.m.Lock()

	if f0 == store.footer {
		t.Errorf("expected curr footer to be != f0 after many mutations")
	}

	checkRefs(store.footer, 2, 1, nil, "after nth batch persisted")

	store.m.Unlock()

	var mref *mmapRef

	checkRefs(f0, 1, 2, func() {
		mref = f0.SegmentLocs[0].mref
	}, "oldest footer check")

	// ----------------------------------------

	ss0.Close() // Close the first, oldest snapshot.

	store.m.Lock()

	checkRefs(store.footer, 2, 1, nil, "after oldest snapshot closed")

	store.m.Unlock()

	checkRefs(f0, 0, 0, nil, "oldest footer after ss0.Close()")

	mref.m.Lock()
	if mref.refs != 1 {
		t.Errorf("expected mref.refs 1 after oldest ss closed, got: %d", mref.refs)
	}
	mref.m.Unlock()

	// ----------------------------------------

	m.Close()

	var fLast *Footer

	store.m.Lock()
	fLast = store.footer
	checkRefs(store.footer, 1, 1, nil, "after collection Close()'ed")
	store.m.Unlock()

	mref.m.Lock()
	if mref.refs != 1 {
		t.Errorf("expected mref.refs 1 after coll closed, got: %d", mref.refs)
	}
	mref.m.Unlock()

	// ----------------------------------------

	store.Close()

	mref.m.Lock()
	if mref.refs != 0 {
		t.Errorf("expected 0 mref.refs after everything closed")
	}
	mref.m.Unlock()

	checkRefs(fLast, 0, 0, nil, "last footer after store.Close()")

	checkRefs(f0, 0, 0, nil, "oldest footer after store.Close()")
}

// ---------------------------------------------

// SKIPPED because segfault isn't caught by recover()
func SKIPPEDTestAccessAfterUnmap(t *testing.T) {
	tmpDir, _ := ioutil.TempDir("", "mossMMap")
	defer os.RemoveAll(tmpDir)

	f, err := os.Create(tmpDir + string(os.PathSeparator) + "test.file")
	if err != nil {
		t.Errorf("expected open file to work, err: %v", err)
	}

	defer f.Close()

	offset := 1024 * 1024 * 1024 // 1 GB.

	f.WriteAt([]byte("hello"), int64(offset))

	var mm mmap.MMap

	mm, err = mmap.Map(f, mmap.RDONLY, 0)
	if err != nil {
		t.Errorf("expected mmap to work, err: %v", err)
	}

	x := mm[offset : offset+5]

	if string(x) != "hello" {
		t.Errorf("expected hello")
	}

	defer func() {
		if r := recover(); r != nil {
			fmt.Println("Recovered in f", r)
		} else {
			t.Errorf("expected recover from panic")
		}
	}()

	mm.Unmap()

	/*
			The following access of x results in a segfault, like...

				unexpected fault address 0x4060c000
				fatal error: fault
				[signal 0xb code=0x1 addr=0x4060c000 pc=0xb193f]

		    The recover() machinery doesn't handle this situation, however,
		    as it's not a normal kind of panic()
	*/
	if x[0] != 'h' {
		t.Errorf("expected h, but actually expected a segfault")
	}

	t.Errorf("expected segfault, but instead unmmapped mem access worked")
}