summaryrefslogtreecommitdiff
path: root/plugins/jobs/broker/beanstalk/conn.go
blob: 7aba6bbb485362143b744f65d51ba9353ed6d429 (plain)
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
package beanstalk

import (
	"fmt"
	"github.com/beanstalkd/go-beanstalk"
	"github.com/cenkalti/backoff/v4"
	"strings"
	"sync"
	"time"
)

var connErrors = []string{"pipe", "read tcp", "write tcp", "connection", "EOF"}

// creates new connections
type connFactory interface {
	newConn() (*conn, error)
}

// conn protects allocation for one connection between
// threads and provides reconnecting capabilities.
type conn struct {
	tout  time.Duration
	conn  *beanstalk.Conn
	alive bool
	free  chan interface{}
	dead  chan interface{}
	stop  chan interface{}
	lock  *sync.Cond
}

// creates new beanstalk connection and reconnect watcher.
func newConn(network, addr string, tout time.Duration) (cn *conn, err error) {
	cn = &conn{
		tout:  tout,
		alive: true,
		free:  make(chan interface{}, 1),
		dead:  make(chan interface{}, 1),
		stop:  make(chan interface{}),
		lock:  sync.NewCond(&sync.Mutex{}),
	}

	cn.conn, err = beanstalk.Dial(network, addr)
	if err != nil {
		return nil, err
	}

	go cn.watch(network, addr)

	return cn, nil
}

// reset the connection and reconnect watcher.
func (cn *conn) Close() error {
	cn.lock.L.Lock()
	defer cn.lock.L.Unlock()

	close(cn.stop)
	for cn.alive {
		cn.lock.Wait()
	}

	return nil
}

// acquire connection instance or return error in case of timeout. When mandratory set to true
// timeout won't be applied.
func (cn *conn) acquire(mandatory bool) (*beanstalk.Conn, error) {
	// do not apply timeout on mandatory connections
	if mandatory {
		select {
		case <-cn.stop:
			return nil, fmt.Errorf("connection closed")
		case <-cn.free:
			return cn.conn, nil
		}
	}

	select {
	case <-cn.stop:
		return nil, fmt.Errorf("connection closed")
	case <-cn.free:
		return cn.conn, nil
	default:
		// *2 to handle commands called right after the connection reset
		tout := time.NewTimer(cn.tout * 2)
		select {
		case <-cn.stop:
			tout.Stop()
			return nil, fmt.Errorf("connection closed")
		case <-cn.free:
			tout.Stop()
			return cn.conn, nil
		case <-tout.C:
			return nil, fmt.Errorf("unable to allocate connection (timeout %s)", cn.tout)
		}
	}
}

// release acquired connection.
func (cn *conn) release(err error) error {
	if isConnError(err) {
		// reconnect is required
		cn.dead <- err
	} else {
		cn.free <- nil
	}

	return err
}

// watch and reconnect if dead
func (cn *conn) watch(network, addr string) {
	cn.free <- nil
	t := time.NewTicker(WatchThrottleLimit)
	defer t.Stop()
	for {
		select {
		case <-cn.dead:
			// simple throttle limiter
			<-t.C
			// try to reconnect
			// TODO add logging here
			expb := backoff.NewExponentialBackOff()
			expb.MaxInterval = cn.tout

			reconnect := func() error {
				conn, err := beanstalk.Dial(network, addr)
				if err != nil {
					fmt.Println(fmt.Sprintf("redial: error during the beanstalk dialing, %s", err.Error()))
					return err
				}

				// TODO ADD LOGGING
				fmt.Println("------beanstalk successfully redialed------")

				cn.conn = conn
				cn.free <- nil
				return nil
			}

			err := backoff.Retry(reconnect, expb)
			if err != nil {
				fmt.Println(fmt.Sprintf("redial failed: %s", err.Error()))
				cn.dead <- nil
			}

		case <-cn.stop:
			cn.lock.L.Lock()
			select {
			case <-cn.dead:
			case <-cn.free:
			}

			// stop underlying connection
			cn.conn.Close()
			cn.alive = false
			cn.lock.Signal()

			cn.lock.L.Unlock()

			return
		}
	}
}

// isConnError indicates that error is related to dead socket.
func isConnError(err error) bool {
	if err == nil {
		return false
	}

	for _, errStr := range connErrors {
		// golang...
		if strings.Contains(err.Error(), errStr) {
			return true
		}
	}

	return false
}