Skip to content

Commit ff0f4af

Browse files
author
Konstantin Belyavskiy
committed
Implement reconnection strategy class
Extend base Connection class to support a list of nodes and an optional Strategy parameter to choose next item from this list. Add built-in reconnect strategy class based on Round-Robin alg. @params: - peers Return next connection or an error if all URIs are unavailable. Closes #106
1 parent cbb09e0 commit ff0f4af

File tree

1 file changed

+85
-0
lines changed

1 file changed

+85
-0
lines changed

client.py

Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
#!/usr/bin/env python
2+
# -*- coding: utf-8 -*-
3+
4+
import sys
5+
import time
6+
7+
from tarantool.connection import Connection
8+
from tarantool.error import NetworkError
9+
from tarantool.utils import ENCODING_DEFAULT
10+
11+
class RoundRobinStrategy(object):
12+
def __init__(self, addrs):
13+
self.addrs = addrs
14+
self.pos = 0
15+
16+
def getnext(self):
17+
tmp = self.pos
18+
self.pos = (self.pos + 1) % len(self.addrs)
19+
return self.addrs[tmp]
20+
21+
class MeshConnection(Connection):
22+
def __init__(self, addrs, user, password, connect_now, encoding, Strategy):
23+
self.nattempts = 2 * len(addrs) + 1
24+
self.Strategy = Strategy(addrs)
25+
addr = self.Strategy.getnext()
26+
host = addrs[0]['host']
27+
port = addrs[0]['port']
28+
super(MeshConnection, self).__init__(host=host,
29+
port=port,
30+
user=user,
31+
password=password,
32+
connect_now=connect_now,
33+
encoding=encoding)
34+
35+
def _opt_reconnect(self):
36+
nattempts = self.nattempts
37+
while nattempts > 0:
38+
try:
39+
super(MeshConnection, self)._opt_reconnect()
40+
break
41+
except NetworkError:
42+
nattempts -= 1
43+
addr = self.Strategy.getnext()
44+
self.host = addr['host']
45+
self.port = addr['port']
46+
else:
47+
raise NetworkError
48+
49+
def connectmesh(addrs=({'host': 'localhost', 'port': 3301},), user=None,
50+
password=None, connect_now=True, encoding=ENCODING_DEFAULT,
51+
Strategy=RoundRobinStrategy):
52+
'''
53+
Create a connection to the Tarantool server.
54+
55+
:param str host: Server hostname or IP-address
56+
:param int port: Server port
57+
58+
:rtype: :class:`~tarantool.connection.Connection`
59+
60+
:raise: `NetworkError`
61+
'''
62+
63+
return MeshConnection(addrs=addrs,
64+
user=user,
65+
password=password,
66+
connect_now=connect_now,
67+
encoding=encoding,
68+
Strategy=Strategy)
69+
70+
addrs=(
71+
{'host': 'localhost', 'port': 3301},
72+
{'host': 'localhost', 'port': 3304},
73+
)
74+
75+
con = connectmesh(addrs)
76+
77+
while True:
78+
try:
79+
print con.ping()
80+
except NetworkError:
81+
print 'NetworkError !'
82+
break
83+
except Exception as e:
84+
print e
85+
time.sleep(1)

0 commit comments

Comments
 (0)