Merge branch '13803-oj-gem-malloc-bug'
[arvados.git] / sdk / python / tests / run_test_server.py
1 # Copyright (C) The Arvados Authors. All rights reserved.
2 #
3 # SPDX-License-Identifier: Apache-2.0
4
5 from __future__ import print_function
6 from __future__ import division
7 from builtins import str
8 from builtins import range
9 import argparse
10 import atexit
11 import errno
12 import glob
13 import httplib2
14 import os
15 import pipes
16 import random
17 import re
18 import shutil
19 import signal
20 import socket
21 import string
22 import subprocess
23 import sys
24 import tempfile
25 import time
26 import unittest
27 import yaml
28
29 MY_DIRNAME = os.path.dirname(os.path.realpath(__file__))
30 if __name__ == '__main__' and os.path.exists(
31       os.path.join(MY_DIRNAME, '..', 'arvados', '__init__.py')):
32     # We're being launched to support another test suite.
33     # Add the Python SDK source to the library path.
34     sys.path.insert(1, os.path.dirname(MY_DIRNAME))
35
36 import arvados
37 import arvados.config
38
39 ARVADOS_DIR = os.path.realpath(os.path.join(MY_DIRNAME, '../../..'))
40 SERVICES_SRC_DIR = os.path.join(ARVADOS_DIR, 'services')
41 if 'GOPATH' in os.environ:
42     # Add all GOPATH bin dirs to PATH -- but insert them after the
43     # ruby gems bin dir, to ensure "bundle" runs the Ruby bundler
44     # command, not the golang.org/x/tools/cmd/bundle command.
45     gopaths = os.environ['GOPATH'].split(':')
46     addbins = [os.path.join(path, 'bin') for path in gopaths]
47     newbins = []
48     for path in os.environ['PATH'].split(':'):
49         newbins.append(path)
50         if os.path.exists(os.path.join(path, 'bundle')):
51             newbins += addbins
52             addbins = []
53     newbins += addbins
54     os.environ['PATH'] = ':'.join(newbins)
55
56 TEST_TMPDIR = os.path.join(ARVADOS_DIR, 'tmp')
57 if not os.path.exists(TEST_TMPDIR):
58     os.mkdir(TEST_TMPDIR)
59
60 my_api_host = None
61 _cached_config = {}
62 _cached_db_config = {}
63
64 def find_server_pid(PID_PATH, wait=10):
65     now = time.time()
66     timeout = now + wait
67     good_pid = False
68     while (not good_pid) and (now <= timeout):
69         time.sleep(0.2)
70         try:
71             with open(PID_PATH, 'r') as f:
72                 server_pid = int(f.read())
73             good_pid = (os.kill(server_pid, 0) is None)
74         except EnvironmentError:
75             good_pid = False
76         now = time.time()
77
78     if not good_pid:
79         return None
80
81     return server_pid
82
83 def kill_server_pid(pidfile, wait=10, passenger_root=False):
84     # Must re-import modules in order to work during atexit
85     import os
86     import signal
87     import subprocess
88     import time
89
90     now = time.time()
91     startTERM = now
92     deadline = now + wait
93
94     if passenger_root:
95         # First try to shut down nicely
96         restore_cwd = os.getcwd()
97         os.chdir(passenger_root)
98         subprocess.call([
99             'bundle', 'exec', 'passenger', 'stop', '--pid-file', pidfile])
100         os.chdir(restore_cwd)
101         # Use up to half of the +wait+ period waiting for "passenger
102         # stop" to work. If the process hasn't exited by then, start
103         # sending TERM signals.
104         startTERM += wait//2
105
106     server_pid = None
107     while now <= deadline and server_pid is None:
108         try:
109             with open(pidfile, 'r') as f:
110                 server_pid = int(f.read())
111         except IOError:
112             # No pidfile = nothing to kill.
113             return
114         except ValueError as error:
115             # Pidfile exists, but we can't parse it. Perhaps the
116             # server has created the file but hasn't written its PID
117             # yet?
118             print("Parse error reading pidfile {}: {}".format(pidfile, error),
119                   file=sys.stderr)
120             time.sleep(0.1)
121             now = time.time()
122
123     while now <= deadline:
124         try:
125             exited, _ = os.waitpid(server_pid, os.WNOHANG)
126             if exited > 0:
127                 _remove_pidfile(pidfile)
128                 return
129         except OSError:
130             # already exited, or isn't our child process
131             pass
132         try:
133             if now >= startTERM:
134                 os.kill(server_pid, signal.SIGTERM)
135                 print("Sent SIGTERM to {} ({})".format(server_pid, pidfile),
136                       file=sys.stderr)
137         except OSError as error:
138             if error.errno == errno.ESRCH:
139                 # Thrown by os.getpgid() or os.kill() if the process
140                 # does not exist, i.e., our work here is done.
141                 _remove_pidfile(pidfile)
142                 return
143             raise
144         time.sleep(0.1)
145         now = time.time()
146
147     print("Server PID {} ({}) did not exit, giving up after {}s".
148           format(server_pid, pidfile, wait),
149           file=sys.stderr)
150
151 def _remove_pidfile(pidfile):
152     try:
153         os.unlink(pidfile)
154     except:
155         if os.path.lexists(pidfile):
156             raise
157
158 def find_available_port():
159     """Return an IPv4 port number that is not in use right now.
160
161     We assume whoever needs to use the returned port is able to reuse
162     a recently used port without waiting for TIME_WAIT (see
163     SO_REUSEADDR / SO_REUSEPORT).
164
165     Some opportunity for races here, but it's better than choosing
166     something at random and not checking at all. If all of our servers
167     (hey Passenger) knew that listening on port 0 was a thing, the OS
168     would take care of the races, and this wouldn't be needed at all.
169     """
170
171     sock = socket.socket()
172     sock.bind(('0.0.0.0', 0))
173     port = sock.getsockname()[1]
174     sock.close()
175     return port
176
177 def _wait_until_port_listens(port, timeout=10, warn=True):
178     """Wait for a process to start listening on the given port.
179
180     If nothing listens on the port within the specified timeout (given
181     in seconds), print a warning on stderr before returning.
182     """
183     try:
184         subprocess.check_output(['which', 'lsof'])
185     except subprocess.CalledProcessError:
186         print("WARNING: No `lsof` -- cannot wait for port to listen. "+
187               "Sleeping 0.5 and hoping for the best.",
188               file=sys.stderr)
189         time.sleep(0.5)
190         return
191     deadline = time.time() + timeout
192     while time.time() < deadline:
193         try:
194             subprocess.check_output(
195                 ['lsof', '-t', '-i', 'tcp:'+str(port)])
196         except subprocess.CalledProcessError:
197             time.sleep(0.1)
198             continue
199         return True
200     if warn:
201         print(
202             "WARNING: Nothing is listening on port {} (waited {} seconds).".
203             format(port, timeout),
204             file=sys.stderr)
205     return False
206
207 def _logfilename(label):
208     """Set up a labelled log file, and return a path to write logs to.
209
210     Normally, the returned path is {tmpdir}/{label}.log.
211
212     In debug mode, logs are also written to stderr, with [label]
213     prepended to each line. The returned path is a FIFO.
214
215     +label+ should contain only alphanumerics: it is also used as part
216     of the FIFO filename.
217
218     """
219     logfilename = os.path.join(TEST_TMPDIR, label+'.log')
220     if not os.environ.get('ARVADOS_DEBUG', ''):
221         return logfilename
222     fifo = os.path.join(TEST_TMPDIR, label+'.fifo')
223     try:
224         os.remove(fifo)
225     except OSError as error:
226         if error.errno != errno.ENOENT:
227             raise
228     os.mkfifo(fifo, 0o700)
229     stdbuf = ['stdbuf', '-i0', '-oL', '-eL']
230     # open(fifo, 'r') would block waiting for someone to open the fifo
231     # for writing, so we need a separate cat process to open it for
232     # us.
233     cat = subprocess.Popen(
234         stdbuf+['cat', fifo],
235         stdin=open('/dev/null'),
236         stdout=subprocess.PIPE)
237     tee = subprocess.Popen(
238         stdbuf+['tee', '-a', logfilename],
239         stdin=cat.stdout,
240         stdout=subprocess.PIPE)
241     subprocess.Popen(
242         stdbuf+['sed', '-e', 's/^/['+label+'] /'],
243         stdin=tee.stdout,
244         stdout=sys.stderr)
245     return fifo
246
247 def run(leave_running_atexit=False):
248     """Ensure an API server is running, and ARVADOS_API_* env vars have
249     admin credentials for it.
250
251     If ARVADOS_TEST_API_HOST is set, a parent process has started a
252     test server for us to use: we just need to reset() it using the
253     admin token fixture.
254
255     If a previous call to run() started a new server process, and it
256     is still running, we just need to reset() it to fixture state and
257     return.
258
259     If neither of those options work out, we'll really start a new
260     server.
261     """
262     global my_api_host
263
264     # Delete cached discovery documents.
265     #
266     # This will clear cached docs that belong to other processes (like
267     # concurrent test suites) even if they're still running. They should
268     # be able to tolerate that.
269     for fn in glob.glob(os.path.join(
270             str(arvados.http_cache('discovery')),
271             '*,arvados,v1,rest,*')):
272         os.unlink(fn)
273
274     pid_file = _pidfile('api')
275     pid_file_ok = find_server_pid(pid_file, 0)
276
277     existing_api_host = os.environ.get('ARVADOS_TEST_API_HOST', my_api_host)
278     if existing_api_host and pid_file_ok:
279         if existing_api_host == my_api_host:
280             try:
281                 return reset()
282             except:
283                 # Fall through to shutdown-and-start case.
284                 pass
285         else:
286             # Server was provided by parent. Can't recover if it's
287             # unresettable.
288             return reset()
289
290     # Before trying to start up our own server, call stop() to avoid
291     # "Phusion Passenger Standalone is already running on PID 12345".
292     # (If we've gotten this far, ARVADOS_TEST_API_HOST isn't set, so
293     # we know the server is ours to kill.)
294     stop(force=True)
295
296     restore_cwd = os.getcwd()
297     api_src_dir = os.path.join(SERVICES_SRC_DIR, 'api')
298     os.chdir(api_src_dir)
299
300     # Either we haven't started a server of our own yet, or it has
301     # died, or we have lost our credentials, or something else is
302     # preventing us from calling reset(). Start a new one.
303
304     if not os.path.exists('tmp'):
305         os.makedirs('tmp')
306
307     if not os.path.exists('tmp/api'):
308         os.makedirs('tmp/api')
309
310     if not os.path.exists('tmp/logs'):
311         os.makedirs('tmp/logs')
312
313     # Install the git repository fixtures.
314     gitdir = os.path.join(SERVICES_SRC_DIR, 'api', 'tmp', 'git')
315     gittarball = os.path.join(SERVICES_SRC_DIR, 'api', 'test', 'test.git.tar')
316     if not os.path.isdir(gitdir):
317         os.makedirs(gitdir)
318     subprocess.check_output(['tar', '-xC', gitdir, '-f', gittarball])
319
320     # The nginx proxy isn't listening here yet, but we need to choose
321     # the wss:// port now so we can write the API server config file.
322     wss_port = find_available_port()
323     _setport('wss', wss_port)
324
325     port = find_available_port()
326     env = os.environ.copy()
327     env['RAILS_ENV'] = 'test'
328     env['ARVADOS_TEST_WSS_PORT'] = str(wss_port)
329     env.pop('ARVADOS_WEBSOCKETS', None)
330     env.pop('ARVADOS_TEST_API_HOST', None)
331     env.pop('ARVADOS_API_HOST', None)
332     env.pop('ARVADOS_API_HOST_INSECURE', None)
333     env.pop('ARVADOS_API_TOKEN', None)
334     start_msg = subprocess.check_output(
335         ['bundle', 'exec',
336          'passenger', 'start', '-d', '-p{}'.format(port),
337          '--pid-file', pid_file,
338          '--log-file', os.path.join(os.getcwd(), 'log/test.log'),
339          '--ssl',
340          '--ssl-certificate', 'tmp/self-signed.pem',
341          '--ssl-certificate-key', 'tmp/self-signed.key'],
342         env=env)
343
344     if not leave_running_atexit:
345         atexit.register(kill_server_pid, pid_file, passenger_root=api_src_dir)
346
347     match = re.search(r'Accessible via: https://(.*?)/', start_msg)
348     if not match:
349         raise Exception(
350             "Passenger did not report endpoint: {}".format(start_msg))
351     my_api_host = match.group(1)
352     os.environ['ARVADOS_API_HOST'] = my_api_host
353
354     # Make sure the server has written its pid file and started
355     # listening on its TCP port
356     find_server_pid(pid_file)
357     _wait_until_port_listens(port)
358
359     reset()
360     os.chdir(restore_cwd)
361
362 def reset():
363     """Reset the test server to fixture state.
364
365     This resets the ARVADOS_TEST_API_HOST provided by a parent process
366     if any, otherwise the server started by run().
367
368     It also resets ARVADOS_* environment vars to point to the test
369     server with admin credentials.
370     """
371     existing_api_host = os.environ.get('ARVADOS_TEST_API_HOST', my_api_host)
372     token = auth_token('admin')
373     httpclient = httplib2.Http(ca_certs=os.path.join(
374         SERVICES_SRC_DIR, 'api', 'tmp', 'self-signed.pem'))
375     httpclient.request(
376         'https://{}/database/reset'.format(existing_api_host),
377         'POST',
378         headers={'Authorization': 'OAuth2 {}'.format(token)})
379     os.environ['ARVADOS_API_HOST_INSECURE'] = 'true'
380     os.environ['ARVADOS_API_TOKEN'] = token
381     if _wait_until_port_listens(_getport('controller-ssl'), timeout=0.5, warn=False):
382         os.environ['ARVADOS_API_HOST'] = '0.0.0.0:'+str(_getport('controller-ssl'))
383     else:
384         os.environ['ARVADOS_API_HOST'] = existing_api_host
385
386 def stop(force=False):
387     """Stop the API server, if one is running.
388
389     If force==False, kill it only if we started it ourselves. (This
390     supports the use case where a Python test suite calls run(), but
391     run() just uses the ARVADOS_TEST_API_HOST provided by the parent
392     process, and the test suite cleans up after itself by calling
393     stop(). In this case the test server provided by the parent
394     process should be left alone.)
395
396     If force==True, kill it even if we didn't start it
397     ourselves. (This supports the use case in __main__, where "run"
398     and "stop" happen in different processes.)
399     """
400     global my_api_host
401     if force or my_api_host is not None:
402         kill_server_pid(_pidfile('api'))
403         my_api_host = None
404
405 def run_controller():
406     if 'ARVADOS_TEST_PROXY_SERVICES' in os.environ:
407         return
408     stop_controller()
409     rails_api_port = int(string.split(os.environ.get('ARVADOS_TEST_API_HOST', my_api_host), ':')[-1])
410     port = find_available_port()
411     conf = os.path.join(TEST_TMPDIR, 'arvados.yml')
412     with open(conf, 'w') as f:
413         f.write("""
414 Clusters:
415   zzzzz:
416     NodeProfiles:
417       "*":
418         "arvados-controller":
419           Listen: ":{}"
420         "arvados-api-server":
421           Listen: ":{}"
422           TLS: true
423         """.format(port, rails_api_port))
424     logf = open(_logfilename('controller'), 'a')
425     controller = subprocess.Popen(
426         ["arvados-server", "controller", "-config", conf],
427         stdin=open('/dev/null'), stdout=logf, stderr=logf, close_fds=True)
428     with open(_pidfile('controller'), 'w') as f:
429         f.write(str(controller.pid))
430     _wait_until_port_listens(port)
431     _setport('controller', port)
432     return port
433
434 def stop_controller():
435     if 'ARVADOS_TEST_PROXY_SERVICES' in os.environ:
436         return
437     kill_server_pid(_pidfile('controller'))
438
439 def run_ws():
440     if 'ARVADOS_TEST_PROXY_SERVICES' in os.environ:
441         return
442     stop_ws()
443     port = find_available_port()
444     conf = os.path.join(TEST_TMPDIR, 'ws.yml')
445     with open(conf, 'w') as f:
446         f.write("""
447 Client:
448   APIHost: {}
449   Insecure: true
450 Listen: :{}
451 LogLevel: {}
452 Postgres:
453   host: {}
454   dbname: {}
455   user: {}
456   password: {}
457   sslmode: require
458         """.format(os.environ['ARVADOS_API_HOST'],
459                    port,
460                    ('info' if os.environ.get('ARVADOS_DEBUG', '') in ['','0'] else 'debug'),
461                    _dbconfig('host'),
462                    _dbconfig('database'),
463                    _dbconfig('username'),
464                    _dbconfig('password')))
465     logf = open(_logfilename('ws'), 'a')
466     ws = subprocess.Popen(
467         ["ws", "-config", conf],
468         stdin=open('/dev/null'), stdout=logf, stderr=logf, close_fds=True)
469     with open(_pidfile('ws'), 'w') as f:
470         f.write(str(ws.pid))
471     _wait_until_port_listens(port)
472     _setport('ws', port)
473     return port
474
475 def stop_ws():
476     if 'ARVADOS_TEST_PROXY_SERVICES' in os.environ:
477         return
478     kill_server_pid(_pidfile('ws'))
479
480 def _start_keep(n, keep_args):
481     keep0 = tempfile.mkdtemp()
482     port = find_available_port()
483     keep_cmd = ["keepstore",
484                 "-volume={}".format(keep0),
485                 "-listen=:{}".format(port),
486                 "-pid="+_pidfile('keep{}'.format(n))]
487
488     for arg, val in keep_args.items():
489         keep_cmd.append("{}={}".format(arg, val))
490
491     logf = open(_logfilename('keep{}'.format(n)), 'a')
492     kp0 = subprocess.Popen(
493         keep_cmd, stdin=open('/dev/null'), stdout=logf, stderr=logf, close_fds=True)
494
495     with open(_pidfile('keep{}'.format(n)), 'w') as f:
496         f.write(str(kp0.pid))
497
498     with open("{}/keep{}.volume".format(TEST_TMPDIR, n), 'w') as f:
499         f.write(keep0)
500
501     _wait_until_port_listens(port)
502
503     return port
504
505 def run_keep(blob_signing_key=None, enforce_permissions=False, num_servers=2):
506     stop_keep(num_servers)
507
508     keep_args = {}
509     if not blob_signing_key:
510         blob_signing_key = 'zfhgfenhffzltr9dixws36j1yhksjoll2grmku38mi7yxd66h5j4q9w4jzanezacp8s6q0ro3hxakfye02152hncy6zml2ed0uc'
511     with open(os.path.join(TEST_TMPDIR, "keep.blob_signing_key"), "w") as f:
512         keep_args['-blob-signing-key-file'] = f.name
513         f.write(blob_signing_key)
514     keep_args['-enforce-permissions'] = str(enforce_permissions).lower()
515     with open(os.path.join(TEST_TMPDIR, "keep.data-manager-token-file"), "w") as f:
516         keep_args['-data-manager-token-file'] = f.name
517         f.write(auth_token('data_manager'))
518     keep_args['-never-delete'] = 'false'
519
520     api = arvados.api(
521         version='v1',
522         host=os.environ['ARVADOS_API_HOST'],
523         token=os.environ['ARVADOS_API_TOKEN'],
524         insecure=True)
525
526     for d in api.keep_services().list(filters=[['service_type','=','disk']]).execute()['items']:
527         api.keep_services().delete(uuid=d['uuid']).execute()
528     for d in api.keep_disks().list().execute()['items']:
529         api.keep_disks().delete(uuid=d['uuid']).execute()
530
531     for d in range(0, num_servers):
532         port = _start_keep(d, keep_args)
533         svc = api.keep_services().create(body={'keep_service': {
534             'uuid': 'zzzzz-bi6l4-keepdisk{:07d}'.format(d),
535             'service_host': 'localhost',
536             'service_port': port,
537             'service_type': 'disk',
538             'service_ssl_flag': False,
539         }}).execute()
540         api.keep_disks().create(body={
541             'keep_disk': {'keep_service_uuid': svc['uuid'] }
542         }).execute()
543
544     # If keepproxy and/or keep-web is running, send SIGHUP to make
545     # them discover the new keepstore services.
546     for svc in ('keepproxy', 'keep-web'):
547         pidfile = _pidfile('keepproxy')
548         if os.path.exists(pidfile):
549             try:
550                 os.kill(int(open(pidfile).read()), signal.SIGHUP)
551             except OSError:
552                 os.remove(pidfile)
553
554 def _stop_keep(n):
555     kill_server_pid(_pidfile('keep{}'.format(n)))
556     if os.path.exists("{}/keep{}.volume".format(TEST_TMPDIR, n)):
557         with open("{}/keep{}.volume".format(TEST_TMPDIR, n), 'r') as r:
558             shutil.rmtree(r.read(), True)
559         os.unlink("{}/keep{}.volume".format(TEST_TMPDIR, n))
560     if os.path.exists(os.path.join(TEST_TMPDIR, "keep.blob_signing_key")):
561         os.remove(os.path.join(TEST_TMPDIR, "keep.blob_signing_key"))
562
563 def stop_keep(num_servers=2):
564     for n in range(0, num_servers):
565         _stop_keep(n)
566
567 def run_keep_proxy():
568     if 'ARVADOS_TEST_PROXY_SERVICES' in os.environ:
569         return
570     stop_keep_proxy()
571
572     port = find_available_port()
573     env = os.environ.copy()
574     env['ARVADOS_API_TOKEN'] = auth_token('anonymous')
575     logf = open(_logfilename('keepproxy'), 'a')
576     kp = subprocess.Popen(
577         ['keepproxy',
578          '-pid='+_pidfile('keepproxy'),
579          '-listen=:{}'.format(port)],
580         env=env, stdin=open('/dev/null'), stdout=logf, stderr=logf, close_fds=True)
581
582     api = arvados.api(
583         version='v1',
584         host=os.environ['ARVADOS_API_HOST'],
585         token=auth_token('admin'),
586         insecure=True)
587     for d in api.keep_services().list(
588             filters=[['service_type','=','proxy']]).execute()['items']:
589         api.keep_services().delete(uuid=d['uuid']).execute()
590     api.keep_services().create(body={'keep_service': {
591         'service_host': 'localhost',
592         'service_port': port,
593         'service_type': 'proxy',
594         'service_ssl_flag': False,
595     }}).execute()
596     os.environ["ARVADOS_KEEP_SERVICES"] = "http://localhost:{}".format(port)
597     _setport('keepproxy', port)
598     _wait_until_port_listens(port)
599
600 def stop_keep_proxy():
601     if 'ARVADOS_TEST_PROXY_SERVICES' in os.environ:
602         return
603     kill_server_pid(_pidfile('keepproxy'))
604
605 def run_arv_git_httpd():
606     if 'ARVADOS_TEST_PROXY_SERVICES' in os.environ:
607         return
608     stop_arv_git_httpd()
609
610     gitdir = os.path.join(SERVICES_SRC_DIR, 'api', 'tmp', 'git')
611     gitport = find_available_port()
612     env = os.environ.copy()
613     env.pop('ARVADOS_API_TOKEN', None)
614     logf = open(_logfilename('arv-git-httpd'), 'a')
615     agh = subprocess.Popen(
616         ['arv-git-httpd',
617          '-repo-root='+gitdir+'/test',
618          '-address=:'+str(gitport)],
619         env=env, stdin=open('/dev/null'), stdout=logf, stderr=logf)
620     with open(_pidfile('arv-git-httpd'), 'w') as f:
621         f.write(str(agh.pid))
622     _setport('arv-git-httpd', gitport)
623     _wait_until_port_listens(gitport)
624
625 def stop_arv_git_httpd():
626     if 'ARVADOS_TEST_PROXY_SERVICES' in os.environ:
627         return
628     kill_server_pid(_pidfile('arv-git-httpd'))
629
630 def run_keep_web():
631     if 'ARVADOS_TEST_PROXY_SERVICES' in os.environ:
632         return
633     stop_keep_web()
634
635     keepwebport = find_available_port()
636     env = os.environ.copy()
637     env['ARVADOS_API_TOKEN'] = auth_token('anonymous')
638     logf = open(_logfilename('keep-web'), 'a')
639     keepweb = subprocess.Popen(
640         ['keep-web',
641          '-allow-anonymous',
642          '-attachment-only-host=download',
643          '-listen=:'+str(keepwebport)],
644         env=env, stdin=open('/dev/null'), stdout=logf, stderr=logf)
645     with open(_pidfile('keep-web'), 'w') as f:
646         f.write(str(keepweb.pid))
647     _setport('keep-web', keepwebport)
648     _wait_until_port_listens(keepwebport)
649
650 def stop_keep_web():
651     if 'ARVADOS_TEST_PROXY_SERVICES' in os.environ:
652         return
653     kill_server_pid(_pidfile('keep-web'))
654
655 def run_nginx():
656     if 'ARVADOS_TEST_PROXY_SERVICES' in os.environ:
657         return
658     stop_nginx()
659     nginxconf = {}
660     nginxconf['CONTROLLERPORT'] = _getport('controller')
661     nginxconf['CONTROLLERSSLPORT'] = find_available_port()
662     nginxconf['KEEPWEBPORT'] = _getport('keep-web')
663     nginxconf['KEEPWEBDLSSLPORT'] = find_available_port()
664     nginxconf['KEEPWEBSSLPORT'] = find_available_port()
665     nginxconf['KEEPPROXYPORT'] = _getport('keepproxy')
666     nginxconf['KEEPPROXYSSLPORT'] = find_available_port()
667     nginxconf['GITPORT'] = _getport('arv-git-httpd')
668     nginxconf['GITSSLPORT'] = find_available_port()
669     nginxconf['WSPORT'] = _getport('ws')
670     nginxconf['WSSPORT'] = _getport('wss')
671     nginxconf['SSLCERT'] = os.path.join(SERVICES_SRC_DIR, 'api', 'tmp', 'self-signed.pem')
672     nginxconf['SSLKEY'] = os.path.join(SERVICES_SRC_DIR, 'api', 'tmp', 'self-signed.key')
673     nginxconf['ACCESSLOG'] = _logfilename('nginx_access')
674     nginxconf['ERRORLOG'] = _logfilename('nginx_error')
675     nginxconf['TMPDIR'] = TEST_TMPDIR
676
677     conftemplatefile = os.path.join(MY_DIRNAME, 'nginx.conf')
678     conffile = os.path.join(TEST_TMPDIR, 'nginx.conf')
679     with open(conffile, 'w') as f:
680         f.write(re.sub(
681             r'{{([A-Z]+)}}',
682             lambda match: str(nginxconf.get(match.group(1))),
683             open(conftemplatefile).read()))
684
685     env = os.environ.copy()
686     env['PATH'] = env['PATH']+':/sbin:/usr/sbin:/usr/local/sbin'
687
688     nginx = subprocess.Popen(
689         ['nginx',
690          '-g', 'error_log stderr info;',
691          '-g', 'pid '+_pidfile('nginx')+';',
692          '-c', conffile],
693         env=env, stdin=open('/dev/null'), stdout=sys.stderr)
694     _setport('controller-ssl', nginxconf['CONTROLLERSSLPORT'])
695     _setport('keep-web-dl-ssl', nginxconf['KEEPWEBDLSSLPORT'])
696     _setport('keep-web-ssl', nginxconf['KEEPWEBSSLPORT'])
697     _setport('keepproxy-ssl', nginxconf['KEEPPROXYSSLPORT'])
698     _setport('arv-git-httpd-ssl', nginxconf['GITSSLPORT'])
699
700 def stop_nginx():
701     if 'ARVADOS_TEST_PROXY_SERVICES' in os.environ:
702         return
703     kill_server_pid(_pidfile('nginx'))
704
705 def _pidfile(program):
706     return os.path.join(TEST_TMPDIR, program + '.pid')
707
708 def _portfile(program):
709     return os.path.join(TEST_TMPDIR, program + '.port')
710
711 def _setport(program, port):
712     with open(_portfile(program), 'w') as f:
713         f.write(str(port))
714
715 # Returns 9 if program is not up.
716 def _getport(program):
717     try:
718         return int(open(_portfile(program)).read())
719     except IOError:
720         return 9
721
722 def _dbconfig(key):
723     global _cached_db_config
724     if not _cached_db_config:
725         _cached_db_config = yaml.load(open(os.path.join(
726             SERVICES_SRC_DIR, 'api', 'config', 'database.yml')))
727     return _cached_db_config['test'][key]
728
729 def _apiconfig(key):
730     global _cached_config
731     if _cached_config:
732         return _cached_config[key]
733     def _load(f, required=True):
734         fullpath = os.path.join(SERVICES_SRC_DIR, 'api', 'config', f)
735         if not required and not os.path.exists(fullpath):
736             return {}
737         return yaml.load(fullpath)
738     cdefault = _load('application.default.yml')
739     csite = _load('application.yml', required=False)
740     _cached_config = {}
741     for section in [cdefault.get('common',{}), cdefault.get('test',{}),
742                     csite.get('common',{}), csite.get('test',{})]:
743         _cached_config.update(section)
744     return _cached_config[key]
745
746 def fixture(fix):
747     '''load a fixture yaml file'''
748     with open(os.path.join(SERVICES_SRC_DIR, 'api', "test", "fixtures",
749                            fix + ".yml")) as f:
750         yaml_file = f.read()
751         try:
752           trim_index = yaml_file.index("# Test Helper trims the rest of the file")
753           yaml_file = yaml_file[0:trim_index]
754         except ValueError:
755           pass
756         return yaml.load(yaml_file)
757
758 def auth_token(token_name):
759     return fixture("api_client_authorizations")[token_name]["api_token"]
760
761 def authorize_with(token_name):
762     '''token_name is the symbolic name of the token from the api_client_authorizations fixture'''
763     arvados.config.settings()["ARVADOS_API_TOKEN"] = auth_token(token_name)
764     arvados.config.settings()["ARVADOS_API_HOST"] = os.environ.get("ARVADOS_API_HOST")
765     arvados.config.settings()["ARVADOS_API_HOST_INSECURE"] = "true"
766
767 class TestCaseWithServers(unittest.TestCase):
768     """TestCase to start and stop supporting Arvados servers.
769
770     Define any of MAIN_SERVER, KEEP_SERVER, and/or KEEP_PROXY_SERVER
771     class variables as a dictionary of keyword arguments.  If you do,
772     setUpClass will start the corresponding servers by passing these
773     keyword arguments to the run, run_keep, and/or run_keep_server
774     functions, respectively.  It will also set Arvados environment
775     variables to point to these servers appropriately.  If you don't
776     run a Keep or Keep proxy server, setUpClass will set up a
777     temporary directory for Keep local storage, and set it as
778     KEEP_LOCAL_STORE.
779
780     tearDownClass will stop any servers started, and restore the
781     original environment.
782     """
783     MAIN_SERVER = None
784     WS_SERVER = None
785     KEEP_SERVER = None
786     KEEP_PROXY_SERVER = None
787     KEEP_WEB_SERVER = None
788
789     @staticmethod
790     def _restore_dict(src, dest):
791         for key in list(dest.keys()):
792             if key not in src:
793                 del dest[key]
794         dest.update(src)
795
796     @classmethod
797     def setUpClass(cls):
798         cls._orig_environ = os.environ.copy()
799         cls._orig_config = arvados.config.settings().copy()
800         cls._cleanup_funcs = []
801         os.environ.pop('ARVADOS_KEEP_SERVICES', None)
802         os.environ.pop('ARVADOS_EXTERNAL_CLIENT', None)
803         for server_kwargs, start_func, stop_func in (
804                 (cls.MAIN_SERVER, run, reset),
805                 (cls.WS_SERVER, run_ws, stop_ws),
806                 (cls.KEEP_SERVER, run_keep, stop_keep),
807                 (cls.KEEP_PROXY_SERVER, run_keep_proxy, stop_keep_proxy),
808                 (cls.KEEP_WEB_SERVER, run_keep_web, stop_keep_web)):
809             if server_kwargs is not None:
810                 start_func(**server_kwargs)
811                 cls._cleanup_funcs.append(stop_func)
812         if (cls.KEEP_SERVER is None) and (cls.KEEP_PROXY_SERVER is None):
813             cls.local_store = tempfile.mkdtemp()
814             os.environ['KEEP_LOCAL_STORE'] = cls.local_store
815             cls._cleanup_funcs.append(
816                 lambda: shutil.rmtree(cls.local_store, ignore_errors=True))
817         else:
818             os.environ.pop('KEEP_LOCAL_STORE', None)
819         arvados.config.initialize()
820
821     @classmethod
822     def tearDownClass(cls):
823         for clean_func in cls._cleanup_funcs:
824             clean_func()
825         cls._restore_dict(cls._orig_environ, os.environ)
826         cls._restore_dict(cls._orig_config, arvados.config.settings())
827
828
829 if __name__ == "__main__":
830     actions = [
831         'start', 'stop',
832         'start_ws', 'stop_ws',
833         'start_controller', 'stop_controller',
834         'start_keep', 'stop_keep',
835         'start_keep_proxy', 'stop_keep_proxy',
836         'start_keep-web', 'stop_keep-web',
837         'start_arv-git-httpd', 'stop_arv-git-httpd',
838         'start_nginx', 'stop_nginx',
839     ]
840     parser = argparse.ArgumentParser()
841     parser.add_argument('action', type=str, help="one of {}".format(actions))
842     parser.add_argument('--auth', type=str, metavar='FIXTURE_NAME', help='Print authorization info for given api_client_authorizations fixture')
843     parser.add_argument('--num-keep-servers', metavar='int', type=int, default=2, help="Number of keep servers desired")
844     parser.add_argument('--keep-enforce-permissions', action="store_true", help="Enforce keep permissions")
845
846     args = parser.parse_args()
847
848     if args.action not in actions:
849         print("Unrecognized action '{}'. Actions are: {}.".
850               format(args.action, actions),
851               file=sys.stderr)
852         sys.exit(1)
853     if args.action == 'start':
854         stop(force=('ARVADOS_TEST_API_HOST' not in os.environ))
855         run(leave_running_atexit=True)
856         host = os.environ['ARVADOS_API_HOST']
857         if args.auth is not None:
858             token = auth_token(args.auth)
859             print("export ARVADOS_API_TOKEN={}".format(pipes.quote(token)))
860             print("export ARVADOS_API_HOST={}".format(pipes.quote(host)))
861             print("export ARVADOS_API_HOST_INSECURE=true")
862         else:
863             print(host)
864     elif args.action == 'stop':
865         stop(force=('ARVADOS_TEST_API_HOST' not in os.environ))
866     elif args.action == 'start_ws':
867         run_ws()
868     elif args.action == 'stop_ws':
869         stop_ws()
870     elif args.action == 'start_controller':
871         run_controller()
872     elif args.action == 'stop_controller':
873         stop_controller()
874     elif args.action == 'start_keep':
875         run_keep(enforce_permissions=args.keep_enforce_permissions, num_servers=args.num_keep_servers)
876     elif args.action == 'stop_keep':
877         stop_keep(num_servers=args.num_keep_servers)
878     elif args.action == 'start_keep_proxy':
879         run_keep_proxy()
880     elif args.action == 'stop_keep_proxy':
881         stop_keep_proxy()
882     elif args.action == 'start_arv-git-httpd':
883         run_arv_git_httpd()
884     elif args.action == 'stop_arv-git-httpd':
885         stop_arv_git_httpd()
886     elif args.action == 'start_keep-web':
887         run_keep_web()
888     elif args.action == 'stop_keep-web':
889         stop_keep_web()
890     elif args.action == 'start_nginx':
891         run_nginx()
892         print("export ARVADOS_API_HOST=0.0.0.0:{}".format(_getport('controller-ssl')))
893     elif args.action == 'stop_nginx':
894         stop_nginx()
895     else:
896         raise Exception("action recognized but not implemented!?")