Unverified Commit eb171d31 authored by 望哥's avatar 望哥 Committed by GitHub

Merge pull request #1 from divebomb/master

Add: deadlock check
parents a06ff797 23f9ab54
# gostd
# gost
Optimization of something in golang sdk
A go sdk for [Apache Dubbo-go](github.com/apache/dubbo-go).
## bytes
* BytesBufferPool
> bytes.Buffer pool
* SlicePool
> slice pool
## sync
> deadlock
Copy from [go-deadlock](https://github.com/sasha-s/go-deadlock) and add EnableDeadlock.
## strings
* IsNil
> check a var is nil or not.
## time
Timer optimization through time-wheel.
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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 gxbytes
import (
"bytes"
"sync"
)
var (
defaultPool *ObjectPool
)
func init() {
defaultPool = NewObjectPool(func() PoolObject {
return new(bytes.Buffer)
})
}
// GetBytesBuffer returns bytes.Buffer from pool
func GetBytesBuffer() *bytes.Buffer {
return defaultPool.Get().(*bytes.Buffer)
}
// PutIoBuffer returns IoBuffer to pool
func PutBytesBuffer(buf *bytes.Buffer) {
defaultPool.Put(buf)
}
// Pool object
type PoolObject interface {
Reset()
}
type New func() PoolObject
// Pool is bytes.Buffer Pool
type ObjectPool struct {
New New
pool sync.Pool
}
func NewObjectPool(n New) *ObjectPool {
return &ObjectPool{New: n}
}
// take returns *bytes.Buffer from Pool
func (p *ObjectPool) Get() PoolObject {
v := p.pool.Get()
if v == nil {
return p.New()
}
return v.(PoolObject)
}
// give returns *byes.Buffer to Pool
func (p *ObjectPool) Put(o PoolObject) {
o.Reset()
p.pool.Put(o)
}
package gxbytes
import (
"testing"
)
func TestBytesBufferPool(t *testing.T) {
buf := GetBytesBuffer()
bytes := []byte{0x00, 0x01, 0x02, 0x03, 0x04}
buf.Write(bytes)
if buf.Len() != len(bytes) {
t.Error("iobuffer len not match write bytes' size")
}
PutBytesBuffer(buf)
buf2 := GetBytesBuffer()
// https://go-review.googlesource.com/c/go/+/162919/
// before go 1.13, sync.Pool just reserves some objs before every gc and will be cleanup by gc.
// after Go 1.13, maybe there are many reserved objs after gc.
if buf != buf2 {
t.Errorf("buf pointer %p != buf2 pointer %p", buf, buf2)
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF 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 gxbytes
import (
"sync"
)
const (
minShift = 6
maxShift = 18
errSlot = -1
)
var (
defaultSlicePool *SlicePool
)
func init() {
defaultSlicePool = NewSlicePool()
}
// SlicePool is []byte pools
type SlicePool struct {
minShift int
minSize int
maxSize int
pool []*sliceSlot
}
type sliceSlot struct {
defaultSize int
pool sync.Pool
}
// newSlicePool returns SlicePool
func NewSlicePool() *SlicePool {
p := &SlicePool{
minShift: minShift,
minSize: 1 << minShift,
maxSize: 1 << maxShift,
}
for i := 0; i <= maxShift-minShift; i++ {
slab := &sliceSlot{
defaultSize: 1 << (uint)(i+minShift),
}
p.pool = append(p.pool, slab)
}
return p
}
func (p *SlicePool) slot(size int) int {
if size > p.maxSize {
return errSlot
}
slot := 0
shift := 0
if size > p.minSize {
size--
for size > 0 {
size = size >> 1
shift++
}
slot = shift - p.minShift
}
return slot
}
func newSlice(size int) []byte {
return make([]byte, size)
}
// Get returns *[]byte from SlicePool
func (p *SlicePool) Get(size int) *[]byte {
slot := p.slot(size)
if slot == errSlot {
b := newSlice(size)
return &b
}
v := p.pool[slot].pool.Get()
if v == nil {
b := newSlice(p.pool[slot].defaultSize)
b = b[0:size]
return &b
}
b := v.(*[]byte)
*b = (*b)[0:size]
return b
}
// Put returns *[]byte to SlicePool
func (p *SlicePool) Put(buf *[]byte) {
if buf == nil {
return
}
size := cap(*buf)
slot := p.slot(size)
if slot == errSlot {
return
}
if size != int(p.pool[slot].defaultSize) {
return
}
p.pool[slot].pool.Put(buf)
}
// GetBytes returns *[]byte from SlicePool
func GetBytes(size int) *[]byte {
return defaultSlicePool.Get(size)
}
// PutBytes Put *[]byte to SlicePool
func PutBytes(buf *[]byte) {
defaultSlicePool.Put(buf)
}
package gxbytes
import (
"math/rand"
"testing"
"time"
)
func init() {
rand.Seed(time.Now().UnixNano())
}
func intRange(min, max int) int {
return rand.Intn(max-min) + min
}
func intN(n int) int {
return rand.Intn(n) + 1
}
func ExampleGetBytes() {
str := "hello, world"
// Obtain a buffer from the pool.
bufPtr := GetBytes(len(str))
defer PutBytes(bufPtr)
buf := *bufPtr
copy(buf, []byte(str))
if string(buf) != str {
panic("wrong slice buffer content!!")
}
}
func TestSlicePoolSmallBytes(t *testing.T) {
pool := NewSlicePool()
for i := 0; i < 1024; i++ {
size := intN(1 << minShift)
bp := pool.Get(size)
if cap(*bp) != 1<<minShift {
t.Errorf("Expect get the %d bytes from pool, but got %d", size, cap(*bp))
}
// Puts the bytes to pool
pool.Put(bp)
}
}
func TestSlicePoolMediumBytes(t *testing.T) {
pool := NewSlicePool()
for i := minShift; i < maxShift; i++ {
size := intRange((1<<uint(i))+1, 1<<uint(i+1))
bp := pool.Get(size)
if cap(*bp) != 1<<uint(i+1) {
t.Errorf("Expect get the slab size (%d) from pool, but got %d", 1<<uint(i+1), cap(*bp))
}
//Puts the bytes to pool
pool.Put(bp)
}
}
func TestSlicePoolLargeBytes(t *testing.T) {
pool := NewSlicePool()
for i := 0; i < 1024; i++ {
size := 1<<maxShift + intN(i+1)
bp := pool.Get(size)
if cap(*bp) != size {
t.Errorf("Expect get the %d bytes from pool, but got %d", size, cap(*bp))
}
// Puts the bytes to pool
pool.Put(bp)
}
}
func TestBytesSlot(t *testing.T) {
pool := NewSlicePool()
if pool.slot(pool.minSize-1) != 0 {
t.Errorf("Expect get the 0 slot")
}
if pool.slot(pool.minSize) != 0 {
t.Errorf("Expect get the 0 slot")
}
if pool.slot(pool.minSize+1) != 1 {
t.Errorf("Expect get the 1 slot")
}
if pool.slot(pool.maxSize-1) != maxShift-minShift {
t.Errorf("Expect get the %d slot", maxShift-minShift)
}
if pool.slot(pool.maxSize) != maxShift-minShift {
t.Errorf("Expect get the %d slot", maxShift-minShift)
}
if pool.slot(pool.maxSize+1) != errSlot {
t.Errorf("Expect get errSlot")
}
}
// Copyright 2016 ~ 2018 AlexStocks(https://github.com/AlexStocks).
// All rights reserved. Use of this source code is
// governed by Apache License 2.0.
package gxstrings
import (
"reflect"
)
func IsNil(i interface{}) bool {
if i == nil {
return true
}
if reflect.ValueOf(i).IsNil() {
return true
}
return false
}
This diff is collapsed.
# Online deadlock detection in go (golang). [![Try it online](https://img.shields.io/badge/try%20it-online-blue.svg)](https://wandbox.org/permlink/hJc6QCZowxbNm9WW) [![Docs](https://godoc.org/github.com/sasha-s/go-deadlock?status.svg)](https://godoc.org/github.com/sasha-s/go-deadlock) [![Build Status](https://travis-ci.org/sasha-s/go-deadlock.svg?branch=master)](https://travis-ci.org/sasha-s/go-deadlock) [![codecov](https://codecov.io/gh/sasha-s/go-deadlock/branch/master/graph/badge.svg)](https://codecov.io/gh/sasha-s/go-deadlock) [![version](https://badge.fury.io/gh/sasha-s%2Fgo-deadlock.svg)](https://github.com/sasha-s/go-deadlock/releases) [![Go Report Card](https://goreportcard.com/badge/github.com/sasha-s/go-deadlock)](https://goreportcard.com/report/github.com/sasha-s/go-deadlock) [![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0)
## Why
Deadlocks happen and are painful to debug.
## What
go-deadlock provides (RW)Mutex drop-in replacements for sync.(RW)Mutex.
It would not work if you create a spaghetti of channels.
Mutexes only.
## Installation
```sh
go get github.com/sasha-s/go-deadlock/...
```
## Usage
```go
import "github.com/sasha-s/go-deadlock"
var mu deadlock.Mutex
// Use normally, it works exactly like sync.Mutex does.
mu.Lock()
defer mu.Unlock()
// Or
var rw deadlock.RWMutex
rw.RLock()
defer rw.RUnlock()
```
### Deadlocks
One of the most common sources of deadlocks is inconsistent lock ordering:
say, you have two mutexes A and B, and in some goroutines you have
```go
A.Lock() // defer A.Unlock() or similar.
...
B.Lock() // defer B.Unlock() or similar.
```
And in another goroutine the order of locks is reversed:
```go
B.Lock() // defer B.Unlock() or similar.
...
A.Lock() // defer A.Unlock() or similar.
```
Another common sources of deadlocs is duplicate take a lock in a goroutine:
```
A.Rlock() or lock()
A.lock() or A.RLock()
```
This does not guarantee a deadlock (maybe the goroutines above can never be running at the same time), but it usually a design flaw at least.
go-deadlock can detect such cases (unless you cross goroutine boundary - say lock A, then spawn a goroutine, block until it is singals, and lock B inside of the goroutine), even if the deadlock itself happens very infrequently and is painful to reproduce!
Each time go-deadlock sees a lock attempt for lock B, it records the order A before B, for each lock that is currently being held in the same goroutine, and it prints (and exits the program by default) when it sees the locking order being violated.
In addition, if it sees that we are waiting on a lock for a long time (opts.DeadlockTimeout, 30 seconds by default), it reports a potential deadlock, also printing the stacktrace for a goroutine that is currently holding the lock we are desperately trying to grab.
## Sample output
#### Inconsistent lock ordering:
```
POTENTIAL DEADLOCK: Inconsistent locking. saw this ordering in one goroutine:
happened before
inmem.go:623 bttest.(*server).ReadModifyWriteRow { r.mu.Lock() } <<<<<
inmem_test.go:118 bttest.TestConcurrentMutationsReadModifyAndGC.func4 { _, _ = s.ReadModifyWriteRow(ctx, rmw()) }
happened after
inmem.go:629 bttest.(*server).ReadModifyWriteRow { tbl.mu.RLock() } <<<<<
inmem_test.go:118 bttest.TestConcurrentMutationsReadModifyAndGC.func4 { _, _ = s.ReadModifyWriteRow(ctx, rmw()) }
in another goroutine: happened before
inmem.go:799 bttest.(*table).gc { t.mu.RLock() } <<<<<
inmem_test.go:125 bttest.TestConcurrentMutationsReadModifyAndGC.func5 { tbl.gc() }
happend after
inmem.go:814 bttest.(*table).gc { r.mu.Lock() } <<<<<
inmem_test.go:125 bttest.TestConcurrentMutationsReadModifyAndGC.func5 { tbl.gc() }
```
#### Waiting for a lock for a long time:
```
POTENTIAL DEADLOCK:
Previous place where the lock was grabbed
goroutine 240 lock 0xc820160440
inmem.go:799 bttest.(*table).gc { t.mu.RLock() } <<<<<
inmem_test.go:125 bttest.TestConcurrentMutationsReadModifyAndGC.func5 { tbl.gc() }
Have been trying to lock it again for more than 40ms
goroutine 68 lock 0xc820160440
inmem.go:785 bttest.(*table).mutableRow { t.mu.Lock() } <<<<<
inmem.go:428 bttest.(*server).MutateRow { r := tbl.mutableRow(string(req.RowKey)) }
inmem_test.go:111 bttest.TestConcurrentMutationsReadModifyAndGC.func3 { s.MutateRow(ctx, req) }
Here is what goroutine 240 doing now
goroutine 240 [select]:
github.com/sasha-s/go-deadlock.lock(0xc82028ca10, 0x5189e0, 0xc82013a9b0)
/Users/sasha/go/src/github.com/sasha-s/go-deadlock/deadlock.go:163 +0x1640
github.com/sasha-s/go-deadlock.(*Mutex).Lock(0xc82013a9b0)
/Users/sasha/go/src/github.com/sasha-s/go-deadlock/deadlock.go:54 +0x86
google.golang.org/cloud/bigtable/bttest.(*table).gc(0xc820160440)
/Users/sasha/go/src/google.golang.org/cloud/bigtable/bttest/inmem.go:814 +0x28d
google.golang.org/cloud/bigtable/bttest.TestConcurrentMutationsReadModifyAndGC.func5(0xc82015c760, 0xc820160440) /Users/sasha/go/src/google.golang.org/cloud/bigtable/bttest/inmem_test.go:125 +0x48
created by google.golang.org/cloud/bigtable/bttest.TestConcurrentMutationsReadModifyAndGC
/Users/sasha/go/src/google.golang.org/cloud/bigtable/bttest/inmem_test.go:126 +0xb6f
```
## Used in
[cockroachdb: Potential deadlock between Gossip.SetStorage and Node.gossipStores](https://github.com/cockroachdb/cockroach/issues/7972)
[bigtable/bttest: A race between GC and row mutations](https://code-review.googlesource.com#/c/5301/)
## Need a mutex that works with net.context?
I have [one](https://github.com/sasha-s/go-csync).
## Grabbing an RLock twice from the same goroutine
This is, surprisingly, not a good idea!
From [RWMutex](https://golang.org/pkg/sync/#RWMutex) docs:
>If a goroutine holds a RWMutex for reading and another goroutine might call Lock, no goroutine should expect to be able to acquire a read lock until the initial read lock is released. In particular, this prohibits recursive read locking. This is to ensure that the lock eventually becomes available; a blocked Lock call excludes new readers from acquiring the lock.
The following code will deadlock &mdash; [run the example on playground](https://play.golang.org/p/AkL-W63nq5f) or [try it online with go-deadlock on wandbox](https://wandbox.org/permlink/JwnL0GMySBju4SII):
```go
package main
import (
"fmt"
"sync"
)
func main() {
var mu sync.RWMutex
chrlockTwice := make(chan struct{}) // Used to control rlockTwice
rlockTwice := func() {
mu.RLock()
fmt.Println("first Rlock succeeded")
<-chrlockTwice
<-chrlockTwice
fmt.Println("trying to Rlock again")
mu.RLock()
fmt.Println("second Rlock succeeded")
mu.RUnlock()
mu.RUnlock()
}
chLock := make(chan struct{}) // Used to contol lock
lock := func() {
<-chLock
fmt.Println("about to Lock")
mu.Lock()
fmt.Println("Lock succeeded")
mu.Unlock()
<-chLock
}
control := func() {
chrlockTwice <- struct{}{}
chLock <- struct{}{}
close(chrlockTwice)
close(chLock)
}
go control()
go lock()
rlockTwice()
}
```
package gxsync
// ref: github.com/sasha-s/go-deadlock
import (
"bufio"
"bytes"
"fmt"
"io"
"os"
"sync"
"time"
"github.com/petermattis/goid"
)
// Opts control how deadlock detection behaves.
// Options are supposed to be set once at a startup (say, when parsing flags).
var Opts = struct {
// Mutex/RWMutex would work exactly as their sync counterparts
// -- almost no runtime penalty, no deadlock detection if Disable == true.
Disable bool
// Would disable lock order based deadlock detection if DisableLockOrderDetection == true.
DisableLockOrderDetection bool
// Waiting for a lock for longer than DeadlockTimeout is considered a deadlock.
// Ignored is DeadlockTimeout <= 0.
DeadlockTimeout time.Duration
// OnPotentialDeadlock is called each time a potential deadlock is detected -- either based on
// lock order or on lock wait time.
OnPotentialDeadlock func()
// Will keep MaxMapSize lock pairs (happens before // happens after) in the map.
// The map resets once the threshold is reached.
MaxMapSize int
// Will dump stacktraces of all goroutines when inconsistent locking is detected.
PrintAllCurrentGoroutines bool
mu *sync.Mutex // Protects the LogBuf.
// Will print deadlock info to log buffer.
LogBuf io.Writer
}{
DeadlockTimeout: time.Second * 30,
OnPotentialDeadlock: func() {
os.Exit(2)
},
MaxMapSize: 1024 * 64,
mu: &sync.Mutex{},
LogBuf: os.Stderr,
}
// Cond is sync.Cond wrapper
type Cond struct {
sync.Cond
}
// Locker is sync.Locker wrapper
type Locker struct {
sync.Locker
}
// Once is sync.Once wrapper
type Once struct {
sync.Once
}
// Pool is sync.Poll wrapper
type Pool struct {
sync.Pool
}
// WaitGroup is sync.WaitGroup wrapper
type WaitGroup struct {
sync.WaitGroup
}
// A Mutex is a drop-in replacement for sync.Mutex.
// Performs deadlock detection unless disabled in Opts.
type Mutex struct {
mu sync.Mutex
}
// Lock locks the mutex.
// If the lock is already in use, the calling goroutine
// blocks until the mutex is available.
//
// Unless deadlock detection is disabled, logs potential deadlocks to Opts.LogBuf,
// calling Opts.OnPotentialDeadlock on each occasion.
func (m *Mutex) Lock() {
lock(m.mu.Lock, m)
}
// Unlock unlocks the mutex.
// It is a run-time error if m is not locked on entry to Unlock.
//
// A locked Mutex is not associated with a particular goroutine.
// It is allowed for one goroutine to lock a Mutex and then
// arrange for another goroutine to unlock it.
func (m *Mutex) Unlock() {
m.mu.Unlock()
if !Opts.Disable {
postUnlock(m)
}
}
// An RWMutex is a drop-in replacement for sync.RWMutex.
// Performs deadlock detection unless disabled in Opts.
type RWMutex struct {
mu sync.RWMutex
}
// Lock locks rw for writing.
// If the lock is already locked for reading or writing,
// Lock blocks until the lock is available.
// To ensure that the lock eventually becomes available,
// a blocked Lock call excludes new readers from acquiring
// the lock.
//
// Unless deadlock detection is disabled, logs potential deadlocks to Opts.LogBuf,
// calling Opts.OnPotentialDeadlock on each occasion.
func (m *RWMutex) Lock() {
lock(m.mu.Lock, m)
}
// Unlock unlocks the mutex for writing. It is a run-time error if rw is
// not locked for writing on entry to Unlock.
//
// As with Mutexes, a locked RWMutex is not associated with a particular
// goroutine. One goroutine may RLock (Lock) an RWMutex and then
// arrange for another goroutine to RUnlock (Unlock) it.
func (m *RWMutex) Unlock() {
m.mu.Unlock()
if !Opts.Disable {
postUnlock(m)
}
}
// RLock locks the mutex for reading.
//
// Unless deadlock detection is disabled, logs potential deadlocks to Opts.LogBuf,
// calling Opts.OnPotentialDeadlock on each occasion.
func (m *RWMutex) RLock() {
lock(m.mu.RLock, m)
}
// RUnlock undoes a single RLock call;
// it does not affect other simultaneous readers.
// It is a run-time error if rw is not locked for reading
// on entry to RUnlock.
func (m *RWMutex) RUnlock() {
m.mu.RUnlock()
if !Opts.Disable {
postUnlock(m)
}
}
// RLocker returns a Locker interface that implements
// the Lock and Unlock methods by calling RLock and RUnlock.
func (m *RWMutex) RLocker() sync.Locker {
return (*rlocker)(m)
}
func preLock(skip int, p interface{}) {
lo.preLock(skip, p)
}
func postLock(skip int, p interface{}) {
lo.postLock(skip, p)
}
func postUnlock(p interface{}) {
lo.postUnlock(p)
}
func lock(lockFn func(), ptr interface{}) {
if Opts.Disable {
lockFn()
return
}
preLock(4, ptr)
if Opts.DeadlockTimeout <= 0 {
lockFn()
} else {
ch := make(chan struct{})
go func() {
for {
t := time.NewTimer(Opts.DeadlockTimeout)
defer t.Stop() // This runs after the losure finishes, but it's OK.
select {
case <-t.C:
lo.mu.Lock()
prev, ok := lo.cur[ptr]
if !ok {
lo.mu.Unlock()
break // Nobody seems to be holding the lock, try again.
}
Opts.mu.Lock()
fmt.Fprintln(Opts.LogBuf, header)
fmt.Fprintln(Opts.LogBuf, "Previous place where the lock was grabbed")
fmt.Fprintf(Opts.LogBuf, "goroutine %v lock %p\n", prev.gid, ptr)
printStack(Opts.LogBuf, prev.stack)
fmt.Fprintln(Opts.LogBuf, "Have been trying to lock it again for more than", Opts.DeadlockTimeout)
fmt.Fprintf(Opts.LogBuf, "goroutine %v lock %p\n", goid.Get(), ptr)
printStack(Opts.LogBuf, callers(2))
stacks := stacks()
grs := bytes.Split(stacks, []byte("\n\n"))
for _, g := range grs {
if goid.ExtractGID(g) == prev.gid {
fmt.Fprintln(Opts.LogBuf, "Here is what goroutine", prev.gid, "doing now")
Opts.LogBuf.Write(g)
fmt.Fprintln(Opts.LogBuf)
}
}
lo.other(ptr)
if Opts.PrintAllCurrentGoroutines {
fmt.Fprintln(Opts.LogBuf, "All current goroutines:")
Opts.LogBuf.Write(stacks)
}
fmt.Fprintln(Opts.LogBuf)
if buf, ok := Opts.LogBuf.(*bufio.Writer); ok {
buf.Flush()
}
Opts.mu.Unlock()
lo.mu.Unlock()
Opts.OnPotentialDeadlock()
<-ch
return
case <-ch:
return
}
}
}()
lockFn()
postLock(4, ptr)
close(ch)
return
}
postLock(4, ptr)
}
type lockOrder struct {
mu sync.Mutex
cur map[interface{}]stackGID // stacktraces + gids for the locks currently taken.
order map[beforeAfter]ss // expected order of locks.
}
type stackGID struct {
stack []uintptr
gid int64
}
type beforeAfter struct {
before interface{}
after interface{}
}
type ss struct {
before []uintptr
after []uintptr
}
var lo = newLockOrder()
func newLockOrder() *lockOrder {
return &lockOrder{
cur: map[interface{}]stackGID{},
order: map[beforeAfter]ss{},
}
}
func (l *lockOrder) postLock(skip int, p interface{}) {
stack := callers(skip)
gid := goid.Get()
l.mu.Lock()
l.cur[p] = stackGID{stack, gid}
l.mu.Unlock()
}
func (l *lockOrder) preLock(skip int, p interface{}) {
if Opts.DisableLockOrderDetection {
return
}
stack := callers(skip)
gid := goid.Get()
l.mu.Lock()
for b, bs := range l.cur {
if b == p {
if bs.gid == gid {
Opts.mu.Lock()
fmt.Fprintln(Opts.LogBuf, header, "Recursive locking:")
fmt.Fprintf(Opts.LogBuf, "current goroutine %d lock %p\n", gid, b)
printStack(Opts.LogBuf, stack)
fmt.Fprintln(Opts.LogBuf, "Previous place where the lock was grabbed (same goroutine)")
printStack(Opts.LogBuf, bs.stack)
l.other(p)
if buf, ok := Opts.LogBuf.(*bufio.Writer); ok {
buf.Flush()
}
Opts.mu.Unlock()
Opts.OnPotentialDeadlock()
}
continue
}
if bs.gid != gid { // We want locks taken in the same goroutine only.
continue
}
if s, ok := l.order[beforeAfter{p, b}]; ok {
Opts.mu.Lock()
fmt.Fprintln(Opts.LogBuf, header, "Inconsistent locking. saw this ordering in one goroutine:")
fmt.Fprintln(Opts.LogBuf, "happened before")
printStack(Opts.LogBuf, s.before)
fmt.Fprintln(Opts.LogBuf, "happened after")
printStack(Opts.LogBuf, s.after)
fmt.Fprintln(Opts.LogBuf, "in another goroutine: happened before")
printStack(Opts.LogBuf, bs.stack)
fmt.Fprintln(Opts.LogBuf, "happened after")
printStack(Opts.LogBuf, stack)
l.other(p)
fmt.Fprintln(Opts.LogBuf)
if buf, ok := Opts.LogBuf.(*bufio.Writer); ok {
buf.Flush()
}
Opts.mu.Unlock()
Opts.OnPotentialDeadlock()
}
l.order[beforeAfter{b, p}] = ss{bs.stack, stack}
if len(l.order) == Opts.MaxMapSize { // Reset the map to keep memory footprint bounded.
l.order = map[beforeAfter]ss{}
}
}
l.mu.Unlock()
}
func (l *lockOrder) postUnlock(p interface{}) {
l.mu.Lock()
delete(l.cur, p)
l.mu.Unlock()
}
type rlocker RWMutex
func (r *rlocker) Lock() { (*RWMutex)(r).RLock() }
func (r *rlocker) Unlock() { (*RWMutex)(r).RUnlock() }
// Under lo.mu Locked.
func (l *lockOrder) other(ptr interface{}) {
empty := true
for k := range l.cur {
if k == ptr {
continue
}
empty = false
}
if empty {
return
}
fmt.Fprintln(Opts.LogBuf, "Other goroutines holding locks:")
for k, pp := range l.cur {
if k == ptr {
continue
}
fmt.Fprintf(Opts.LogBuf, "goroutine %v lock %p\n", pp.gid, k)
printStack(Opts.LogBuf, pp.stack)
}
fmt.Fprintln(Opts.LogBuf)
}
const header = "POTENTIAL DEADLOCK:"
// +build go1.9
package gxsync
// ref: github.com/sasha-s/go-deadlock
import "sync"
// Map is sync.Map wrapper
type Map struct {
sync.Map
}
package gxsync
// ref: github.com/sasha-s/go-deadlock
import (
"log"
"math/rand"
"sync"
"sync/atomic"
"testing"
"time"
)
func TestNoDeadlocks(t *testing.T) {
defer restore()()
Opts.DeadlockTimeout = time.Millisecond * 5000
var a RWMutex
var b Mutex
var c RWMutex
var wg sync.WaitGroup
for i := 0; i < 10; i++ {
wg.Add(1)
go func() {
defer wg.Done()
for k := 0; k < 5; k++ {
func() {
a.Lock()
defer a.Unlock()
func() {
b.Lock()
defer b.Unlock()
func() {
c.RLock()
defer c.RUnlock()
time.Sleep(time.Duration((1000 + rand.Intn(1000))) * time.Millisecond / 200)
}()
}()
}()
}
}()
wg.Add(1)
go func() {
defer wg.Done()
for k := 0; k < 5; k++ {
func() {
a.RLock()
defer a.RUnlock()
func() {
b.Lock()
defer b.Unlock()
func() {
c.Lock()
defer c.Unlock()
time.Sleep(time.Duration((1000 + rand.Intn(1000))) * time.Millisecond / 200)
}()
}()
}()
}
}()
}
wg.Wait()
}
func TestLockOrder(t *testing.T) {
defer restore()()
Opts.DeadlockTimeout = 0
var deadlocks uint32
Opts.OnPotentialDeadlock = func() {
atomic.AddUint32(&deadlocks, 1)
}
var a RWMutex
var b Mutex
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
a.Lock()
b.Lock()
b.Unlock()
a.Unlock()
}()
wg.Wait()
wg.Add(1)
go func() {
defer wg.Done()
b.Lock()
a.RLock()
a.RUnlock()
b.Unlock()
}()
wg.Wait()
if atomic.LoadUint32(&deadlocks) != 1 {
t.Fatalf("expected 1 deadlock, detected %d", deadlocks)
}
}
func TestHardDeadlock(t *testing.T) {
defer restore()()
Opts.DisableLockOrderDetection = true
Opts.DeadlockTimeout = time.Millisecond * 20
var deadlocks uint32
Opts.OnPotentialDeadlock = func() {
atomic.AddUint32(&deadlocks, 1)
}
var mu Mutex
mu.Lock()
ch := make(chan struct{})
go func() {
defer close(ch)
mu.Lock()
defer mu.Unlock()
}()
select {
case <-ch:
case <-time.After(time.Millisecond * 100):
}
if atomic.LoadUint32(&deadlocks) != 1 {
t.Fatalf("expected 1 deadlock, detected %d", deadlocks)
}
log.Println("****************")
mu.Unlock()
<-ch
}
func TestRWMutex(t *testing.T) {
defer restore()()
Opts.DeadlockTimeout = time.Millisecond * 20
var deadlocks uint32
Opts.OnPotentialDeadlock = func() {
atomic.AddUint32(&deadlocks, 1)
}
var a RWMutex
a.RLock()
go func() {
// We detect a potential deadlock here.
a.Lock()
defer a.Unlock()
}()
time.Sleep(time.Millisecond * 100) // We want the Lock call to happen.
ch := make(chan struct{})
go func() {
// We detect a potential deadlock here.
defer close(ch)
a.RLock()
defer a.RUnlock()
}()
select {
case <-ch:
t.Fatal("expected a timeout")
case <-time.After(time.Millisecond * 50):
}
a.RUnlock()
if atomic.LoadUint32(&deadlocks) != 2 {
t.Fatalf("expected 2 deadlocks, detected %d", deadlocks)
}
<-ch
}
func restore() func() {
opts := Opts
return func() {
Opts = opts
}
}
func TestLockDuplicate(t *testing.T) {
defer restore()()
Opts.DeadlockTimeout = 0
var deadlocks uint32
Opts.OnPotentialDeadlock = func() {
atomic.AddUint32(&deadlocks, 1)
}
var a RWMutex
var b Mutex
go func() {
a.RLock()
a.Lock()
a.RUnlock()
a.Unlock()
}()
go func() {
b.Lock()
b.Lock()
b.Unlock()
b.Unlock()
}()
time.Sleep(time.Second * 1)
if atomic.LoadUint32(&deadlocks) != 2 {
t.Fatalf("expected 2 deadlocks, detected %d", deadlocks)
}
}
package gxsync
// ref: github.com/sasha-s/go-deadlock
func EnableDeadlock(enable bool) {
Opts.Disable = true
Opts.DisableLockOrderDetection = true
if enable {
Opts.Disable = false
Opts.DisableLockOrderDetection = false
}
}
package gxsync
// ref: github.com/sasha-s/go-deadlock
import (
"bytes"
"fmt"
"io"
"io/ioutil"
"os"
"os/user"
"path/filepath"
"runtime"
"strings"
"sync"
)
func callers(skip int) []uintptr {
s := make([]uintptr, 50) // Most relevant context seem to appear near the top of the stack.
return s[:runtime.Callers(2+skip, s)]
}
func printStack(w io.Writer, stack []uintptr) {
home := os.Getenv("HOME")
usr, err := user.Current()
if err == nil {
home = usr.HomeDir
}
cwd, _ := os.Getwd()
for i, pc := range stack {
f := runtime.FuncForPC(pc)
name := f.Name()
pkg := ""
if pos := strings.LastIndex(name, "/"); pos >= 0 {
name = name[pos+1:]
}
if pos := strings.Index(name, "."); pos >= 0 {
pkg = name[:pos]
name = name[pos+1:]
}
file, line := f.FileLine(pc - 1)
if (pkg == "runtime" && name == "goexit") || (pkg == "testing" && name == "tRunner") {
fmt.Fprintln(w)
return
}
tail := ""
if i == 0 {
tail = " <<<<<" // Make the line performing a lock prominent.
}
// Shorten the file name.
clean := file
if cwd != "" {
cl, err := filepath.Rel(cwd, file)
if err == nil {
clean = cl
}
}
if home != "" {
s2 := strings.Replace(file, home, "~", 1)
if len(clean) > len(s2) {
clean = s2
}
}
fmt.Fprintf(w, "%s:%d %s.%s %s%s\n", clean, line, pkg, name, code(file, line), tail)
}
fmt.Fprintln(w)
}
var fileSources struct {
sync.Mutex
lines map[string][][]byte
}
// Reads souce file lines from disk if not cached already.
func getSourceLines(file string) [][]byte {
fileSources.Lock()
defer fileSources.Unlock()
if fileSources.lines == nil {
fileSources.lines = map[string][][]byte{}
}
if lines, ok := fileSources.lines[file]; ok {
return lines
}
text, _ := ioutil.ReadFile(file)
fileSources.lines[file] = bytes.Split(text, []byte{'\n'})
return fileSources.lines[file]
}
func code(file string, line int) string {
lines := getSourceLines(file)
// lines are 1 based.
if line >= len(lines) || line <= 0 {
return "???"
}
return "{ " + string(bytes.TrimSpace(lines[line-1])) + " }"
}
// Stacktraces for all goroutines.
func stacks() []byte {
buf := make([]byte, 1024*16)
for {
n := runtime.Stack(buf, true)
if n < len(buf) {
return buf[:n]
}
buf = make([]byte, 2*len(buf))
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment