-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathpool.go
176 lines (163 loc) · 4.66 KB
/
pool.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
package pgsql
import "C" // Redundant in this file, but cgo complains otherwise.
import (
"os"
"fmt"
"log"
"sync"
"time"
"runtime"
"container/list"
)
const DEFAULT_IDLE_TIMEOUT = 300 // Seconds
type poolConn struct {
*Conn
atime int64 // Time at which Conn is inserted into free list
}
type pool struct {
params string // Params to create new Conn
conns *list.List // List of available Conns
max int // Maximum number of connections to create
n int // Number of connections created
cond *sync.Cond // Pool lock, and condition to signal when connection is released
timeout int64 // Idle timeout period in seconds
closed bool
Debug bool // Set to true to print debug messages to stderr
}
func (p *pool) log(msg string) {
if p.Debug {
log.Println(time.LocalTime().Format("2006-01-02 15:04:05"), msg)
}
}
// A Pool manages a list of connections that can be safely used by multiple goroutines.
type Pool struct {
// Subtle: Embed *pool struct so that timeoutCloser can operate on *pool
// without preventing *Pool being garbage collected (and properly finalized).
// See http://groups.google.com/group/golang-nuts/browse_thread/thread/d48b4d38e8fcc96f for discussion.
*pool
}
// Close connections that have been idle for > p.timeout seconds.
func timeoutCloser(p *pool) {
for p != nil && !p.closed {
p.cond.L.Lock()
now := time.Seconds()
delay := 1e9 * p.timeout
for p.conns.Len() > 0 {
front := p.conns.Front()
pc := front.Value.(poolConn)
atime := pc.atime
if (now - atime) > p.timeout {
pc.Conn.Close()
p.conns.Remove(front)
p.n--
p.log("idle connection closed")
} else {
// Wait until first connection would timeout if it isn't used.
delay = 1e9 * (p.timeout - (now - atime) + 1)
break
}
}
p.cond.L.Unlock()
time.Sleep(delay)
}
p.log("timeoutCloser finished")
}
// NewPool returns a new Pool that will create new connections on demand
// using connectParams, up to a maximum of maxConns outstanding connections.
// An error is returned if an initial connection cannot be created.
// Connections that have been idle for idleTimeout seconds will be automatically
// closed.
func NewPool(connectParams string, maxConns, idleTimeout int) (p *Pool, err os.Error) {
if maxConns < 1 {
return nil, os.NewError("maxConns must be >= 1")
}
if idleTimeout < 5 {
return nil, os.NewError("idleTimeout must be >= 5")
}
// Create initial connection to verify connectParams will work.
c, err := Connect(connectParams)
if err != nil {
return
}
p = &Pool{
&pool{
params: connectParams,
conns: list.New(),
max: maxConns,
n: 1,
cond: sync.NewCond(new(sync.Mutex)),
timeout: int64(idleTimeout),
},
}
p.conns.PushFront(poolConn{c, time.Seconds()})
go timeoutCloser(p.pool)
runtime.SetFinalizer(p, (*Pool).close)
return
}
// Acquire returns the next available connection, or returns an error if it
// failed to create a new connection.
// When an Acquired connection has been finished with, it should be returned
// to the pool via Release.
func (p *Pool) Acquire() (c *Conn, err os.Error) {
p.cond.L.Lock()
defer p.cond.L.Unlock()
if p.closed {
return nil, os.NewError("pool is closed")
}
if p.conns.Len() > 0 {
c = p.conns.Remove(p.conns.Front()).(poolConn).Conn
} else if p.conns.Len() == 0 && p.n < p.max {
c, err = Connect(p.params)
if err != nil {
return
}
p.n++
p.log("connection created")
} else { // p.conns.Len() == 0 && p.n == p.max
for p.conns.Len() == 0 {
p.cond.Wait()
}
c = p.conns.Remove(p.conns.Front()).(poolConn).Conn
}
if p.Debug {
p.log(fmt.Sprintf("connection acquired: %d idle, %d unused", p.conns.Len(), p.max-p.n))
}
return c, nil
}
// Release returns the previously Acquired connection to the list of available connections.
func (p *Pool) Release(c *Conn) {
p.cond.L.Lock()
defer p.cond.L.Unlock()
if !p.closed {
p.conns.PushBack(poolConn{c, time.Seconds()})
if p.Debug {
p.log(fmt.Sprintf("connection released: %d idle, %d unused", p.conns.Len(), p.max-p.n))
}
p.cond.Signal()
}
}
func (p *Pool) close() {
if p != nil {
nConns := p.conns.Len()
for p.conns.Len() > 0 {
p.conns.Remove(p.conns.Front()).(poolConn).Close()
}
p.n -= nConns
p.closed = true
runtime.SetFinalizer(p, nil)
p.log("close finished")
}
}
// Close closes any available connections and prevents the Acquiring of any new connections.
// It returns an error if there are any outstanding connections remaining.
func (p *Pool) Close() os.Error {
p.cond.L.Lock()
defer p.cond.L.Unlock()
if !p.closed {
p.close()
if p.n > 0 {
return os.NewError(fmt.Sprintf("pool closed but %d connections in use", p.n))
}
}
return nil
}