Skip to content

Commit 9b6253d

Browse files
author
Konstantin Belyavskiy
committed
Implement reconnection strategy class
Add built-in reconnect strategy class based on Round-Robin alg. @params: - peers - nattempts Return next connection or an error if all URIs are unavailable. Closes #106
1 parent cbb09e0 commit 9b6253d

File tree

1 file changed

+104
-0
lines changed

1 file changed

+104
-0
lines changed

client.py

Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,104 @@
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.const import (
9+
SOCKET_TIMEOUT,
10+
RECONNECT_MAX_ATTEMPTS,
11+
RECONNECT_DELAY,
12+
)
13+
14+
from tarantool.error import (
15+
Error,
16+
DatabaseError,
17+
NetworkError,
18+
NetworkWarning,
19+
)
20+
21+
from tarantool.schema import (
22+
Schema,
23+
SchemaError
24+
)
25+
26+
from tarantool.utils import (
27+
ENCODING_DEFAULT
28+
)
29+
30+
class RoundRobinStrategy(object):
31+
def __init__(self, addrs):
32+
self.addrs = addrs
33+
self.pos = 0
34+
35+
def getnext(self):
36+
tmp = self.pos
37+
self.pos = (self.pos + 1) % len(self.addrs)
38+
return self.addrs[tmp]
39+
40+
class MeshConnection(Connection):
41+
def __init__(self, addrs, user, password, connect_now, encoding, Strategy):
42+
self.nattempts = 2 * len(addrs) + 1
43+
self.Strategy = Strategy(addrs)
44+
addr = self.Strategy.getnext()
45+
host = addrs[0]['host']
46+
port = addrs[0]['port']
47+
super(MeshConnection, self).__init__(host=host,
48+
port=port,
49+
user=user,
50+
password=password,
51+
connect_now=connect_now,
52+
encoding=encoding)
53+
54+
def _opt_reconnect(self):
55+
nattempts = self.nattempts
56+
while nattempts > 0:
57+
try:
58+
super(MeshConnection, self)._opt_reconnect()
59+
break
60+
except NetworkError:
61+
nattempts -= 1
62+
addr = self.Strategy.getnext()
63+
self.host = addr['host']
64+
self.port = addr['port']
65+
else:
66+
raise NetworkError
67+
68+
def connectmesh(addrs=({'host': 'localhost', 'port': 3301},), user=None,
69+
password=None, connect_now=True, encoding=ENCODING_DEFAULT,
70+
Strategy=RoundRobinStrategy):
71+
'''
72+
Create a connection to the Tarantool server.
73+
74+
:param str host: Server hostname or IP-address
75+
:param int port: Server port
76+
77+
:rtype: :class:`~tarantool.connection.Connection`
78+
79+
:raise: `NetworkError`
80+
'''
81+
82+
return MeshConnection(addrs=addrs,
83+
user=user,
84+
password=password,
85+
connect_now=connect_now,
86+
encoding=encoding,
87+
Strategy=Strategy)
88+
89+
addrs=(
90+
{'host': 'localhost', 'port': 3301},
91+
{'host': 'localhost', 'port': 3304},
92+
)
93+
94+
con = connectmesh(addrs)
95+
96+
while True:
97+
try:
98+
print con.ping()
99+
except NetworkError:
100+
print 'NetworkError !'
101+
break
102+
except Exception as e:
103+
print e
104+
time.sleep(1)

0 commit comments

Comments
 (0)