This repository has been archived by the owner on Apr 16, 2018. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 31
/
admin.py
executable file
·2332 lines (2026 loc) · 95.9 KB
/
admin.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
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
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
###############################################################################
#
# SageMathCloud: A collaborative web-based interface to Sage, IPython, LaTeX and the Terminal.
#
# Copyright (C) 2014, William Stein
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
###############################################################################
"""
Administration and Launch control of salvus components
"""
####################
# Standard imports
####################
import json, logging, os, shutil, signal, socket, stat, subprocess, sys, tempfile, time
from string import Template
import misc
############################################################
# Paths where data and configuration are stored
############################################################
SITENAME = 'cloud.sagemath.com'
DATA = 'data'
CONF = 'conf'
AGENT = os.path.join(os.environ['HOME'], '.ssh', 'agent')
PWD = os.path.abspath('.')
PIDS = os.path.join(DATA, 'pids') # preferred location for pid files
LOGS = os.path.join(DATA, 'logs') # preferred location for pid files
BIN = os.path.join(DATA, 'local', 'bin')
PYTHON = os.path.join(BIN, 'python')
SECRETS = os.path.join(DATA,'secrets')
# Read in socket of ssh-agent, if there is an AGENT file.
# NOTE: I'm using this right now on my laptop, but it's not yet
# deployed on cloud.sagemath *yet*. When done, it will mean the
# ssh key used by the hub is password protected, which
# will be much more secure: someone who steals ~/.ssh gets nothing,
# though still if somebody logs in as the salvus user on one of
# these nodes, they can ssh to other nodes, though they can't
# change passwords, etc. Also, this means having the ssh private
# key on the compute vm's is no longer a security risk, since it
# is protected by a (very long, very random) passphrase.
if os.path.exists(AGENT):
for X in open(AGENT).readlines():
if 'SSH_AUTH_SOCK' in X:
# The AGENT file is as output by ssh-agent.
os.environ['SSH_AUTH_SOCK'] = X.split(';')[0][len('SSH_AUTH_SOCK='):]
# TODO: factor out all $HOME/salvus/salvus style stuff in code below and use BASE.
BASE = 'salvus/salvus/'
LOG_INTERVAL = 6
GIT_REPO='' # TODO
whoami = os.environ['USER']
# Default ports
HAPROXY_PORT = 8000
NGINX_PORT = 8080
HUB_PORT = 5000
HUB_PROXY_PORT = 5001
SYNCSTRING_PORT = 6001
# These are used by the firewall.
CASSANDRA_CLIENT_PORT = 9160
CASSANDRA_NATIVE_PORT = 9042
CASSANDRA_INTERNODE_PORTS = [7000, 7001]
CASSANDRA_PORTS = CASSANDRA_INTERNODE_PORTS + [CASSANDRA_CLIENT_PORT, CASSANDRA_NATIVE_PORT]
####################
# Sending an email (useful for monitoring script)
# See http://www.nixtutor.com/linux/send-mail-through-gmail-with-python/
####################
def email(msg= '', subject='ADMIN -- cloud.sagemath.com', toaddrs='[email protected]', fromaddr='[email protected]'):
log.info("sending email to %s", toaddrs)
username = 'salvusmath'
password = open(os.path.join(os.environ['HOME'],'salvus/salvus/data/secrets/salvusmath_email_password')
).read().strip()
import smtplib
from email.mime.text import MIMEText
msg = MIMEText(msg)
msg['Subject'] = subject
msg['From'] = fromaddr
msg['To'] = toaddrs
server = smtplib.SMTP('smtp.gmail.com:587')
server.starttls()
server.login(username,password)
server.sendmail(fromaddr, toaddrs, msg.as_string())
server.quit()
def zfs_size(s):
"""
Convert a zfs size string to gigabytes (float)
"""
if len(s) == 0:
return 0.0
u = s[-1]; q = float(s[:-1])
if u == 'M':
q /= 1000
elif u == 'T':
q *= 1000
elif u == 'K':
q /= 1000000
return q
####################
# Running a subprocess
####################
MAXTIME_S=300
def run(args, maxtime=MAXTIME_S, verbose=True, stderr=True):
"""
Run the command line specified by args (using subprocess.Popen)
and return the stdout and stderr, killing the subprocess if it
takes more than maxtime seconds to run.
If stderr is false, don't include in the returned output.
If args is a list of lists, run all the commands separately in the
list.
if ignore_errors is true, completely ignores any error codes!
"""
if args and isinstance(args[0], list):
return '\n'.join([str(run(a, maxtime=maxtime,verbose=verbose)) for a in args])
args = [str(x) for x in args]
if maxtime:
def timeout(*a):
raise KeyboardInterrupt("running '%s' took more than %s seconds, so killed"%(' '.join(args), maxtime))
signal.signal(signal.SIGALRM, timeout)
signal.alarm(maxtime)
if verbose:
log.info("running '%s'", ' '.join(args))
try:
a = subprocess.Popen(args, stdin=subprocess.PIPE, stdout = subprocess.PIPE,
stderr=subprocess.PIPE)
if stderr:
out = a.stderr.read()
else:
out = ''
out += a.stdout.read()
if verbose:
log.info("output '%s'", out[:256])
return out
finally:
if maxtime:
signal.signal(signal.SIGALRM, signal.SIG_IGN) # cancel the alarm
# A convenience object "sh":
# sh['list', 'of', ..., 'arguments'] to run a shell command
class SH(object):
def __init__(self, maxtime=MAXTIME_S):
self.maxtime = maxtime
def __getitem__(self, args):
return run([args] if isinstance(args, str) else list(args), maxtime=self.maxtime)
sh = SH()
def process_status(pid, run):
"""
Return the status of a process, obtained using the ps command.
The run option is used to run the command (so it could run on
a remote machine). The result is a dictionary; it is empty if
the given process is not running.
"""
fields = ['%cpu', '%mem', 'etime', 'pid', 'start', 'cputime', 'rss', 'vsize']
v = run(['ps', '-p', str(int(pid)), '-o', ' '.join(fields)], verbose=False).splitlines()
if len(v) <= 1: return {}
return dict(zip(fields, v[-1].split()))
def dns(host, timeout=10):
"""
Return list of ip addresses of a given host. Errors out after timeout seconds.
"""
a = os.popen3("host -t A -W %s %s | awk '{print $4}'"%(timeout,host))
err = a[2].read().strip()
if err:
raise RuntimeError(err)
out = a[1].read()
if 'found' in out:
raise RuntimeError("unknown domain '%s'"%host)
else:
return out.split()[1:]
########################################
# Standard Python Logging
########################################
logging.basicConfig()
log = logging.getLogger('')
#log.setLevel(logging.DEBUG) # WARNING, INFO, etc.
#log.setLevel(logging.WARNING) # WARNING, INFO, etc.
log.setLevel(logging.INFO) # WARNING, INFO, etc.
def restrict(path):
#log.info("ensuring that '%s' has restrictive permissions", path)
if os.stat(path)[stat.ST_MODE] != 0o40700:
os.chmod(path, 0o40700)
def init_data_directory():
#log.info("ensuring that '%s' exist", DATA)
for path in [DATA, PIDS, LOGS]:
if not os.path.exists(path):
os.makedirs(path)
restrict(path)
#log.info("ensuring that PATH starts with programs in DATA directory")
os.environ['PATH'] = os.path.join(DATA, 'local/bin/') + ':' + os.environ['PATH']
init_data_directory()
########################################
# Misc operating system interaction
########################################
def system(args):
"""
Run the command line specified by args (using os.system) and
return the stdout and stderr, killing the subprocess if it takes
more than maxtime seconds to run. If args is a list of lists, run
all the commands separately in the list, returning *sum* of error
codes output by os.system.
"""
if args and isinstance(args[0], list):
return sum([system(a) for a in args])
c = ' '.join([str(x) for x in args])
log.info("running '%s' via system", c)
return os.system(c)
def abspath(path='.'):
return os.path.abspath(path)
def kill(pid, signal=15):
"""Send signal to the process with pid."""
if pid is not None:
return run(['kill', '-%s'%signal, pid])
def copyfile(src, target):
return shutil.copyfile(src, target)
def readfile(filename):
"""Read the named file and return its contents."""
if not os.path.exists(filename):
raise IOError, "no such file or directory: '%s'"%filename
try:
return open(filename).read()
except IOError:
pass
def writefile(filename, content):
open(filename,'w').write(content)
def makedirs(path):
if not os.path.exists(path):
os.makedirs(path)
def unlink(filename):
os.unlink(filename)
def path_exists(path):
return os.path.exists(path)
def is_running(pid):
try:
os.kill(pid, 0)
return True
except OSError:
return False
########################################
# Component: named collection of Process objects
########################################
class Component(object):
def __init__(self, id, processes):
self._processes = processes
self._id = id
def __repr__(self):
return "Component %s with %s processes"%(self._id, len(self._processes))
def __getitem__(self, i):
return self._processes[i]
def _procs_with_id(self, ids):
return [p for p in self._processes if ids is None or p.id() in ids]
def start(self, ids=None):
return [p.start() for p in self._procs_with_id(ids)]
def stop(self, ids=None):
return [p.stop() for p in self._procs_with_id(ids)]
def reload(self, ids=None):
return [p.reload() for p in self._procs_with_id(ids)]
def restart(self, ids=None):
return [p.restart() for p in self._procs_with_id(ids)]
def status(self, ids=None):
return [p.status() for p in self._procs_with_id(ids)]
########################################
# Process: a daemon process
########################################
class Process(object):
def __init__(self, id, name, port,
pidfile, logfile=None, monitor_database=None,
start_cmd=None, stop_cmd=None, reload_cmd=None,
start_using_system = False,
service=None,
term_signal=15):
self._name = name
self._port = port
self._id = str(id)
assert len(self._id.split()) == 1
self._pidfile = pidfile
self._start_cmd = start_cmd
self._start_using_system = start_using_system
self._stop_cmd = stop_cmd
self._reload_cmd = reload_cmd
self._pids = {}
self._logfile = logfile
self._monitor_database = monitor_database
self._monitor_pidfile = os.path.splitext(pidfile)[0] + '-log.pid'
self._term_signal = term_signal
def id(self):
return self._id
def log_tail(self):
if self._logfile is None:
raise NotImplementedError("the logfile is not known")
system(['tail', '-f', self._logfile])
def _parse_pidfile(self, contents):
return int(contents)
def _read_pid(self, file):
try:
return self._pids[file]
except KeyError:
try:
self._pids[file] = self._parse_pidfile(readfile(file).strip())
except: # no file
self._pids[file] = None
return self._pids[file]
def pid(self):
return self._read_pid(self._pidfile)
def is_running(self):
return len(self.status()) > 0
def _start_monitor(self):
# TODO: temporarily disabled -- they do no real good anyways.
return
if self._monitor_database and self._logfile:
run([PYTHON, 'monitor.py', '--logfile', self._logfile,
'--pidfile', self._monitor_pidfile, '--interval', LOG_INTERVAL,
'--database_nodes', self._monitor_database,
'--target_pidfile', self._pidfile,
'--target_name', self._name,
'--target_address', socket.gethostname(),
'--target_port', self._port])
def monitor_pid(self):
return self._read_pid(self._monitor_pidfile)
def _stop_monitor(self):
# NOTE: This function should never need to be called; the
# monitor stops automatically when the process it is
# monitoring stops and it has succeeded in recording this fact
# in the database.
if self._monitor_database and self._logfile and path_exists(self._monitor_pidfile):
try:
kill(self.monitor_pid())
unlink(self._monitor_pidfile)
except Exception, msg:
print msg
def _pre_start(self):
pass # overload to add extra config steps before start
def start(self):
if self.is_running(): return
self._pids = {}
self._pre_start()
if self._start_cmd is not None:
if self._start_using_system:
print system(self._start_cmd)
else:
print run(self._start_cmd)
print self._start_monitor()
def stop(self, force=False):
pid = self.pid()
if pid is None and not force: return
if self._stop_cmd is not None:
print run(self._stop_cmd)
else:
kill(pid, self._term_signal)
try:
if os.path.exists(self._pidfile): unlink(self._pidfile)
except Exception, msg:
print msg
if pid:
while True:
s = process_status(pid, run)
if not s:
break
print "waiting for %s to terminate"%pid
time.sleep(0.5)
self._pids = {}
def reload(self):
self._stop_monitor()
self._pids = {}
if self._reload_cmd is not None:
return run(self._reload_cmd)
else:
return 'reload not defined'
def status(self):
pid = self.pid()
if not pid: return {}
s = process_status(pid, run)
if not s:
self._stop_monitor()
self._pids = {}
if path_exists(self._pidfile):
unlink(self._pidfile)
return s
def restart(self):
self.stop()
self.start()
####################
# Nginx
####################
class Nginx(Process):
def __init__(self, id=0, port=NGINX_PORT, monitor_database=None, base_url=""):
self._base_url = base_url
self._port = port
self._log = 'nginx-%s.log'%id
self._pid = 'nginx-%s.pid'%id
self._nginx_conf = 'nginx-%s.conf'%id
nginx_cmd = ['nginx', '-c', '../' + self._nginx_conf]
Process.__init__(self, id, name='nginx', port=self._port,
monitor_database = monitor_database,
logfile = os.path.join(LOGS, self._log),
pidfile = os.path.join(PIDS, self._pid),
start_cmd = nginx_cmd,
stop_cmd = nginx_cmd + ['-s', 'stop'],
reload_cmd = nginx_cmd + ['-s', 'reload'])
def _pre_start(self):
# Create and write conf file
conf = Template(open(os.path.join(CONF, 'nginx.conf')).read())
conf = conf.substitute(logfile=self._log, pidfile=self._pid,
http_port=self._port, base_url=self._base_url,
ifbase='#' if not self._base_url else '',
ifnobase='' if not self._base_url else '#')
writefile(filename=os.path.join(DATA, self._nginx_conf), content=conf)
# Write base_url javascript file, so clients have access to it
s = "salvus_base_url='%s'; /* autogenerated on nginx startup by admin.py */"%self._base_url
open(os.path.join(PWD, 'static/salvus_base_url.js'), 'w').write(s)
def __repr__(self):
return "Nginx process %s"%self._id
####################
# Stunnel
####################
class Stunnel(Process):
def __init__(self, id=0, accept_port=443, connect_port=HAPROXY_PORT, monitor_database=None):
logfile = os.path.join(LOGS,'stunnel-%s.log'%id)
base = abspath()
pidfile = os.path.join(base, PIDS,'stunnel-%s.pid'%id) # abspath of pidfile required by stunnel
self._stunnel_conf = os.path.join(DATA, 'stunnel-%s.conf'%id)
self._accept_port = accept_port
self._connect_port = connect_port
Process.__init__(self, id, name='stunnel', port=accept_port,
monitor_database = monitor_database,
logfile = logfile,
pidfile = pidfile,
# stunnel typically run as sudo, and sudo need not preserve PATH on Linux.
start_cmd = [os.path.join(base, DATA, 'local/bin', 'stunnel'), self._stunnel_conf])
def _pre_start(self):
pem = os.path.join(SECRETS, 'sagemath.com/nopassphrase.pem')
if not os.path.exists(pem):
raise RuntimeError("stunnel requires that the secret '%s' exists"%pem)
stunnel = 'stunnel.conf'
conf = Template(open(os.path.join(CONF, stunnel)).read())
conf = conf.substitute(logfile=self._logfile, pidfile=self._pidfile,
accept_port=self._accept_port, connect_port=self._connect_port)
writefile(filename=self._stunnel_conf, content=conf)
def __repr__(self):
return "Stunnel process %s"%self._id
####################
# HAproxy
####################
class Haproxy(Process):
def __init__(self, id=0,
sitename=SITENAME, # name of site, e.g., 'cloud.sagemath.com' if site is https://cloud.sagemath.com; used only if insecure_redirect is set
accept_proxy_port=HAPROXY_PORT, # port that stunnel sends decrypted traffic to
insecure_redirect_port=None, # if set to a port number (say 80), then all traffic to that port is immediately redirected to the secure site
insecure_testing_port=None, # if set to a port, then gives direct insecure access to full site
nginx_servers=None, # list of ip addresses
hub_servers=None, # list of ip addresses
proxy_servers=None, # list of ip addresses
monitor_database=None,
conf_file='conf/haproxy.conf',
base_url=''):
pidfile = os.path.join(PIDS, 'haproxy-%s.pid'%id)
# WARNING: this is now ignored since I don't want to patch haproxy; instead logging goes to syslog...
logfile = os.path.join(LOGS, 'haproxy-%s.log'%id)
# randomize the order of the servers to get better distribution between them by all the different
# haproxies that are running on the edge machines. (Users may hit any of them.)
import random
if nginx_servers:
random.shuffle(nginx_servers)
t = Template('server nginx$n $ip:$port maxconn $maxconn check ')
nginx_servers = ' ' + ('\n '.join([t.substitute(n=n, ip=x['ip'], port=x.get('port', NGINX_PORT), maxconn=x.get('maxconn',10000)) for
n, x in enumerate(nginx_servers)]))
if hub_servers:
random.shuffle(hub_servers)
t = Template('server hub$n $ip:$port cookie server:$ip:$port check inter 4000 maxconn $maxconn')
hub_servers = ' ' + ('\n '.join([t.substitute(n=n, ip=x['ip'], port=x.get('port', HUB_PORT), maxconn=x.get('maxconn',100)) for
n, x in enumerate(hub_servers)]))
if proxy_servers:
random.shuffle(proxy_servers)
t = Template('server proxy$n $ip:$port cookie server:$ip:$cookie_port check inter 4000 maxconn $maxconn')
# WARNING: note that cookie_port -- that is the port in the cookie's value, is set to be 1 less, i.e., it is
# the corresponding hub port. This could cause bugs/confusion if that convention were changed!!!!!! ***
# We do this so we can use the same cookie for both the hub and proxy servers, for efficiency.
proxy_servers = ' ' + ('\n '.join([t.substitute(n = n,
ip = x['ip'],
port = x.get('proxy_port', HUB_PROXY_PORT),
cookie_port = str(int(x.get('proxy_port', HUB_PROXY_PORT))-1),
maxconn = x.get('maxconn',100)) for
n, x in enumerate(proxy_servers)]))
if insecure_redirect_port:
insecure_redirect = Template(
"""
frontend unsecured *:$port
redirect location https://$sitename
""").substitute(port=insecure_redirect_port, sitename=sitename)
else:
insecure_redirect=''
conf = Template(open(conf_file).read()).substitute(
accept_proxy_port = accept_proxy_port,
insecure_testing_bind = 'bind *:%s'%insecure_testing_port if insecure_testing_port else '',
nginx_servers = nginx_servers,
hub_servers = hub_servers,
proxy_servers = proxy_servers,
insecure_redirect = insecure_redirect,
base_url = base_url
)
haproxy_conf = 'haproxy-%s.conf'%id
target_conf = os.path.join(DATA, haproxy_conf)
writefile(filename=target_conf, content=conf)
Process.__init__(self, id, name='haproxy', port=accept_proxy_port,
pidfile = pidfile,
logfile = logfile, monitor_database = monitor_database,
start_using_system = True,
start_cmd = ['HAPROXY_LOGFILE='+logfile, os.path.join(BIN, 'haproxy'), '-D', '-f', target_conf, '-p', pidfile])
def _parse_pidfile(self, contents):
return int(contents.splitlines()[0])
####################
# Hub
####################
class Hub(Process):
def __init__(self,
id = 0,
host = '',
port = HUB_PORT,
proxy_port = HUB_PROXY_PORT,
monitor_database = None,
keyspace = 'salvus',
debug = False,
logfile = None,
pidfile = None,
base_url = None,
local = False):
self._port = port
if pidfile is None:
pidfile = os.path.join(PIDS, 'hub-%s.pid'%id)
if logfile is None:
logfile = os.path.join(LOGS, 'hub-%s.log'%id)
extra = []
if debug:
extra.append('-g')
if base_url:
extra.append('--base_url')
extra.append(base_url)
if local:
extra.append('--local')
Process.__init__(self, id, name='hub', port=port,
pidfile = pidfile,
logfile = logfile, monitor_database=monitor_database,
start_cmd = [os.path.join(PWD, 'hub'), 'start',
'--id', id,
'--port', port,
'--proxy_port', proxy_port,
'--keyspace', keyspace,
'--host', host,
'--database_nodes', monitor_database,
'--pidfile', pidfile,
'--logfile', logfile] + extra,
stop_cmd = [os.path.join(PWD, 'hub'), 'stop', '--id', id],
reload_cmd = [os.path.join(PWD, 'hub'), 'restart', '--id', id])
def __repr__(self):
return "Hub server %s on port %s"%(self.id(), self._port)
####################
# Syncstring
####################
#class Syncstring(Process):
# def __init__(self,
# host = '',
# monitor_database = None,
# keyspace = 'salvus',
# debug = False,
# id = '0'): # id is ignored
# Process.__init__(self, id,
# name ='syncstring',
# port = SYNCSTRING_PORT,
# pidfile = os.path.join(PIDS, 'syncstring.pid'),
# logfile = os.path.join(PIDS, 'syncstring.log'),
# monitor_database = monitor_database,
# start_cmd = [os.path.join(PWD, 'syncstring'), 'start',
# '--keyspace', keyspace,
# '--host', host,
# '--database_nodes', monitor_database],
# stop_cmd = [os.path.join(PWD, 'syncstring'), 'stop'])
#
# def __repr__(self):
# return "Syncstring server"
########################################
# Cassandra database server
########################################
# environ variable for conf/ dir: CASSANDRA_CONF
class Cassandra(Process):
def __init__(self,
topology = None,
path = None, # CASSANDRA_HOME
id = 0,
monitor_database = None,
conf_template_path = None,
MAX_HEAP_SIZE = None,
HEAP_NEWSIZE = None,
**kwds):
"""
id -- arbitrary identifier
conf_template_path -- path that contains the initial conf files
"""
if MAX_HEAP_SIZE is not None:
os.environ['MAX_HEAP_SIZE'] = MAX_HEAP_SIZE
if HEAP_NEWSIZE is not None:
os.environ['HEAP_NEWSIZE'] = HEAP_NEWSIZE
cassandra_install = os.path.join(DATA, 'local', 'cassandra')
if conf_template_path is None:
conf_template_path = os.path.join(cassandra_install, 'conf')
assert os.path.exists(conf_template_path)
path = os.path.join(DATA, 'cassandra-%s'%id) if path is None else path
makedirs(path)
os.environ['CASSANDRA_HOME'] = path
logs_path = os.path.join(path, 'logs'); makedirs(logs_path)
conf_path = os.path.join(path, 'conf'); makedirs(conf_path)
if topology:
kwds['endpoint_snitch'] = 'org.apache.cassandra.locator.PropertyFileSnitch'
kwds['class_name'] = 'org.apache.cassandra.locator.SimpleSeedProvider'
for name in os.listdir(conf_template_path):
f = os.path.join(conf_template_path, name)
if not os.path.isfile(f): continue
r = open(f).read()
if name == 'cassandra.yaml':
for k,v in kwds.iteritems():
if isinstance(v, bool):
v = str(v).lower()
i = r.find('%s:'%k)
if i == -1:
#raise ValueError("no configuration option '%s'"%k)
# put it at the end -- some VALID options, e.g. auto_bootstrap, aren't even in the file
r += "\n\n%s: %s\n"%(k,v)
continue
if r[i-1] == "#":
i = i - 1
elif r[i-2] == "#":
i = i - 2
j = r[i:].find('\n')
if j == -1:
j = len(r)
r = r[:i] + '%s: %s'%(k,v) + r[j+i:]
if 'initial_token' not in kwds:
# Make sure initial_token is not set.
r = r.replace("\ninitial_token:","\n#initial_token:")
elif topology and name == 'cassandra-topology.properties':
r = topology
writefile(filename=os.path.join(conf_path, name), content=r)
pidfile = os.path.join(PIDS, 'cassandra-%s.pid'%id)
Process.__init__(self, id=id, name='cassandra', port=9160,
logfile = '%s/system.log'%logs_path,
pidfile = pidfile,
start_cmd = ['start-cassandra', '-c', conf_path, '-p', pidfile],
monitor_database=monitor_database)
##############################################
# A Virtual Machine running at UW
##############################################
class Vm(Process):
def __init__(self, ip_address, hostname=None, vcpus=2, ram=4, vnc=0, disk='', base='salvus', id=0, monitor_database=None, name='virtual_machine', fstab=''):
"""
INPUT:
- ip_address -- ip_address machine gets on the VPN
- hostname -- hostname to set on the machine itself (if
not given, sets to something based on the ip address)
- vcpus -- number of cpus
- ram -- number of gigabytes of ram (an integer)
- vnc -- port of vnc console (default: 0 for no vnc)
- disk -- string 'name1:size1,name2:size2,...' with size in gigabytes
- base -- string (default: 'salvus'); name of base vm image
- id -- optional, defaulta:0 (basically ignored)
- monitor_database -- default: None
- name -- default: "virtual_machine"
"""
self._ip_address = ip_address
self._hostname = hostname
self._vcpus = vcpus
self._ram = ram
self._vnc = vnc
self._base = base
self._disk = disk
self._fstab = fstab.strip()
pidfile = os.path.join(PIDS, 'vm-%s.pid'%ip_address)
logfile = os.path.join(LOGS, 'vm-%s.log'%ip_address)
start_cmd = [PYTHON, 'vm.py', '-d', '--ip_address', ip_address,
'--pidfile', pidfile, '--logfile', logfile,
'--vcpus', vcpus, '--ram', ram,
'--vnc', vnc,
'--base', base] + \
(['--fstab', fstab] if self._fstab else []) + \
(['--disk', disk] if self._disk else []) + \
(['--hostname', self._hostname] if self._hostname else [])
stop_cmd = [PYTHON, 'vm.py', '--stop', '--logfile', logfile, '--ip_address', ip_address] + (['--hostname', self._hostname] if self._hostname else [])
Process.__init__(self, id=id, name=name, port=0,
pidfile = pidfile, logfile = logfile,
start_cmd = start_cmd,
stop_cmd = stop_cmd,
monitor_database=monitor_database,
term_signal = 2 # must use 2 (=SIGINT) instead of 15 or 9 for proper cleanup!
)
def stop(self):
Process.stop(self, force=True)
##############################################
# A Virtual Machine instance running on Google Compute Engine
##############################################
class Vmgce(Process):
def __init__(self, ip_address='', hostname='', instance_type='n1-standard-1', base='', disk='', zone='', id=0, monitor_database=None, name='gce_virtual_machine'):
"""
INPUT:
- ip_address -- ip_address machine gets on the VPN
- hostname -- hostname to set on the machine itself
- instance_type -- see https://cloud.google.com/products/compute-engine/#pricing
- disk -- string 'name1:size1,name2:size2,...' with size in gigabytes
- base -- string (default: use newest); name of base snapshot
- id -- optional, defaulta:0 (basically ignored)
- monitor_database -- default: None
- name -- default: "gce_virtual_machine"
"""
if not ip_address:
raise RuntimeError("you must specify the ip_address")
if not hostname:
raise RuntimeError("you must specify the hostname")
self._ip_address = ip_address
self._hostname = hostname
self._instance_type = instance_type
self._base = base
self._disk = disk
self._zone = zone
pidfile = os.path.join(PIDS, 'vm_gce-%s.pid'%ip_address)
logfile = os.path.join(LOGS, 'vm_gce-%s.log'%ip_address)
start_cmd = ([PYTHON, 'vm_gce.py',
'--daemon', '--pidfile', pidfile, '--logfile', logfile] +
(['--zone', zone] if zone else []) +
['start',
'--ip_address', ip_address,
'--type', instance_type] +
(['--base', base] if base else []) +
(['--disk', disk] if disk else []) + [self._hostname])
stop_cmd = [PYTHON, 'vm_gce.py'] + (['--zone', zone] if zone else []) + ['stop', self._hostname]
Process.__init__(self, id=id, name=name, port=0,
pidfile = pidfile, logfile = logfile,
start_cmd = start_cmd,
stop_cmd = stop_cmd,
monitor_database=monitor_database,
term_signal = 2 # must use 2 (=SIGINT) instead of 15 or 9 for proper cleanup!
)
def stop(self):
Process.stop(self, force=True)
#################################
# Classical Sage Notebook Server
#################################
class Sagenb(Process):
def __init__(self, address, path, port, pool_size=16, monitor_database=None, debug=True, id=0):
self._address = address # to listen on
self._path = path
self._port = port
pidfile = os.path.join(PIDS, 'sagenb-%s.pid'%port)
logfile = os.path.join(LOGS, 'sagenb-%s.log'%port)
Process.__init__(self, id, name='sage', port=port,
pidfile = pidfile,
logfile = logfile,
monitor_database = monitor_database,
start_cmd = [PYTHON, 'sagenb_server.py', '--daemon',
'--path', path,
'--port', port,
'--address', address,
'--pool_size', pool_size,
'--pidfile', pidfile,
'--logfile', logfile]
)
########################################
# tinc VPN management
########################################
def ping(hostname, count=3, timeout=2):
"""
Try to ping hostname count times, timing out if we do not
finishing after timeout seconds.
Return False if the ping fails. If the ping succeeds, return
(min, average, max) ping times in milliseconds.
"""
p = subprocess.Popen(['ping', '-t', str(timeout), '-c', str(count), hostname],
stdin=subprocess.PIPE, stdout = subprocess.PIPE,
stderr=subprocess.PIPE)
if p.wait() == 0:
r = p.stdout.read()
i = r.rfind('=')
v = [float(t) for t in r[i+1:].strip().split()[0].split('/')]
return v[0], v[1], v[2]
else:
return False # fail
def tinc_conf(ip_address):
"""
Configure tinc on this machine, so it can be part of the VPN.
-- ip_address -- address this machine gets on the vpn
"""
SALVUS = os.path.realpath(__file__)
os.chdir(os.path.split(SALVUS)[0])
# make sure the directories are there
TARGET = 'data/local/etc/tinc'
if os.path.exists(TARGET):
print "deleting '%s'"%TARGET
shutil.rmtree(TARGET)
for path in [TARGET, 'data/local/var/run']: # .../run used for pidfile
if not os.path.exists(path):
os.makedirs(path)
# create symbolic link to hosts directory in salvus git repo
os.symlink(os.path.join('../../../../conf/tinc_hosts'),
os.path.join(TARGET, 'hosts'))
# determine what our external ip address is
external_ip = misc.local_ip_address(dest='8.8.8.8')
# determine our hostname
hostname = socket.gethostname()
# Create the tinc-up script
tinc_up = os.path.join(TARGET, 'tinc-up')
open(tinc_up,'w').write(
"""#!/bin/sh
ifconfig $INTERFACE %s netmask 255.0.0.0
"""%ip_address)
os.chmod(tinc_up, stat.S_IRWXU)
# Create tinc.conf
tinc_conf = open(os.path.join(TARGET, 'tinc.conf'),'w')
tinc_conf.write('Name = %s\n'%hostname)
for h in os.listdir(os.path.join(TARGET, 'hosts')):
if "Address" in open(os.path.join(TARGET, 'hosts', h)).read():
tinc_conf.write('ConnectTo = %s\n'%h)
# on OS X, we need this, but otherwise we don't:
if os.uname()[0] == "Darwin":
tinc_conf.write('Device = /dev/tap0\n')
tinc_conf.close()
host_file = os.path.join(TARGET, 'hosts', hostname)
open(host_file,'w').write(
"""Address = %s
Subnet = %s/32"""%(external_ip, ip_address))
# generate keys
print sh['data/local/sbin/tincd', '-K']
# add file to git and checkin, then push to official repo
gitaddr = "[email protected]:williamstein/salvus.git"
print sh['git', 'pull', gitaddr]
print sh['git', 'add', os.path.join('conf/tinc_hosts', hostname)]
print sh['git', 'commit', '-a', '-m', 'tinc config for %s'%hostname]
print sh['git', 'push', gitaddr]
print "To join the vpn on startup,"
print "add this line to /etc/rc.local:\n"