-
-
Notifications
You must be signed in to change notification settings - Fork 68
/
container_manager.py
executable file
·1209 lines (1107 loc) · 33.9 KB
/
container_manager.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 python3
import argparse
import datetime
import grp
import logging
import logging.config
import os
import pwd
import random
import shlex
import shutil
import stat
import subprocess
import sys
import time
import lxc
import psutil
import yaml
number_of_compute_nodes = 3
#This will be visible on root and help pages. Suggested template:
# Resources for your computation are provided by <a href="...">...</a>.
provider_html = r"""
"""
# Container names
lxcn_base = "base" # OS and packages
lxcn_precell = "precell" # Everything but SageCell and system configuration
lxcn_sagecell = "sagecell" # Sage and SageCell
lxcn_backup = "sagecell-backup" # Saved master for restoration if necessary
lxcn_tester = "sctest" # Accessible via special port, for testing
lxcn_prefix = "sc-" # Prefix for main compute nodes
lxcn_version_prefix = "sage-" # Prefix for fixed version compute nodes
# Timeout in seconds to wait for a container to shutdown, network to start etc.
timeout = 120
# Time after which SageCell should be up and running.
start_delay = 126
# How long to wait after starting new containers before destroying old ones.
deploy_delay = 2*60*60 # Two hours to allow all interacts finish "naturally".
# User names and IDs
users = {"group": "sagecell", "GID": 8888,
"server": "sc_serv", "server_ID": 8888,
"worker": "sc_work", "worker_ID": 9999}
# Github repositories as (user, repository, branch)
repositories = [
("sagemath", "sage", "10.2"), # Jupyter js code is gone in Sage-10.3 and will require substantial work to deal with
("sagemath", "sagecell", "master"),
]
# Packages to be installed in the base container
system_packages = [
# SageMath prerequisites as of Sage 9.7
'bc',
'binutils',
'bzip2',
'ca-certificates',
'cliquer',
'cmake',
'curl',
'ecl',
'eclib-tools',
'fflas-ffpack',
'flintqs',
'g++',
'gcc',
'gengetopt',
'gfan',
'gfortran',
'glpk-utils',
'gmp-ecm',
'lcalc',
'libatomic-ops-dev',
'libboost-dev',
'libbraiding-dev',
'libbz2-dev',
'libcdd-dev',
'libcdd-tools',
'libcliquer-dev',
'libcurl4-openssl-dev',
'libec-dev',
'libecm-dev',
'libffi-dev',
'libflint-dev',
'libfplll-dev',
'libfreetype6-dev',
'libgc-dev',
'libgd-dev',
'libgf2x-dev',
'libgiac-dev',
'libgivaro-dev',
'libglpk-dev',
'libgmp-dev',
'libgsl-dev',
'libhomfly-dev',
'libiml-dev',
'liblfunction-dev',
'liblinbox-dev',
'liblrcalc-dev',
'liblzma-dev',
'libm4ri-dev',
'libm4rie-dev',
'libmpc-dev',
'libmpfi-dev',
'libmpfr-dev',
'libncurses5-dev',
'libntl-dev',
'libopenblas-dev',
'libpari-dev',
'libpcre3-dev',
'libplanarity-dev',
'libppl-dev',
'libprimesieve-dev',
'libpython3-dev',
'libqhull-dev',
'libreadline-dev',
'librw-dev',
'libsingular4-dev',
'libsqlite3-dev',
'libssl-dev',
'libsuitesparse-dev',
'libsymmetrica2-dev',
'libz-dev',
'libzmq3-dev',
'libzn-poly-dev',
'm4',
'make',
'nauty',
'ninja-build',
'openssl',
'palp',
'pari-doc',
'pari-elldata',
'pari-galdata',
'pari-galpol',
'pari-gp2c',
'pari-seadata',
'patch',
'perl',
'pkg-config',
'planarity',
'ppl-dev',
'python3',
'python3-venv',
'r-base-dev',
'r-cran-lattice',
'singular',
'singular-doc',
'sqlite3',
'sympow',
'tachyon',
'tar',
'tox',
'xcas',
'xz-utils',
# SageMath development
'autoconf',
'automake',
'git',
'gpgconf',
'libtool',
# 'openssh', not available on Ubuntu 22.04
'openssh-client',
'pkg-config',
# SageMath recommendations
'default-jdk',
'dvipng',
'ffmpeg',
'imagemagick',
'latexmk',
'libavdevice-dev',
'pandoc',
'tex-gyre',
'texlive-fonts-recommended',
'texlive-lang-cyrillic',
'texlive-lang-english',
'texlive-lang-european',
'texlive-lang-french',
'texlive-lang-german',
'texlive-lang-italian',
'texlive-lang-japanese',
'texlive-lang-polish',
'texlive-lang-portuguese',
'texlive-lang-spanish',
'texlive-latex-extra',
'texlive-xetex',
# SageMath optional
'4ti2',
'clang',
'coinor-cbc',
'coinor-libcbc-dev',
'graphviz',
'libfile-slurp-perl',
'libgraphviz-dev',
'libigraph-dev',
'libisl-dev',
'libjson-perl',
'libmongodb-perl',
'libnauty-dev',
'libperl-dev',
'libpolymake-dev',
'libsvg-perl',
'libterm-readkey-perl',
'libterm-readline-gnu-perl',
'libxml-libxslt-perl',
'libxml-writer-perl',
'libxml2-dev',
'lrslib',
'pari-gp2c',
'pdf2svg',
# 'polymake', triggers firefox snap that does not work in containers
'texinfo',
# SageMathCell
'bison',
'build-essential',
'epstool',
'fig2dev',
'gettext',
'gnuplot',
'ipset',
'iptables',
'libcairo2-dev',
'libgeos-dev',
'libhdf5-dev',
'libnetcdf-dev',
'libopenmpi-dev',
'libopenmpi3',
'libproj-dev',
'libsnappy-dev',
'libsystemd-dev',
'libxslt1-dev',
'macaulay2',
'nginx',
'npm',
'octave',
'octave-econometrics',
'octave-statistics',
'php8.3-fpm',
'proj-bin',
'python3-requests',
'rsyslog-relp',
'ssh',
'texlive',
'tk-dev',
'tmpreaper',
'unattended-upgrades',
'unzip',
'wget',
# R packages
'r-cran-desolve',
'r-cran-ggally',
'r-cran-ggeffects',
'r-cran-ggplot2',
'r-cran-lazyeval',
'r-cran-pracma',
'r-cran-reticulate',
'r-cran-rhandsontable',
'r-cran-rms',
'r-cran-survey',
'r-cran-tidyverse',
]
# R packages that are not available as system ones
R_packages = [
"flextable",
"formattable",
"ggformula",
"glmmTMB",
"gt",
"gtExtras",
"huxtable",
"kableExtra",
"mosaic",
"pixiedust",
"reactable",
"reactablefmtr",
"swirl",
]
# Optional Sage packages to be installed
sage_optional_packages = [
"4ti2",
"biopython",
"bliss",
"cbc",
"database_cremona_ellcurve",
"database_jones_numfield",
"database_odlyzko_zeta",
"database_symbolic_data",
"dot2tex", # needs graphviz
"fricas",
"gap_packages",
"gap3",
"latte_int",
"lie", # needs bison
"lrslib",
"mcqd",
"normaliz",
"pari_elldata",
"pari_galpol",
"pari_nftables",
"pari_seadata",
"pybtex", # needs unzip
"pynormaliz",
"qepcad",
"saclib",
"tides",
#"topcom", Does not work as of November 2022 with relying on system packages
]
# Python packages to be installed into Sage (via pip)
python_packages = [
# Dependencies of SageMathCell
"comm",
"lockfile",
"paramiko",
"psutil",
"sockjs-tornado",
"git+https://github.com/systemd/python-systemd.git",
# Optional
"future", # fipy does not work without it installed first
"admcycles",
"altair",
"APMonitor",
"astropy",
"astroquery",
"autoviz",
"bioinfokit",
"bitarray",
"bokeh",
"calplot",
"cartopy",
"chart_studio",
"colorlog",
"covid-daily",
"cramjam",
"cufflinks",
"dash",
"dask[array]",
"drawdata",
"duckdb",
"emoji",
"galgebra",
"geopandas",
"geoplot",
"getdist",
"ggplot",
"gif",
"giotto-tda",
"google-api-python-client",
"google-generativeai",
"graphviz",
"gspread",
"fipy",
"folium",
"healpy",
"h5py",
"husl",
"itikz",
"july",
"keras",
"keyring",
"koboextractor",
"langchain",
"langchain-openai",
"langserve",
"langserve[all]",
"lenstools",
"lhsmdu",
"lxml",
"manimlib",
"mapclassify",
"mathchem",
"mistralai",
"mpi4py",
"msedge-selenium-tools",
"munkres",
"nest_asyncio",
"netcdf4",
"nltk",
"numexpr",
"oauth2client",
"oct2py",
"openai",
"openpyxl",
"pandas",
"pandas-profiling",
"patsy",
"plotly",
"polars",
"pretty_html_table",
"pydot",
"pyforest",
"pygnuplot",
"PyPDF4",
"pyproj",
"pyswarms",
"python-snappy",
"python-ternary",
"pyvo",
"qiskit",
"qiskit[nature]",
"requests",
"scikit-image",
"scikit-learn",
"scikit-tda",
"scimath",
"scrapy",
"seaborn",
"selenium",
"Shapely",
"SimPy",
"snappy",
"spacy",
"SpeechRecognition",
"spiceypy",
"statsmodels",
"surface_dynamics",
"sweetviz",
"tables",
"tbcontrol",
"theano",
"tikzplotlib",
"torch",
"transformers",
"tweepy",
"twint",
"vega_datasets",
"WeasyPrint",
"wordcloud",
"xarray",
"xlrd",
"moss", # This one only complains about missing dependencies
]
# limits configuration for the host - will not be overwritten later
limits_conf = """\
* - nofile 32768
root - nofile 32768
"""
# rsyslog configuration for the host - will not be overwritten later
rsyslog_conf = r"""global(maxMessageSize="64k")
module(load="imrelp")
input(type="imrelp" port="12514")
template(name="sagecell" type="list") {
property(name="hostname")
constant(value=" ")
property(name="syslogtag")
property(name="msg" spifno1stsp="on")
property(name="msg" droplastlf="on")
constant(value="\n")
}
if $syslogfacility-text == "local3" then
{
action(type="omfile"
file="/var/log/sagecell.stats.log"
template="sagecell")
stop
}
"""
# HA-Proxy configuration is regenerated every time the script is run.
HAProxy_header = """\
# Default from Ubuntu 22.04 LTS
global
log /dev/log local0
log /dev/log local1 notice
chroot /var/lib/haproxy
stats socket /run/haproxy/admin.sock mode 660 level admin expose-fd listeners
stats timeout 30s
user haproxy
group haproxy
daemon
# Default SSL material locations
ca-base /etc/ssl/certs
crt-base /etc/ssl/private
# See: https://ssl-config.mozilla.org/#server=haproxy&server-version=2.0.3&config=intermediate
ssl-default-bind-ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384
ssl-default-bind-ciphersuites TLS_AES_128_GCM_SHA256:TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_SHA256
ssl-default-bind-options ssl-min-ver TLSv1.2 no-tls-tickets
defaults
log global
mode http
option httplog
option dontlognull
timeout connect 5000
timeout client 50000
timeout server 50000
errorfile 400 /etc/haproxy/errors/400.http
errorfile 403 /etc/haproxy/errors/403.http
errorfile 408 /etc/haproxy/errors/408.http
errorfile 500 /etc/haproxy/errors/500.http
errorfile 502 /etc/haproxy/errors/502.http
errorfile 503 /etc/haproxy/errors/503.http
errorfile 504 /etc/haproxy/errors/504.http
# SageMathCell additions
option http-server-close
option redispatch
timeout client-fin 50s
timeout tunnel 30m
"""
# {suffix} {port} {hostname} {peer_port} have to be set once
# lines with {node} and {id} should be repeated for each server
HAProxy_section = r"""
frontend http{suffix}
bind *:{port}
rate-limit sessions 10
http-request replace-path (/embedded_sagecell\.js.*) /static\1 if { url_beg /embedded_sagecell }
use_backend static{suffix} if { path_beg /static }
use_backend compute{suffix}
monitor-uri /?healthcheck
monitor fail if { nbsrv(compute{suffix}) lt 1 }
peers local{suffix}
peer {hostname} localhost:{peer_port}
backend static{suffix}
server {node} {ip}:8889 id {id} check
backend compute{suffix}
stick-table type string len 36 size 1m expire 30m peers local{suffix}
stick on urlp(CellSessionID)
stick match req.hdr(Jupyter-Kernel-ID)
stick store-response res.hdr(Jupyter-Kernel-ID)
stick match path bytes(8,36) if { path_reg ^/kernel/.{36}/ }
option httpchk
server {node} {ip}:8888 id {id} check
"""
HAProxy_stats = """
listen stats
bind *:9999
stats enable
stats refresh 5s
stats uri /
stats show-legends
"""
def call(command):
command = command.format_map(users)
log.debug("executing %s", command)
return subprocess.call(shlex.split(command))
def check_call(command):
command = command.format_map(users)
log.debug("executing %s", command)
subprocess.check_call(shlex.split(command))
def check_output(command):
command = command.format_map(users)
log.debug("executing %s", command)
return subprocess.check_output(shlex.split(command),
universal_newlines=True)
def communicate(command, message):
command = command.format_map(users)
log.debug("sending %s to %s", message, command)
with subprocess.Popen(shlex.split(command),
stdin=subprocess.PIPE,
universal_newlines=True) as p:
p.communicate(message)
if p.returncode != 0:
msg = "{} failed".format(command)
log.error(msg)
raise RuntimeError(msg)
def timer_delay(delay, test=None):
r"""
Wait with a countdown timer.
``delay`` is either a timedelta or the number of seconds.
``test`` is either ``None`` (default) or callable, in which case the timer
stops as soon as ``False`` is returned.
"""
if isinstance(delay, datetime.timedelta):
delay = delay.total_seconds()
now = time.time()
end = now + delay
while now < end and (test is None or test()):
remaining = datetime.timedelta(seconds=int(end - now))
sys.stdout.write(" Please wait {} ...\r".format(remaining))
sys.stdout.flush()
time.sleep(1)
now = time.time()
def update_repositories():
r"""
Clone/update repositories and checkout appropriate branches.
"""
if not os.path.exists("github"):
os.mkdir("github")
os.chdir("github")
git = lambda command: check_call("git " + command)
for user, repository, branch in repositories:
log.info("updating repository %s", repository)
if not os.path.exists(repository):
git("clone https://github.com/{}/{}.git".format(user, repository))
os.chdir(repository)
git("fetch")
git("checkout " + branch)
if call("git symbolic-ref -q HEAD") == 0:
git("pull")
os.chdir(os.pardir)
os.chdir(os.pardir)
def create_host_users():
r"""
Create host users if necessary.
If users exist (from previous runs), check that they are as expected.
"""
log.info("creating users on the host")
try:
check_call("addgroup --gid {GID} {group}")
check_call("adduser --uid {server_ID} --ingroup {group} --gecos '' "
"--disabled-password --no-create-home {server}")
check_call("adduser --uid {worker_ID} --ingroup {group} --gecos '' "
"--disabled-password --no-create-home {worker}")
except subprocess.CalledProcessError:
try:
g = grp.getgrnam(users["group"])
s = pwd.getpwnam(users["server"])
w = pwd.getpwnam(users["worker"])
if g.gr_gid != users["GID"] or \
s.pw_uid != users["server_ID"] or s.pw_gid != users["GID"] or \
w.pw_uid != users["worker_ID"] or w.pw_gid != users["GID"]:
raise KeyError
except KeyError:
raise RuntimeError("failed to create accounts on host")
def setup_container_users():
r"""
Create container users and setup SSH access.
"""
log.info("setting up users in the containter")
check_call("addgroup --gid {GID} {group}")
check_call("adduser --uid {server_ID} --ingroup {group} --gecos '' "
"--disabled-password {server}")
check_call("adduser --uid {worker_ID} --ingroup {group} --gecos '' "
"--disabled-password {worker}")
shome = os.path.join("/home", users["server"])
os.chmod(shome, stat.S_IRWXU |
stat.S_IRGRP | stat.S_IXGRP |
stat.S_IROTH | stat.S_IXOTH)
os.chdir(shome)
os.setegid(users["GID"])
os.seteuid(users["server_ID"])
os.mkdir(".ssh", 0o700)
check_call("ssh-keygen -t ed25519 -q -N '' -f .ssh/id_ed25519")
whome = os.path.join("/home", users["worker"])
os.chdir(whome)
os.setuid(0)
os.seteuid(users["worker_ID"])
os.mkdir(".cache", 0o700)
os.mkdir(".sage")
os.mkdir(".ssh", 0o700)
files_to_lock = [
".cache/pip",
".sage/local",
".ssh",
".bash_logout",
".bash_profile",
".bashrc",
".profile",
]
check_call(" ".join(["touch"] + files_to_lock))
os.setuid(0)
shutil.copy2(os.path.join(shome, ".ssh/id_ed25519.pub"),
".ssh/authorized_keys")
os.chown(".ssh/authorized_keys", users["worker_ID"], users["GID"])
# Get the localhost in the known_hosts file.
check_call("su -l {server} -c "
"'ssh -q -oStrictHostKeyChecking=no {worker}@localhost whoami'")
for f in files_to_lock:
check_call("chattr -R +i " + f)
def become_server():
r"""
Adjust UID etc. to have files created as the server user.
"""
os.setgid(users["GID"])
os.setuid(users["server_ID"])
os.environ["HOME"] = os.path.join("/home", users["server"])
os.chdir(os.environ["HOME"])
os.environ.setdefault("MAKE", "make -j{}".format(os.cpu_count()))
def install_sage():
r"""
Install Sage.
"""
become_server()
shutil.move("github/sage", ".")
os.chdir("sage")
log.info("compiling Sage")
check_call("./bootstrap")
check_call("./configure")
check_call("make")
# FIXME: permissions are wrong in Sage 8.9.
os.chmod("local/share/jmol", stat.S_IRWXU | stat.S_IRGRP | stat.S_IXGRP
| stat.S_IROTH | stat.S_IXOTH)
communicate("./sage", r"""
# make appropriate octave directory
octave.eval('1+2')
quit
""")
log.info("successfully compiled Sage")
def install_packages():
r"""
Assuming Sage is already installed, install optional packages.
"""
become_server()
os.chdir("sage")
log.info("installing optional Sage packages")
for package in sage_optional_packages:
check_call("./sage -i -y {}".format(package))
log.info("installing pip packages")
check_call("./sage -pip install --upgrade pip")
for package in python_packages:
check_call("./sage -pip install {}".format(package))
os.chdir("..")
def install_sagecell():
r"""
Install SageCell, assuming Sage and other packages are already installed.
"""
become_server()
log.info("compiling SageCell")
shutil.move("github/sagecell", ".")
shutil.rmtree("github")
os.chdir("sagecell")
with open("templates/provider.html", "w", encoding="utf-8") as f:
f.write(provider_html)
check_call("../sage/sage -sh -c 'make -B'")
log.info("successfully compiled SageCell")
def install_config_files():
r"""
Install container's config files, adjusting names inside.
"""
log.info("copying configuration files")
os.chdir(os.path.join("/home", users["server"],
"sagecell/contrib/vm/compute_node"))
def adjust_names(file):
with open(file) as f:
content = f.read()
for key, value in users.items():
content = content.replace("{%s}" % key, str(value))
with open(file, "w") as f:
f.write(content)
adjust_names(shutil.copy("config.py", "../../.."))
for root, _, files in os.walk("."):
if root == ".":
continue
for file in files:
name = os.path.join(root, file)
adjust_names(shutil.copy(name, name[1:]))
check_call("systemctl enable sagecell")
class SCLXC(object):
r"""
Wrapper for lxc.Container automatically performing prerequisite operations.
"""
def __init__(self, name):
self.name = name
self.c = lxc.Container(self.name)
def clone(self, clone_name, autostart=False, update=False):
r"""
Clone self, create a base container and destroy old clone if necessary.
"""
if not self.is_defined():
self.create()
if update:
self.update()
self.shutdown()
SCLXC(clone_name).destroy()
log.info("cloning %s to %s", self.name, clone_name)
if not self.c.clone(clone_name, flags=lxc.LXC_CLONE_SNAPSHOT):
raise RuntimeError("failed to clone " + self.name)
clone = SCLXC(clone_name)
if autostart:
clone.c.set_config_item("lxc.start.auto", "1")
clone.c.set_config_item("lxc.start.delay", str(start_delay))
clone.c.set_config_item("lxc.net.0.hwaddr",
"02:00:" + ":".join(["%02x" % random.randint(0, 255) for _ in range(4)]))
clone.c.save_config()
logdir = clone.c.get_config_item("lxc.rootfs.path") + "/var/log/"
for logfile in ["sagecell.log", "sagecell-console.log"]:
if os.path.exists(logdir + logfile):
os.remove(logdir + logfile)
return clone
def create(self):
r"""
Create a base contrainer, destroy old one if necessary.
"""
self.destroy()
log.info("creating %s", self.name)
# Try to automatically pick up proxy from host
os.environ["HTTP_PROXY"] = "apt"
if not self.c.create(
"download", 0,
{"dist": "ubuntu", "release": "noble", "arch": "amd64"},
"btrfs"):
raise RuntimeError("failed to create " + self.name)
os.environ.pop("HTTP_PROXY")
self.update()
# Need to preseed or there will be a dialog
self.inside(communicate, "/usr/bin/debconf-set-selections",
"tmpreaper tmpreaper/readsecurity note")
log.info("installing packages")
self.inside("apt install -y " + " ".join(system_packages))
# Relies on perl, so has to be after package installation
self.inside("/usr/sbin/deluser ubuntu --remove-home")
log.info("installing R packages")
for package in R_packages:
self.inside(f"""Rscript -e 'install.packages("{package}")'""")
self.inside(f"""Rscript -e 'library("{package}")'""")
def destroy(self):
r"""
Stop and destroy self if it exists.
"""
if self.c.defined:
log.info("destroying %s", self.name)
if self.c.running and not self.c.stop():
raise RuntimeError("failed to stop " + self.name)
if not self.c.destroy():
raise RuntimeError("failed to destroy " + self.name)
self.c = lxc.Container(self.name)
else:
log.debug("not destroying %s since it is not defined", self.name)
def inside(self, command, *args):
r"""
Run a function or a system command inside the container.
"""
self.start()
if isinstance(command, str):
command = command.format_map(users)
log.debug("executing '%s' in %s", command, self.name)
if self.c.attach_wait(lxc.attach_run_command,
shlex.split(command)):
raise RuntimeError("failed to execute '{}'".format(command))
else:
args = [arg.format_map(users) if isinstance(arg, str) else arg
for arg in args]
def wrapper():
command(*args)
os.sys.exit() # Otherwise attach_wait returns -1
log.debug("executing %s with arguments %s in %s",
command, args, self.name)
if self.c.attach_wait(wrapper):
raise RuntimeError("failed to execute {} with arguments {}"
.format(command, args))
def prepare_for_sagecell(self, keeprepos=False):
r"""
Set up everything necessary for SageCell installation.
INPUT:
- ``keeprepos`` -- if ``True``, GitHub repositories will NOT be updated
and set to proper state (useful for development).
"""
create_host_users()
self.inside(setup_container_users)
# FIXME: work with temp folders properly
self.inside(os.mkdir, "/tmp/sagecell", 0o730)
self.inside(os.chown, "/tmp/sagecell",
users["server_ID"], users["GID"])
self.inside(os.chmod, "/tmp/sagecell", stat.S_ISGID)
# Copy repositories into container
if not keeprepos:
update_repositories()
log.info("uploading repositories to %s", self.name)
root = self.c.get_config_item("lxc.rootfs.path")
home = os.path.join(root, "home", users["server"])
shutil.copytree("github", os.path.join(home, "github"), symlinks=True)
self.inside("chown -R {server}:{group} /home/{server}/github")
dot_cache = os.path.join(home, ".cache")
try:
shutil.copytree("dot_cache", dot_cache, symlinks=True)
self.inside("chown -R {server}:{group} /home/{server}/.cache")
except FileNotFoundError:
pass
self.inside(install_sage)
self.inside(install_packages)
# Remove old versions of packages
upstream = os.path.join(home, "sage/upstream")
packages = dict()
for f in os.listdir(upstream):
filename = os.path.join(upstream, f)
name = f.split("-", 1)[0]
if name not in packages:
packages[name] = []
packages[name].append((os.stat(filename).st_mtime, filename))
for package in packages.values():
package.sort()
package.pop()
for _, filename in package:
os.remove(filename)
try:
shutil.rmtree("github/sage/upstream")
except FileNotFoundError:
pass
shutil.move(upstream, "github/sage/upstream")
try:
shutil.rmtree("dot_cache")
except FileNotFoundError:
pass
shutil.copytree(dot_cache, "dot_cache", symlinks=True)
def install_sagecell(self):
r"""
Set up SageCell to run on startup.
"""
self.inside(install_sagecell)
self.inside(install_config_files)
self.c.set_config_item("lxc.cgroup.memory.limit_in_bytes", "8G")
self.c.save_config()
self.shutdown()
# Let first-time tasks to run and complete.
self.start()
timer_delay(start_delay)
def ip(self):
self.start()
return self.c.get_ips()[0]
def is_defined(self):
return self.c.defined
def save_logs(self):
stamp_length = len("2014-12-28 15:00:02,315")
root = self.c.get_config_item("lxc.rootfs.path")
logdir = os.path.join(root, "var", "log")
logname = "sagecell.log"
fullname = os.path.join(logdir, logname)
if not os.path.exists(fullname):
return
with open(fullname, "rb") as f:
start = f.read(stamp_length).decode()
f.seek(0, os.SEEK_END)
f.seek(max(f.tell() - 2**16, 0))
end = f.readlines()[-1][:stamp_length].decode()
archname = "container_logs/%s to %s on %s" % (start, end, self.name)
if not os.path.exists("container_logs"):
os.mkdir("container_logs")
log.info("saving %s", archname)
shutil.make_archive(archname, "bztar", logdir, logname)
def shutdown(self):
if self.c.running and not self.c.shutdown(timeout):
raise RuntimeError("failed to shutdown " + self.name)
def start(self):
r"""