-
Notifications
You must be signed in to change notification settings - Fork 46
/
Copy pathtarantool_server.py
220 lines (183 loc) · 6.44 KB
/
tarantool_server.py
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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
# -*- coding: utf-8 -*-
import os
import os.path
import errno
import shlex
import random
import socket
import tempfile
import time
import shutil
import subprocess
from .tarantool_admin import TarantoolAdmin
def check_port(port, rais=True):
try:
sock = socket.create_connection(("localhost", port))
except socket.error:
return True
if rais:
raise RuntimeError("The server is already running on port {0}".format(port))
return False
def find_port(port = None):
if port is None:
port = random.randrange(3300, 9999)
while port < 9999:
if check_port(port, False):
return port
port += 1
return find_port(3300)
class RunnerException(object):
pass
class TarantoolServer(object):
default_tarantool = {
"bin": "tarantool",
"logfile": "tarantool.log",
"init": "init.lua"}
default_cfg = {
"custom_proc_title": "\"tarantool-python testing\"",
"memtx_memory": 0.5 * 1024**3, # 0.5 GiB
"pid_file": "\"box.pid\""}
@property
def logfile_path(self):
return os.path.join(self.vardir, self.default_tarantool['logfile'])
@property
def cfgfile_path(self):
return os.path.join(self.vardir, self.default_tarantool['config'])
@property
def script_path(self):
return os.path.join(self.vardir, self.default_tarantool['init'])
@property
def script_dst(self):
return os.path.join(self.vardir, os.path.basename(self.script))
@property
def script(self):
if not hasattr(self, '_script'): self._script = None
return self._script
@script.setter
def script(self, val):
if val is None:
if hasattr(self, '_script'):
delattr(self, '_script')
return
self._script = os.path.abspath(val)
@property
def binary(self):
if not hasattr(self, '_binary'):
self._binary = self.find_exe()
return self._binary
@property
def _admin(self):
if not hasattr(self, 'admin'):
self.admin = None
return self.admin
@_admin.setter
def _admin(self, port):
try:
int(port)
except ValueError:
raise ValueError("Bad port number: '%s'" % port)
if hasattr(self, 'admin'):
del self.admin
self.admin = TarantoolAdmin('localhost', port)
@property
def log_des(self):
if not hasattr(self, '_log_des'):
self._log_des = open(self.logfile_path, 'a')
return self._log_des
@log_des.deleter
def log_des(self):
if not hasattr(self, '_log_des'):
return
if not self._log_des.closed:
self._log_des.close()
delattr(self, '_log_des')
def __new__(cls):
if os.name == 'nt':
from .remote_tarantool_server import RemoteTarantoolServer
return RemoteTarantoolServer()
return super(TarantoolServer, cls).__new__(cls)
def __init__(self):
os.popen('ulimit -c unlimited')
self.host = 'localhost'
self.args = {}
self.args['primary'] = find_port()
self.args['admin'] = find_port(self.args['primary'] + 1)
self._admin = self.args['admin']
self.vardir = tempfile.mkdtemp(prefix='var_', dir=os.getcwd())
self.find_exe()
self.process = None
def find_exe(self):
if 'TARANTOOL_BOX_PATH' in os.environ:
os.environ["PATH"] = os.environ["TARANTOOL_BOX_PATH"] + os.pathsep + os.environ["PATH"]
for _dir in os.environ["PATH"].split(os.pathsep):
exe = os.path.join(_dir, self.default_tarantool["bin"])
if os.access(exe, os.X_OK):
return os.path.abspath(exe)
raise RuntimeError("Can't find server executable in " + os.environ["PATH"])
def generate_configuration(self):
os.putenv("PRIMARY_PORT", str(self.args['primary']))
os.putenv("ADMIN_PORT", str(self.args['admin']))
def prepare_args(self):
return shlex.split(self.binary if not self.script else self.script_dst)
def wait_until_started(self):
""" Wait until server is started.
Server consists of two parts:
1) wait until server is listening on sockets
2) wait until server tells us his status
"""
while True:
try:
temp = TarantoolAdmin('localhost', self.args['admin'])
while True:
ans = temp('box.info.status')[0]
if ans in ('running', 'hot_standby', 'orphan') or ans.startswith('replica'):
return True
elif ans in ('loading',):
continue
else:
raise Exception("Strange output for `box.info.status`: %s" % (ans))
except socket.error as e:
if e.errno == errno.ECONNREFUSED:
time.sleep(0.1)
continue
raise
def start(self):
# Main steps for running Tarantool\Box
# * Find binary file --DONE(find_exe -> binary)
# * Create vardir --DONE(__init__)
# * Generate cfgfile --DONE(generate_configuration)
# * (MAYBE) Copy init.lua --INSIDE
# * Concatenate arguments and
# start Tarantool\Box --DONE(prepare_args)
# * Wait unitl Tarantool\Box
# started --DONE(wait_until_started)
self.generate_configuration()
if self.script:
shutil.copy(self.script, self.script_dst)
os.chmod(self.script_dst, 0o777)
args = self.prepare_args()
self.process = subprocess.Popen(args,
cwd = self.vardir,
stdout=self.log_des,
stderr=self.log_des)
self.wait_until_started()
def stop(self):
self.admin.disconnect()
if self.process.poll() is None:
self.process.terminate()
self.process.wait()
def restart(self):
self.stop()
self.start()
def clean(self):
if os.path.isdir(self.vardir):
shutil.rmtree(self.vardir)
def __del__(self):
self.stop()
self.clean()
def touch_lock(self):
# A stub method to be compatible with
# RemoteTarantoolServer.
pass
def is_started(self):
return self.process is not None