This repository was archived by the owner on Dec 4, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 52
Expand file tree
/
Copy pathprocess.py
More file actions
468 lines (441 loc) · 15 KB
/
process.py
File metadata and controls
468 lines (441 loc) · 15 KB
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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
#
# Copyright 1997 - July 2008 CWI, August 2008 - 2020 MonetDB B.V.
import subprocess
import os
import sys
import time
import string
import tempfile
import copy
import atexit
import threading
import signal
if sys.version.startswith('2'):
import Queue as queue
else:
import queue
from subprocess import PIPE
try:
from subprocess import DEVNULL
except ImportError:
DEVNULL = os.open(os.devnull, os.O_RDWR)
__all__ = ['PIPE', 'DEVNULL', 'Popen', 'client', 'server']
try:
# on Windows, also make this available
from subprocess import CREATE_NEW_PROCESS_GROUP
except ImportError:
pass
else:
__all__.append('CREATE_NEW_PROCESS_GROUP')
verbose = False
def splitcommand(cmd):
'''Like string.split, except take quotes into account.'''
q = None
w = []
command = []
for c in cmd:
if q:
if c == q:
q = None
else:
w.append(c)
elif c in string.whitespace:
if w:
command.append(''.join(w))
w = []
elif c == '"' or c == "'":
q = c
else:
w.append(c)
if w:
command.append(''.join(w))
if len(command) > 1 and command[0] == 'call':
del command[0]
return command
_mal_client = splitcommand(os.getenv('MAL_CLIENT', 'mclient -lmal'))
_sql_client = splitcommand(os.getenv('SQL_CLIENT', 'mclient -lsql'))
_sql_dump = splitcommand(os.getenv('SQL_DUMP', 'msqldump -q'))
_server = splitcommand(os.getenv('MSERVER', ''))
_dbfarm = os.getenv('GDK_DBFARM', None)
_dotmonetdbfile = []
def _delfiles():
for f in _dotmonetdbfile:
try:
os.unlink(f)
except OSError:
pass
atexit.register(_delfiles)
class _BufferedPipe:
def __init__(self, fd):
self._pipe = fd
self._queue = queue.Queue()
self._eof = False
self._empty = ''
self._thread = threading.Thread(target=self._readerthread,
args=(fd, self._queue))
self._thread.setDaemon(True)
self._thread.start()
def _readerthread(self, fh, queue):
s = 0
w = 0
first = True
while True:
c = fh.read(1)
if first:
if type(c) is type(b''):
self._empty = b''
first = False
queue.put(c) # put '' if at EOF
if not c:
break
def close(self):
if self._thread:
self._thread.join()
self._thread = None
def read(self, size=-1):
if self._eof:
return self._empty
if size < 0:
self.close()
ret = []
while size != 0:
c = self._queue.get()
if c == '\r':
c = self._queue.get() # just ignore \r
ret.append(c)
if size > 0:
size -= 1
try:
# only available as of Python 2.5
self._queue.task_done()
except AttributeError:
# not essential, if not available
pass
if not c:
self._eof = True
break # EOF
return self._empty.join(ret)
def readline(self, size=-1):
ret = []
while size != 0:
c = self.read(1)
ret.append(c)
if size > 0:
size -= 1
if c == '\n' or c == self._empty:
break
return self._empty.join(ret)
class Popen(subprocess.Popen):
def __init__(self, *args, **kwargs):
self.dotmonetdbfile = None
self.isserver = False
if sys.version[:3] < '3.7':
kw = kwargs.copy()
if 'text' in kw:
kw['universal_newlines'] = kw['text']
del kw['text']
kwargs = kw
super().__init__(*args, **kwargs)
def __exit__(self, exc_type, value, traceback):
self.terminate()
self._clean_dotmonetdbfile()
super().__exit__(exc_type, value, traceback)
def __del__(self):
if self._child_created:
self.terminate()
self._clean_dotmonetdbfile()
super().__del__()
def _clean_dotmonetdbfile(self):
if self.dotmonetdbfile is not None:
try:
os.unlink(self.dotmonetdbfile)
except FileNotFoundError:
pass
try:
_dotmonetdbfile.remove(self.dotmonetdbfile)
except ValueError:
pass
self.dotmonetdbfile = None
def wait(self):
ret = super().wait()
self._clean_dotmonetdbfile()
return ret
def communicate(self, input=None):
# since we always use threads for stdout/stderr, we can just read()
stdout = None
stderr = None
if self.stdin:
if input:
try:
self.stdin.write(input)
except IOError:
pass
self.stdin.close()
if self.isserver:
try:
if os.name == 'nt':
self.send_signal(signal.CTRL_BREAK_EVENT)
else:
self.terminate()
except OSError:
pass
if self.stdout:
stdout = self.stdout.read()
self.stdout.close()
if self.stderr:
stderr = self.stderr.read()
self.stderr.close()
self.wait()
return stdout, stderr
class client(Popen):
def __init__(self, lang, args=[], stdin=None, stdout=None, stderr=None,
server=None, port=None, dbname=None, host=None,
user='monetdb', passwd='monetdb', log=False,
interactive=None, echo=None, format=None,
input=None, communicate=False, text=True):
'''Start a client process.'''
if lang == 'mal':
cmd = _mal_client[:]
elif lang == 'sql':
cmd = _sql_client[:]
elif lang == 'sqldump':
cmd = _sql_dump[:]
if verbose:
sys.stdout.write('Default client: ' + ' '.join(cmd + args) + '\n')
# no -i if input from -s or /dev/null
if '-i' in cmd and ('-s' in args or stdin is None):
cmd.remove('-i')
if interactive is not None:
if '-i' in cmd and not interactive:
cmd.remove('-i')
elif '-i' not in cmd and interactive:
cmd.append('-i')
if echo is not None:
if '-e' in cmd and not echo:
cmd.remove('-e')
elif '-e' not in cmd and echo:
cmd.append('-e')
if format is not None:
for c in cmd:
if c.startswith('-f'):
cmd.remove(c)
break
cmd.append('-f' + format)
env = None
# if server instance is specified, it provides defaults for
# database name and port
if server is not None:
if port is None:
port = server.dbport
if dbname is None:
dbname = server.dbname
if port is not None:
for i in range(len(cmd)):
if cmd[i].startswith('--port='):
del cmd[i]
break
cmd.append('--port=%d' % int(port))
if dbname is None:
dbname = os.getenv('TSTDB')
if dbname is not None:
cmd.append('--database=%s' % dbname)
if user is not None or passwd is not None:
env = copy.deepcopy(os.environ)
fd, fnam = tempfile.mkstemp(text=True)
self.dotmonetdbfile = fnam
_dotmonetdbfile.append(fnam)
if user is not None:
os.write(fd, ('user=%s\n' % user).encode('utf-8'))
if passwd is not None:
os.write(fd, ('password=%s\n' % passwd).encode('utf-8'))
os.close(fd)
env['DOTMONETDBFILE'] = fnam
if host is not None:
for i in range(len(cmd)):
if cmd[i].startswith('--host='):
del cmd[i]
break
cmd.append('--host=%s' % host)
if verbose:
sys.stdout.write('Executing: ' + ' '.join(cmd + args) + '\n')
sys.stdout.flush()
if log:
prompt = time.strftime('# %H:%M:%S > ')
cmdstr = ' '.join(cmd + args)
if hasattr(stdin, 'name'):
cmdstr += ' < "%s"' % stdin.name
sys.stdout.write('\n')
sys.stdout.write(prompt + '\n')
sys.stdout.write('%s%s\n' % (prompt, cmdstr))
sys.stdout.write(prompt + '\n')
sys.stdout.write('\n')
sys.stdout.flush()
sys.stderr.write('\n')
sys.stderr.write(prompt + '\n')
sys.stderr.write('%s%s\n' % (prompt, cmdstr))
sys.stderr.write(prompt + '\n')
sys.stderr.write('\n')
sys.stderr.flush()
if stdin is None:
# if no input provided, use /dev/null as input
stdin = open(os.devnull)
if stdout == 'PIPE':
out = PIPE
else:
out = stdout
super().__init__(cmd + args,
stdin=stdin,
stdout=out,
stderr=stderr,
shell=False,
env=env,
text=text)
if stdout == PIPE:
self.stdout = _BufferedPipe(self.stdout)
if stderr == PIPE:
self.stderr = _BufferedPipe(self.stderr)
if input is not None:
self.stdin.write(input)
if communicate:
out, err = self.communicate()
sys.stdout.write(out)
sys.stderr.write(err)
class server(Popen):
def __init__(self, args=[], stdin=None, stdout=None, stderr=None,
mapiport=None, dbname=os.getenv('TSTDB'), dbfarm=None,
dbextra=None, bufsize=0, log=False,
notrace=False, notimeout=False, ipv6=False):
'''Start a server process.'''
cmd = _server[:]
if not cmd:
cmd = ['mserver5',
'--set', ipv6 and 'mapi_listenaddr=all' or 'mapi_listenaddr=0.0.0.0',
'--set', 'gdk_nr_threads=1']
if verbose:
sys.stdout.write('Default server: ' + ' '.join(cmd + args) + '\n')
if notrace and '--trace' in cmd:
cmd.remove('--trace')
if mapiport is not None:
# make sure it's a string
mapiport = str(int(mapiport))
for i in range(len(cmd)):
if cmd[i].startswith('mapi_port='):
del cmd[i]
del cmd[i - 1]
break
usock = None
for i in range(len(cmd)):
if cmd[i].startswith('mapi_usock='):
usock = cmd[i][11:cmd[i].rfind('.')]
del cmd[i]
del cmd[i - 1]
break
cmd.append('--set')
cmd.append('mapi_port=%s' % mapiport)
if usock is not None:
cmd.append('--set')
cmd.append('mapi_usock=%s.%s' % (usock, mapiport))
for i in range(len(cmd)):
if cmd[i].startswith('--dbpath='):
dbpath = cmd[i][9:]
del cmd[i]
break
elif cmd[i] == '--dbpath':
dbpath = cmd[i+1]
del cmd[i:i+2]
break
else:
dbpath = None
if dbpath is not None:
if dbfarm is None:
dbfarm = os.path.dirname(dbpath)
if dbname is None:
dbname = os.path.basename(dbpath)
if dbname is None:
dbname = 'demo'
if dbfarm is None:
if _dbfarm is None:
raise RuntimeError('no dbfarm known')
dbfarm = _dbfarm
dbpath = os.path.join(dbfarm, dbname)
cmd.append('--dbpath=%s' % dbpath)
for i in range(len(cmd)):
if cmd[i].startswith('--dbextra='):
dbextra_path = cmd[i][10:]
del cmd[i]
break
elif cmd[i] == '--dbextra':
dbextra_path = cmd[i+1]
del cmd[i:i+2]
break
else:
dbextra_path = None
if dbextra is not None:
dbextra_path = dbextra
if dbextra_path is not None:
cmd.append('--dbextra=%s' % dbextra_path)
if verbose:
sys.stdout.write('Executing: ' + ' '.join(cmd + args) + '\n')
sys.stdout.flush()
for i in range(len(args)):
if args[i] == '--set' and i+1 < len(args):
s = args[i+1].partition('=')[0]
for j in range(len(cmd)):
if cmd[j] == '--set' and j+1 < len(cmd) and cmd[j+1].startswith(s + '='):
del cmd[j:j+2]
break
if log:
prompt = time.strftime('# %H:%M:%S > ')
cmdstr = ' '.join(cmd + args)
if hasattr(stdin, 'name'):
cmdstr += ' < "%s"' % stdin.name
sys.stdout.write('\n')
sys.stdout.write(prompt + '\n')
sys.stdout.write('%s%s\n' % (prompt, cmdstr))
sys.stdout.write(prompt + '\n')
sys.stdout.write('\n')
sys.stdout.flush()
sys.stderr.write('\n')
sys.stderr.write(prompt + '\n')
sys.stderr.write('%s%s\n' % (prompt, cmdstr))
sys.stderr.write(prompt + '\n')
sys.stderr.write('\n')
sys.stderr.flush()
started = os.path.join(dbpath, '.started')
try:
os.unlink(started)
except OSError:
pass
if os.name == 'nt':
kw = {'creationflags': CREATE_NEW_PROCESS_GROUP}
else:
kw = {}
super().__init__(cmd + args,
stdin=stdin,
stdout=stdout,
stderr=stderr,
shell=False,
text=True,
bufsize=bufsize,
**kw)
self.isserver = True
if stderr == PIPE:
self.stderr = _BufferedPipe(self.stderr)
if stdout == PIPE:
self.stdout = _BufferedPipe(self.stdout)
# store database name and port in the returned instance for the
# client to pick up
self.dbname = dbname
self.dbport = mapiport
while True:
self.poll()
if self.returncode is not None:
# process exited already
break
if os.path.exists(started):
# server is ready
break
time.sleep(0.001)