File: tarantool_connection.py

package info (click to toggle)
tarantool 1.7.2.385.g952d79e-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 21,556 kB
  • ctags: 28,405
  • sloc: ansic: 180,313; cpp: 26,044; sh: 15,513; python: 4,893; makefile: 1,412
file content (183 lines) | stat: -rw-r--r-- 5,929 bytes parent folder | download
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
181
182
183
__author__ = "Konstantin Osipov <kostja.osipov@gmail.com>"

# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
#    notice, this list of conditions and the following disclaimer in the
#    documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY AUTHOR AND CONTRIBUTORS ``AS IS'' AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED.  IN NO EVENT SHALL AUTHOR OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.

import sys
import ctypes
import errno
import re
import socket
import gc
from contextlib import contextmanager

import gevent
from gevent import socket as gsocket

from connpool import ConnectionPool
from test import TestRunGreenlet


class TarantoolPool(ConnectionPool):
    def __init__(self, host, port, *args, **kwargs):
        self.host = host
        self.port = port
        super(TarantoolPool, self).__init__(*args, **kwargs)

    def _new_connection(self):
        result = None
        if self.host == 'unix/' or re.search(r'^/', str(self.port)):
            result = gsocket.socket(gsocket.AF_UNIX, gsocket.SOCK_STREAM)
            result.connect(self.port)
        else:
            result = gsocket.create_connection((self.host, self.port))
            result.setsockopt(gsocket.SOL_TCP, gsocket.TCP_NODELAY, 1)
        return result

    def _addOne(self):
        stime = 0.1
        while True:
            try:
                c = self._new_connection()
            except gsocket.error:
                c = None
            if c:
                break
            gevent.sleep(stime)
            if stime < 400:
                stime *= 2
        self.conn.append(c)
        self.lock.release()

    @contextmanager
    def get(self):
        self.lock.acquire()

        try:
            c = self.conn.pop()
            yield c
        except self.exc_classes:
            greenlet = TestRunGreenlet(self._addOne)
            greenlet.start_later(1)
            raise
        except:
            self.conn.append(c)
            self.lock.release()
            raise
        else:
            self.conn.append(c)
            self.lock.release()

    def close_all(self):
        self.conn.clear()

class TarantoolConnection(object):
    @property
    def uri(self):
        if self.host == 'unix/' or re.search(r'^/', str(self.port)):
            return self.port
        else:
            return self.host+':'+str(self.port)

    def __init__(self, host, port):
        self.host = host
        self.port = port
        self.is_connected = False

    def connect(self):
        if self.host == 'unix/' or re.search(r'^/', str(self.port)):
            self.socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
            self.socket.connect(self.port)
        else:
            self.socket = socket.create_connection((self.host, self.port))
            self.socket.setsockopt(socket.SOL_TCP, socket.TCP_NODELAY, 1)
        self.is_connected = True

    def disconnect(self):
        if self.is_connected:
            self.socket.close()
            self.is_connected = False

    def reconnect(self):
        self.disconnect()
        self.connect()

    def opt_reconnect(self):
        """ On a socket which was disconnected, recv of 0 bytes immediately
            returns with no data. On a socket which is alive, it returns EAGAIN.
            Make use of this property and detect whether or not the socket is
            dead. Reconnect a dead socket, do nothing if the socket is good."""
        try:
            if not self.is_connected or self.socket.recv(
                    1, socket.MSG_DONTWAIT | socket.MSG_PEEK) == '':
                self.reconnect()
        except socket.error as e:
            if e.errno == errno.EAGAIN:
                pass
            else:
                self.reconnect()

    def clone(self):
        return type(self)(self.host, self.port)

    def execute(self, command, silent=True):
        self.opt_reconnect()
        return self.execute_no_reconnect(command, silent)

    def __enter__(self):
        self.connect()
        return self

    def __exit__(self, type, value, tb):
        self.disconnect()

    def __call__(self, command, silent=False, simple=False):
        return self.execute(command, silent)

class TarantoolAsyncConnection(TarantoolConnection):
    pool = TarantoolPool

    def __init__(self, host, port):
        self.host = host
        self.port = port
        self.connections = None
        self.is_connected = False
        libc = ctypes.CDLL(ctypes.util.find_library('c'), use_errno=True)
        self._sys_recv = libc.recv

    @property
    def socket(self):
        with self.connections.get() as c:
            result = c
        return result

    def connect(self):
        self.connections = self.pool(self.host, self.port, 3)
        self.is_connected = True

    def disconnect(self):
        if self.is_connected:
            self.connections.close_all()
            self.is_connected = False

    def execute(self, command, silent=True):
        return self.execute_no_reconnect(command, silent)