forked from crocs-muni/rtt-deployment
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rtt_deploy_utils.py
616 lines (479 loc) · 22.2 KB
/
rtt_deploy_utils.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
import random
import string
import os
import sys
import re
import glob
import shutil
import shlex
import subprocess
import tempfile
from subprocess import call, Popen, PIPE
from common.clilogging import *
from common.rtt_constants import *
def try_fnc(fnc):
try:
return fnc()
except:
pass
def verify_output(ret_code, accept=[0], cmd=None):
if ret_code not in accept:
raise EnvironmentError("Command %s failed with code %s" % (cmd, accept))
def check_paths_abs(paths):
for p in paths:
if not os.path.isabs(p):
raise AssertionError("Path must be absolute: {}".format(p))
def check_paths_rel(paths):
for p in paths:
if os.path.isabs(p):
raise AssertionError("Path must be relative: {}".format(p))
def check_files_exists(paths):
for p in paths:
if not os.path.exists(p):
raise AssertionError("File does not exist: {}".format(p))
def get_no_empty(cfg, section, option):
rval = cfg.get(section, option)
if len(rval) == 0:
raise ValueError("option {} in section {} is empty."
.format(option, section))
return rval
def add_cron_job(script_path, ini_file_path, log_file_path, python3=None):
tmp_file_name = "cron.tmp"
script_base = os.path.splitext(os.path.basename(script_path))[0]
entry_val = script_path if not python3 else '%s %s' % (python3, script_path)
entry = "\n* * * * * /usr/bin/flock -n " \
"/var/tmp/{}.lock {} {} >> {} 2>&1\n" \
.format(script_base, entry_val, ini_file_path, log_file_path)
with open(tmp_file_name, "a") as tmp_file:
exec_sys_call_check("crontab -l", stdout=tmp_file,
acc_codes=[0, 1])
tmp_file.write(entry)
exec_sys_call_check("crontab {}".format(tmp_file_name))
os.remove(tmp_file_name)
def get_rnd_pwd(password_len=30):
spec_chars = "-_.!?+<>^="
characters = string.ascii_letters + string.digits + spec_chars
while True:
rval = "".join(random.SystemRandom().choice(characters) for _ in range(password_len))
if any(spec in rval for spec in spec_chars):
return rval
def create_file_wperms(fpath=None, mask=0o600, mode='w'):
# The default umask is 0o22 which turns off write permission of group and others
prev = os.umask(0)
try:
return open(os.open(fpath, os.O_CREAT | os.O_RDWR | os.O_EXCL, mask), mode)
finally:
os.umask(prev)
def backup_file(fpath, remove=False):
if not os.path.exists(fpath):
return
fdir = os.path.dirname(fpath)
fname = os.path.basename(fpath)
stat = os.stat(fpath)
mask = stat.st_mode & 0o777
ctr = 0
while True:
ctr += 1
cand = os.path.join(fdir, '%s.%03d' % (fname, ctr))
try:
with create_file_wperms(cand, mask) as fdst, open(fpath, 'r') as fsrc:
shutil.copyfileobj(fsrc, fdst)
os.chown(cand, uid=stat.st_uid, gid=stat.st_gid)
if remove:
os.unlink(fpath)
return cand
except Exception as e:
if ctr > 10000:
raise EnvironmentError("Could not create file: %s" % (e,))
continue
def service_enable(svc, enable=True):
return exec_sys_call_check("systemctl %s %s" % (svc, "enable" if enable else "disable"))
def install_debian_pkg(name, non_interactive=True, env=None):
env2use = env or os.environ.copy()
if non_interactive:
env2use['DEBIAN_FRONTEND'] = 'noninteractive'
rval = call(["apt", "install", name, "--yes"], env=env2use)
if rval != 0:
raise EnvironmentError("Installing package {}, error code: {}".format(name, rval))
def install_debian_pkgs(names, non_interactive=True, env=None):
env2use = env or os.environ.copy()
if non_interactive:
env2use['DEBIAN_FRONTEND'] = 'noninteractive'
rval = call(["apt", "install", "--yes", *names], env=env2use)
if rval != 0:
raise EnvironmentError("Installing packages {}, error code: {}".format(names, rval))
def install_debian_pkg_at_least_one(names, non_interactive=True, env=None):
for name in names:
try:
install_debian_pkg(name, non_interactive=non_interactive, env=env)
return True
except Exception as e:
pass
raise EnvironmentError("Installing packages {} failed".format(names))
def install_python_pkg(name, no_cache=True, pip3=None):
cache = ['--no-cache'] if no_cache else []
rval = call([pip3 or "pip3", "install", "-U", *cache, name])
if rval != 0:
raise EnvironmentError("Installing package {}, error code: {}".format(name, rval))
def install_python_pkgs(names, pip3=None):
rval = call([pip3 or "pip3", "install", "-U", "--no-cache", *names])
if rval != 0:
raise EnvironmentError("Installing package {}, error code: {}".format(names, rval))
def exec_sys_call(command, stdin=None, stdout=None, env=None, shell=False):
return call(shlex.split(command), stdin=stdin, stdout=stdout, env=env, shell=shell)
def exec_sys_call_check(command, stdin=None, stdout=None, acc_codes=[0], env=None, shell=False):
rval = call(shlex.split(command), stdin=stdin, stdout=stdout, env=env, shell=shell)
if rval not in acc_codes:
raise EnvironmentError("Executing command \'{}\', error code: {}"
.format(command, rval))
def exec_sys_call_raw_check(command, stdin=None, stdout=None, acc_codes=[0], env=None, shell=False):
rval = call(command, stdin=stdin, stdout=stdout, env=env, shell=shell)
if rval not in acc_codes:
raise EnvironmentError("Executing command \'{}\', error code: {}"
.format(command, rval))
def chmod_chown(path, mode=None, own="", grp=""):
chown_str = own
if grp != "":
chown_str += ":{}".format(grp)
if chown_str != "":
exec_sys_call_check("chown {} \'{}\'".format(chown_str, path))
if mode is not None:
os.chmod(path, mode)
def create_dir(path, mode, own="", grp=""):
if not os.path.exists(path):
os.mkdir(path)
chmod_chown(path, mode, own, grp)
def create_file(path, mode, own="", grp=""):
open(path, "a").close()
chmod_chown(path, mode, own, grp)
def recursive_chmod_chown(path, mod_f=None, mod_d=None, own="", grp=""):
if os.path.isdir(path):
chmod_chown(path, mod_d, own, grp)
for sub in os.listdir(path):
recursive_chmod_chown(os.path.join(path, sub),
mod_f, mod_d, own, grp)
else:
chmod_chown(path, mod_f, own, grp)
def get_make_env(buildj=2):
env = os.environ.copy()
env['MAKEFLAGS'] = os.environ.get('MAKEFLAGS', '') + (' -j%s' % (buildj,))
return env
def get_rtt_build_env(rtt_dir, libmariadbclient='/usr/lib/x86_64-linux-gnu/libmariadbclient.a', deb10=False,
deb11=False, p11libs=None):
env = os.environ.copy()
env['LD_LIBRARY_PATH'] = '%s:%s' % (os.getenv('LD_LIBRARY_PATH', ''), rtt_dir)
env['LD_RUN_PATH'] = '%s:%s' % (os.getenv('LD_RUN_PATH', ''), rtt_dir)
link_pthread = '-Wl,-Bdynamic -lpthread '
link_mysql = '-lmysqlcppconn -L%s -lmariadbclient' % libmariadbclient
if deb10 or deb11:
if p11libs:
env['LD_LIBRARY_PATH'] += ':%s' % (p11libs,)
env['LD_RUN_PATH'] += ':%s' % (p11libs,)
libs_deb10 = '-lgnutls -lhogweed -lnettle -ltasn1 -lgmp -lidn2'
libs_deb11 = '-lm -lssl -lcrypto -lz'
libs_cur = libs_deb10 if deb10 else libs_deb11
if deb11:
link_pthread += ' -ldl '
if p11libs:
link_mysql += ' -L"%s" %s -lunbound -lunistring ' \
'-lp11-kit-internal -lp11-library -lp11-common ' % (p11libs, libs_cur)
else:
link_mysql += ' %s -lunbound -lunistring ' % (libs_cur,)
link_pthread += ' -lp11-kit '
env['LINK_PTHREAD'] = link_pthread
env['LINK_MYSQL'] = link_mysql
env['LDFLAGS'] = '%s -Wl,-Bdynamic -ldl -lz -Wl,-Bstatic -static-libstdc++ -static-libgcc -L %s' \
% (os.getenv('LDFLAGS', ''), rtt_dir)
env['CXXFLAGS'] = '%s -Wl,-Bdynamic -ldl -lz -Wl,-Bstatic -static-libstdc++ -static-libgcc -L %s' \
% (os.getenv('CXXFLAGS', ''), rtt_dir)
return env
def build_p11_lib(release='https://github.com/p11-glue/p11-kit/releases/download/0.23.22/p11-kit-0.23.22.tar.xz',
buildj=2):
exec_sys_call_check("wget {}".format(release))
fname = glob.glob('p11*xz')[0]
exec_sys_call_check("tar -xvf {}".format(fname))
dname = fname.replace('.tar.xz', '')
os.chdir(dname)
try:
exec_sys_call_check("./configure --without-systemd --without-bash-completion --disable-trust-module "
"--without-libtasn1 --without-libffi")
exec_sys_call_check("make clean")
exec_sys_call_check("make -j%s" % (buildj,), acc_codes=[0, 1, 2, 3])
exec_sys_call_check("make -j%s" % (buildj,), acc_codes=[0, 1, 2, 3])
libs_dir = os.path.abspath(os.path.join(os.getcwd(), '.libs'))
if not os.path.exists(os.path.join(libs_dir, 'libp11-kit-internal.a')):
raise SystemError('The library p11-kit-internal.a was not found in built dir')
return libs_dir
finally:
os.chdir('..')
def copy_rtt_libs(rtt_dir):
from subprocess import Popen, PIPE
tbase = 'libmysqlcppconn'
target = 'libmysqlcppconn.so'
cand_paths = [
'/usr/lib/x86_64-linux-gnu',
'/lib64',
'/usr/lib',
'/lib',
]
def subcopy_fpath(fpath):
paths = glob.glob('%s/%s*' % (os.path.dirname(fpath), tbase))
for x in paths:
shutil.copy(x, rtt_dir)
print('Copied libs to RTT %s' % paths)
return glob.glob('%s/%s*.a' % (os.path.dirname(fpath), tbase))[0]
for cand in cand_paths:
fpath = os.path.join(cand, target)
if not os.path.exists(fpath):
continue
return subcopy_fpath(fpath)
# Fallback to find
cmd = 'find /usr/ /lib /lib64 /opt/ -name "libmysqlcppconn.so"'
p = Popen(shlex.split(cmd), stdout=PIPE, stderr=PIPE)
output, err = p.communicate()
results = output.decode('utf').split('\n')
for fpath in results:
fpath = fpath.strip()
if not fpath:
continue
if not os.path.exists(fpath):
continue
return subcopy_fpath(fpath)
raise EnvironmentError("Could not find %s library" % target)
def patch_upstream_dieahrder(env, deb11=False):
if deb11: # GCC 10 -fcommon, lenient global vars
env = os.environ.copy()
env['CPPFLAGS'] = '-fcommon'
env['CFLAGS'] = '-fcommon'
# Is fixed now in the upstream
exec_sys_call_check(
"sed -i -e 's#inline int insertBit#inline static int insertBit#g' libdieharder/dab_filltree2.c")
exec_sys_call_check(
"sed -i -e 's#inline int insert#inline static int insert#g' libdieharder/dab_filltree.c")
exec_sys_call_check(
"sed -i -e 's&#include <dieharder/rgb_operm.h>&//#include <dieharder/rgb_operm.h>&g' include/dieharder/tests.h")
exec_sys_call_check(
"sed -i -e 's#dieharder_LDADD = .*#dieharder_LDFLAGS = -static\\ndieharder_LDADD = -lgsl -lgslcblas -lm ../libdieharder/libdieharder.la#g' dieharder/Makefile.am")
exec_sys_call_check(
"sed -i -e 's#dieharder_LDADD = .*#dieharder_LDADD = -lgsl -lgslcblas -lm -static ../libdieharder/libdieharder.la#g' dieharder/Makefile.in")
return env
def build_static_dieharder(bat_dir, buildj=2, deb11=False):
ddir = glob.glob(os.path.join(bat_dir, 'dieharder-src/dieharder') + '*')
if not ddir or not os.path.exists(ddir[0]):
raise EnvironmentError("Could not find Dieharder sources in %s" % bat_dir)
env = None
ddir = ddir[0]
install_dir = os.path.join(ddir, '..', 'install')
cdir = os.getcwd()
os.chdir(ddir)
try:
# Upstream patch not needed, already working now in our patched version
# https://github.com/crocs-muni/rtt-statistical-batteries/commit/80386d016073aca5d2e1570a9906f931b24b0589
# env = patch_upstream_dieahrder(env, deb11)
exec_sys_call_check("autoreconf -i", env=env)
exec_sys_call_check("chmod +x configure", env=env)
exec_sys_call_check("./configure --disable-shared --enable-static --prefix=%s --enable-static=dieharder" % install_dir, env=env)
exec_sys_call_check("make clean", env=env)
exec_sys_call_check("make -j%s" % (buildj,), acc_codes=[0, 1, 2, 3], env=env)
exec_sys_call_check("make -j%s" % (buildj,), acc_codes=[0, 1, 2, 3], env=env)
exec_sys_call_check("make install", env=env)
finally:
os.chdir(cdir)
def submit_experiment_deploy(cdir=None, pip3=None):
install_python_pkgs([
"pyinstaller", "filelock", "jsonpath-ng", "booltest", "booltest-rtt"
], pip3=pip3)
return submit_experiment_build(cdir)
def submit_experiment_build(cdir=None):
current_dir = os.path.abspath(os.path.curdir)
try:
if cdir:
os.chdir(cdir)
submit_exp_base_name = os.path.splitext(Frontend.SUBMIT_EXPERIMENT_SCRIPT)[0]
exec_sys_call_check("pyinstaller -F {}".format(Frontend.SUBMIT_EXPERIMENT_SCRIPT))
shutil.move("dist/{}".format(submit_exp_base_name),
Frontend.SUBMIT_EXPERIMENT_BINARY)
res = os.path.abspath(Frontend.SUBMIT_EXPERIMENT_BINARY)
chmod_chown(Frontend.SUBMIT_EXPERIMENT_BINARY, 0o2775, grp=Frontend.RTT_ADMIN_GROUP)
shutil.rmtree("dist")
shutil.rmtree("build")
shutil.rmtree("__pycache__", ignore_errors=True)
os.remove("{}.spec".format(submit_exp_base_name))
return res
finally:
os.chdir(current_dir)
def cryptostreams_get_repo(ph4=False):
if ph4:
return CommonConst.CRYPTOSTREAMS_REPO_PH4, CommonConst.CRYPTOSTREAMS_REPO_BRANCH_PH4
else:
return CommonConst.CRYPTOSTREAMS_REPO, CommonConst.CRYPTOSTREAMS_REPO_BRANCH
def cryptostreams_clone(repo, branch, dst=None):
return exec_sys_call_check("git clone --recursive --branch %s %s %s" % (branch, repo, dst if dst else ''))
def cryptostreams_build(cdir=None, buildj=2):
current_dir = os.path.abspath(os.path.curdir)
if cdir:
os.chdir(cdir)
try:
BUILD_DIR = 'build'
try_fnc(lambda: shutil.rmtree(BUILD_DIR))
os.makedirs(BUILD_DIR)
os.chdir(BUILD_DIR)
exec_sys_call_check("cmake ..", acc_codes=[0, 1, 2])
exec_sys_call_check("make -j%s" % (buildj,), acc_codes=[0, 1, 2])
exec_sys_call_check("make -j%s" % (buildj,), acc_codes=[0, 1, 2])
return os.path.abspath('./crypto-streams')
finally:
os.chdir(current_dir)
def cryptostreams_link(crypto_dir, crypto_bin, ph4=False, res_bin_dir='/usr/bin'):
cmd = 'git -C "%s" rev-parse HEAD' % crypto_dir
p = Popen(shlex.split(cmd), stdout=PIPE, stderr=PIPE)
output, err = p.communicate()
verify_output(p.returncode, cmd="CryptoStreams git rev-parse HEAD")
output = output.decode("utf8").strip()
ph4mod = '-ph4' if ph4 else ''
bname = 'crypto-streams-v3.0%s-%s' % (ph4mod, output[:12])
cpath = os.path.abspath(os.path.join(res_bin_dir, bname))
try_fnc(lambda: os.unlink(cpath))
shutil.copy(crypto_bin, cpath)
os.chmod(cpath, 0o755)
lnks = [
os.path.join(res_bin_dir, 'crypto-streams-v3.0'),
os.path.join(res_bin_dir, 'crypto-streams')]
for lnk in lnks:
try_fnc(lambda: os.unlink(lnk))
os.symlink(cpath, lnk)
return [cpath, *lnks]
def cryptostreams_complete_deploy(ph4=False, res_bin_dir='/usr/bin', src_dir=CommonConst.USR_SRC,
crypto_dir=CommonConst.CRYPTOSTREAMS_SRC_DIR, buildj=2):
install_debian_pkgs(["cmake"])
install_debian_pkg_at_least_one(["libboost-random1.74-dev", "libboost-random1.67-dev", "libboost-random1.62-dev"])
current_dir = os.path.abspath(os.path.curdir)
try:
os.chdir(src_dir)
crypto_repo, crypto_branch = cryptostreams_get_repo(ph4)
if os.path.exists(crypto_dir):
shutil.rmtree(crypto_dir)
cryptostreams_clone(crypto_repo, crypto_branch, crypto_dir)
cbin = cryptostreams_build(crypto_dir, buildj=buildj)
return cryptostreams_link(crypto_dir, cbin, ph4=ph4, res_bin_dir=res_bin_dir)
finally:
os.chdir(current_dir)
def set_cfg_value(key, value, cfg_path, sep="="):
sed_string = r"s_\({}\s*\){}\s*.*_\1= {}_".format(key, sep, value)
rval = subprocess.call(["sed", "-i", sed_string, cfg_path])
if rval != 0:
raise EnvironmentError("Executing sed command \'{}\', error code: {}"
.format(sed_string, rval))
def comment_cfg_line(line_content, cfg_path):
sed_string = r"s_\(.*{}.*\)_# \1_".format(line_content)
rval = subprocess.call(["sed", "-i", sed_string, cfg_path])
if rval != 0:
raise EnvironmentError("Executing sed command \'{}\', error code: {}"
.format(sed_string, rval))
def get_mysql_password_args(args=None):
if not args:
return None
db_def_passwd = None
if 'mysql_pass_file' in args and args.mysql_pass_file:
with open(args.mysql_pass_file, 'r') as fh:
db_def_passwd = fh.read().strip()
if 'mysql_pass' in args and args.mysql_pass is not None:
db_def_passwd = args.mysql_pass
return db_def_passwd
def write_db_credentials(username, password, config_path):
import configparser
cred_mysql_db_cfg = configparser.ConfigParser()
cred_mysql_db_cfg.add_section("Credentials")
cred_mysql_db_cfg.set("Credentials", "Username", username)
cred_mysql_db_cfg.set("Credentials", "Password", password)
if config_path:
with open(config_path, "w") as f:
cred_mysql_db_cfg.write(f)
return cred_mysql_db_cfg
def write_db_credentials_json(username, password, config_path):
import json
cred_mysql_db_json = {
"credentials": {
"username": username,
"password": password
}
}
if config_path:
with open(config_path, "w") as f:
json.dump(cred_mysql_db_json, f, indent=4)
return cred_mysql_db_json
def write_ssh_credentials(username, password, keyfile, config_path):
import configparser
cred_store_ssh_cfg = configparser.ConfigParser()
cred_store_ssh_cfg.add_section("Credentials")
cred_store_ssh_cfg.set("Credentials", "Username", username)
cred_store_ssh_cfg.set("Credentials", "Private-key-file", keyfile)
cred_store_ssh_cfg.set("Credentials", "Private-key-password", password)
if config_path:
with open(config_path, "w") as f:
cred_store_ssh_cfg.write(f)
return cred_store_ssh_cfg
def write_db_credentials_web(username, password, db_name, config_path, address='127.0.0.1', port='3306'):
import configparser
sec = 'MySQL-Database'
cred_mysql_db_cfg = configparser.ConfigParser()
cred_mysql_db_cfg.add_section(sec)
cred_mysql_db_cfg.set(sec, "Name", db_name)
cred_mysql_db_cfg.set(sec, "Address", address)
cred_mysql_db_cfg.set(sec, "Port", '%s' % port)
cred_mysql_db_cfg.set(sec, "Username", username)
cred_mysql_db_cfg.set(sec, "Password", password)
if config_path:
with open(config_path, "w") as f:
cred_mysql_db_cfg.write(f)
return cred_mysql_db_cfg
def install_python_3(buildj=2, main_install=False, python_version='3.9.11', python_version_major='3.9'):
exec_sys_call_check("apt install -y build-essential automake curl sudo zlib1g-dev libncurses5-dev libgdbm-dev "
"libnss3-dev libssl-dev libsqlite3-dev libreadline-dev libffi-dev curl libbz2-dev "
"liblzma-dev uuid-dev",
acc_codes=[0, 1])
os.chdir("/tmp")
exec_sys_call_check(f"curl -O https://www.python.org/ftp/python/{python_version}/Python-{python_version}.tar.xz")
exec_sys_call_check(f"tar -xf Python-{python_version}.tar.xz")
os.chdir(f"Python-{python_version}")
exec_sys_call_check("./configure --enable-optimizations --enable-shared --enable-loadable-sqlite-extensions")
exec_sys_call_check("make -j%s" % (buildj,))
if main_install:
exec_sys_call_check("sudo -EH make install")
else:
exec_sys_call_check("sudo -EH make altinstall")
tmplib = tempfile.NamedTemporaryFile('w+')
tmplib.write(f'# Python {python_version} installed from sources\n')
tmplib.write('/usr/local/lib\n')
tmplib.flush()
exec_sys_call_check(f"sudo cp \"{os.path.abspath(tmplib.name)}\" /etc/ld.so.conf.d/python_{python_version.replace('.', '_')}")
exec_sys_call_check("sudo ldconfig")
tmplib.close()
if not os.path.exists("/usr/local/bin/python3") and os.path.exists(f"/usr/local/bin/python{python_version_major}"):
os.symlink(f"/usr/local/bin/python{python_version_major}", "/usr/local/bin/python3")
if not os.path.exists("/usr/local/bin/pip3") and os.path.exists(f"/usr/local/bin/pip{python_version_major}"):
os.symlink(f"/usr/local/bin/pip{python_version_major}", "/usr/local/bin/pip3")
def setup_python3(buildj=2, main_install=False, use_system=False, check_already_installed=True):
python_version = '3.11.0'
python_version_major = '.'.join(python_version.split('.')[:-1])
if use_system:
install_debian_pkgs(["python3-pip", "python3-cryptography", "python3-paramiko"])
return None, None
if check_already_installed and not main_install \
and os.path.exists(f'/usr/local/bin/python{python_version_major}') \
and os.path.exists(f'/usr/local/bin/pip{python_version_major}') \
and os.path.exists('/usr/local/bin/python3') \
and os.path.exists('/usr/local/bin/pip3'):
return '/usr/local/bin/python3', '/usr/local/bin/pip3'
install_python_3(buildj=buildj, main_install=main_install, python_version=python_version, python_version_major=python_version_major)
return f'/usr/local/bin/python{python_version_major}', f'/usr/local/bin/pip{python_version_major}'
def get_debian_version():
with open('/etc/os-release') as fh:
lines = [x.strip() for x in fh.readlines()]
ln = [x for x in lines if x.startswith('VERSION_ID')]
if not ln:
return None
m = re.match(r'.*"(.*)".*', ln[0])
if not m:
return None
return int(m.group(1))