3453: Add ensure_unique_name=True to collection create.
[arvados.git] / sdk / python / tests / run_test_server.py
1 #!/usr/bin/env python
2
3 import argparse
4 import os
5 import shutil
6 import signal
7 import subprocess
8 import sys
9 import tempfile
10 import time
11 import unittest
12 import yaml
13
14 MY_DIRNAME = os.path.dirname(os.path.realpath(__file__))
15 if __name__ == '__main__' and os.path.exists(
16       os.path.join(MY_DIRNAME, '..', 'arvados', '__init__.py')):
17     # We're being launched to support another test suite.
18     # Add the Python SDK source to the library path.
19     sys.path.insert(1, os.path.dirname(MY_DIRNAME))
20
21 import arvados.api
22 import arvados.config
23
24 SERVICES_SRC_DIR = os.path.join(MY_DIRNAME, '../../../services')
25 SERVER_PID_PATH = 'tmp/pids/webrick-test.pid'
26 WEBSOCKETS_SERVER_PID_PATH = 'tmp/pids/passenger-test.pid'
27 if 'GOPATH' in os.environ:
28     gopaths = os.environ['GOPATH'].split(':')
29     gobins = [os.path.join(path, 'bin') for path in gopaths]
30     os.environ['PATH'] = ':'.join(gobins) + ':' + os.environ['PATH']
31
32 if os.path.isdir('tests'):
33     TEST_TMPDIR = 'tests/tmp'
34 else:
35     TEST_TMPDIR = 'tmp'
36
37 def find_server_pid(PID_PATH, wait=10):
38     now = time.time()
39     timeout = now + wait
40     good_pid = False
41     while (not good_pid) and (now <= timeout):
42         time.sleep(0.2)
43         try:
44             with open(PID_PATH, 'r') as f:
45                 server_pid = int(f.read())
46             good_pid = (os.kill(server_pid, 0) == None)
47         except IOError:
48             good_pid = False
49         except OSError:
50             good_pid = False
51         now = time.time()
52
53     if not good_pid:
54         return None
55
56     return server_pid
57
58 def kill_server_pid(PID_PATH, wait=10):
59     try:
60         now = time.time()
61         timeout = now + wait
62         with open(PID_PATH, 'r') as f:
63             server_pid = int(f.read())
64         while now <= timeout:
65             os.kill(server_pid, signal.SIGTERM) == None
66             os.getpgid(server_pid) # throw OSError if no such pid
67             now = time.time()
68             time.sleep(0.1)
69     except IOError:
70         good_pid = False
71     except OSError:
72         good_pid = False
73
74 def run(websockets=False, reuse_server=False):
75     cwd = os.getcwd()
76     os.chdir(os.path.join(SERVICES_SRC_DIR, 'api'))
77
78     if websockets:
79         pid_file = WEBSOCKETS_SERVER_PID_PATH
80     else:
81         pid_file = SERVER_PID_PATH
82
83     test_pid = find_server_pid(pid_file, 0)
84
85     if test_pid == None or not reuse_server:
86         # do not try to run both server variants at once
87         stop()
88
89         # delete cached discovery document
90         shutil.rmtree(arvados.http_cache('discovery'))
91
92         # Setup database
93         os.environ["RAILS_ENV"] = "test"
94         subprocess.call(['bundle', 'exec', 'rake', 'tmp:cache:clear'])
95         subprocess.call(['bundle', 'exec', 'rake', 'db:test:load'])
96         subprocess.call(['bundle', 'exec', 'rake', 'db:fixtures:load'])
97
98         if websockets:
99             os.environ["ARVADOS_WEBSOCKETS"] = "true"
100             subprocess.call(['openssl', 'req', '-new', '-x509', '-nodes',
101                              '-out', './self-signed.pem',
102                              '-keyout', './self-signed.key',
103                              '-days', '3650',
104                              '-subj', '/CN=localhost'])
105             subprocess.call(['bundle', 'exec',
106                              'passenger', 'start', '-d', '-p3333',
107                              '--pid-file',
108                              os.path.join(os.getcwd(), WEBSOCKETS_SERVER_PID_PATH),
109                              '--ssl',
110                              '--ssl-certificate', 'self-signed.pem',
111                              '--ssl-certificate-key', 'self-signed.key'])
112             os.environ["ARVADOS_API_HOST"] = "127.0.0.1:3333"
113         else:
114             subprocess.call(['bundle', 'exec', 'rails', 'server', '-d',
115                              '--pid',
116                              os.path.join(os.getcwd(), SERVER_PID_PATH),
117                              '-p3001'])
118             os.environ["ARVADOS_API_HOST"] = "127.0.0.1:3001"
119
120         pid = find_server_pid(SERVER_PID_PATH)
121
122     os.environ["ARVADOS_API_HOST_INSECURE"] = "true"
123     os.environ["ARVADOS_API_TOKEN"] = ""
124     os.chdir(cwd)
125
126 def stop():
127     cwd = os.getcwd()
128     os.chdir(os.path.join(SERVICES_SRC_DIR, 'api'))
129
130     kill_server_pid(WEBSOCKETS_SERVER_PID_PATH, 0)
131     kill_server_pid(SERVER_PID_PATH, 0)
132
133     try:
134         os.unlink('self-signed.pem')
135     except:
136         pass
137
138     try:
139         os.unlink('self-signed.key')
140     except:
141         pass
142
143     os.chdir(cwd)
144
145 def _start_keep(n, keep_args):
146     keep0 = tempfile.mkdtemp()
147     keep_cmd = ["keepstore",
148                 "-volumes={}".format(keep0),
149                 "-listen=:{}".format(25107+n),
150                 "-pid={}".format("{}/keep{}.pid".format(TEST_TMPDIR, n))]
151
152     for arg, val in keep_args.iteritems():
153         keep_cmd.append("{}={}".format(arg, val))
154
155     kp0 = subprocess.Popen(keep_cmd)
156     with open("{}/keep{}.pid".format(TEST_TMPDIR, n), 'w') as f:
157         f.write(str(kp0.pid))
158
159     with open("{}/keep{}.volume".format(TEST_TMPDIR, n), 'w') as f:
160         f.write(keep0)
161
162 def run_keep(blob_signing_key=None, enforce_permissions=False):
163     stop_keep()
164
165     if not os.path.exists(TEST_TMPDIR):
166         os.mkdir(TEST_TMPDIR)
167
168     keep_args = {}
169     if blob_signing_key:
170         with open(os.path.join(TEST_TMPDIR, "keep.blob_signing_key"), "w") as f:
171             keep_args['--permission-key-file'] = f.name
172             f.write(blob_signing_key)
173     if enforce_permissions:
174         keep_args['--enforce-permissions'] = 'true'
175
176     _start_keep(0, keep_args)
177     _start_keep(1, keep_args)
178
179     os.environ["ARVADOS_API_HOST"] = "127.0.0.1:3001"
180     os.environ["ARVADOS_API_HOST_INSECURE"] = "true"
181
182     authorize_with("admin")
183     api = arvados.api('v1', cache=False)
184     for d in api.keep_services().list().execute()['items']:
185         api.keep_services().delete(uuid=d['uuid']).execute()
186     for d in api.keep_disks().list().execute()['items']:
187         api.keep_disks().delete(uuid=d['uuid']).execute()
188
189     s1 = api.keep_services().create(body={"keep_service": {"service_host": "localhost",  "service_port": 25107, "service_type": "disk"} }).execute()
190     s2 = api.keep_services().create(body={"keep_service": {"service_host": "localhost",  "service_port": 25108, "service_type": "disk"} }).execute()
191     api.keep_disks().create(body={"keep_disk": {"keep_service_uuid": s1["uuid"] } }).execute()
192     api.keep_disks().create(body={"keep_disk": {"keep_service_uuid": s2["uuid"] } }).execute()
193
194 def _stop_keep(n):
195     kill_server_pid("{}/keep{}.pid".format(TEST_TMPDIR, n), 0)
196     if os.path.exists("{}/keep{}.volume".format(TEST_TMPDIR, n)):
197         with open("{}/keep{}.volume".format(TEST_TMPDIR, n), 'r') as r:
198             shutil.rmtree(r.read(), True)
199         os.unlink("{}/keep{}.volume".format(TEST_TMPDIR, n))
200     if os.path.exists(os.path.join(TEST_TMPDIR, "keep.blob_signing_key")):
201         os.remove(os.path.join(TEST_TMPDIR, "keep.blob_signing_key"))
202
203 def stop_keep():
204     _stop_keep(0)
205     _stop_keep(1)
206
207 def run_keep_proxy(auth):
208     stop_keep_proxy()
209
210     if not os.path.exists(TEST_TMPDIR):
211         os.mkdir(TEST_TMPDIR)
212
213     os.environ["ARVADOS_API_HOST"] = "127.0.0.1:3001"
214     os.environ["ARVADOS_API_HOST_INSECURE"] = "true"
215     os.environ["ARVADOS_API_TOKEN"] = fixture("api_client_authorizations")[auth]["api_token"]
216
217     kp0 = subprocess.Popen(["keepproxy",
218                             "-pid={}/keepproxy.pid".format(TEST_TMPDIR),
219                             "-listen=:{}".format(25101)])
220
221     authorize_with("admin")
222     api = arvados.api('v1', cache=False)
223     api.keep_services().create(body={"keep_service": {"service_host": "localhost",  "service_port": 25101, "service_type": "proxy"} }).execute()
224
225     os.environ["ARVADOS_KEEP_PROXY"] = "http://localhost:25101"
226
227 def stop_keep_proxy():
228     kill_server_pid(os.path.join(TEST_TMPDIR, "keepproxy.pid"), 0)
229
230 def fixture(fix):
231     '''load a fixture yaml file'''
232     with open(os.path.join(SERVICES_SRC_DIR, 'api', "test", "fixtures",
233                            fix + ".yml")) as f:
234         return yaml.load(f.read())
235
236 def authorize_with(token):
237     '''token is the symbolic name of the token from the api_client_authorizations fixture'''
238     arvados.config.settings()["ARVADOS_API_TOKEN"] = fixture("api_client_authorizations")[token]["api_token"]
239     arvados.config.settings()["ARVADOS_API_HOST"] = os.environ.get("ARVADOS_API_HOST")
240     arvados.config.settings()["ARVADOS_API_HOST_INSECURE"] = "true"
241
242 class TestCaseWithServers(unittest.TestCase):
243     """TestCase to start and stop supporting Arvados servers.
244
245     Define any of MAIN_SERVER, KEEP_SERVER, and/or KEEP_PROXY_SERVER
246     class variables as a dictionary of keyword arguments.  If you do,
247     setUpClass will start the corresponding servers by passing these
248     keyword arguments to the run, run_keep, and/or run_keep_server
249     functions, respectively.  It will also set Arvados environment
250     variables to point to these servers appropriately.  If you don't
251     run a Keep or Keep proxy server, setUpClass will set up a
252     temporary directory for Keep local storage, and set it as
253     KEEP_LOCAL_STORE.
254
255     tearDownClass will stop any servers started, and restore the
256     original environment.
257     """
258     MAIN_SERVER = None
259     KEEP_SERVER = None
260     KEEP_PROXY_SERVER = None
261
262     @staticmethod
263     def _restore_dict(src, dest):
264         for key in dest.keys():
265             if key not in src:
266                 del dest[key]
267         dest.update(src)
268
269     @classmethod
270     def setUpClass(cls):
271         cls._orig_environ = os.environ.copy()
272         cls._orig_config = arvados.config.settings().copy()
273         cls._cleanup_funcs = []
274         for server_kwargs, start_func, stop_func in (
275               (cls.MAIN_SERVER, run, stop),
276               (cls.KEEP_SERVER, run_keep, stop_keep),
277               (cls.KEEP_PROXY_SERVER, run_keep_proxy, stop_keep_proxy)):
278             if server_kwargs is not None:
279                 start_func(**server_kwargs)
280                 cls._cleanup_funcs.append(stop_func)
281         os.environ.pop('ARVADOS_EXTERNAL_CLIENT', None)
282         if cls.KEEP_PROXY_SERVER is None:
283             os.environ.pop('ARVADOS_KEEP_PROXY', None)
284         if (cls.KEEP_SERVER is None) and (cls.KEEP_PROXY_SERVER is None):
285             cls.local_store = tempfile.mkdtemp()
286             os.environ['KEEP_LOCAL_STORE'] = cls.local_store
287             cls._cleanup_funcs.append(
288                 lambda: shutil.rmtree(cls.local_store, ignore_errors=True))
289         else:
290             os.environ.pop('KEEP_LOCAL_STORE', None)
291         arvados.config.initialize()
292
293     @classmethod
294     def tearDownClass(cls):
295         for clean_func in cls._cleanup_funcs:
296             clean_func()
297         cls._restore_dict(cls._orig_environ, os.environ)
298         cls._restore_dict(cls._orig_config, arvados.config.settings())
299
300
301 if __name__ == "__main__":
302     parser = argparse.ArgumentParser()
303     parser.add_argument('action', type=str, help='''one of "start", "stop", "start_keep", "stop_keep"''')
304     parser.add_argument('--websockets', action='store_true', default=False)
305     parser.add_argument('--reuse', action='store_true', default=False)
306     parser.add_argument('--auth', type=str, help='Print authorization info for given api_client_authorizations fixture')
307     args = parser.parse_args()
308
309     if args.action == 'start':
310         run(websockets=args.websockets, reuse_server=args.reuse)
311         if args.auth != None:
312             authorize_with(args.auth)
313             print("export ARVADOS_API_HOST={}".format(arvados.config.settings()["ARVADOS_API_HOST"]))
314             print("export ARVADOS_API_TOKEN={}".format(arvados.config.settings()["ARVADOS_API_TOKEN"]))
315             print("export ARVADOS_API_HOST_INSECURE={}".format(arvados.config.settings()["ARVADOS_API_HOST_INSECURE"]))
316     elif args.action == 'stop':
317         stop()
318     elif args.action == 'start_keep':
319         run_keep()
320     elif args.action == 'stop_keep':
321         stop_keep()
322     elif args.action == 'start_keep_proxy':
323         run_keep_proxy("admin")
324     elif args.action == 'stop_keep_proxy':
325         stop_keep_proxy()
326     else:
327         print('Unrecognized action "{}", actions are "start", "stop", "start_keep", "stop_keep"'.format(args.action))