-
Notifications
You must be signed in to change notification settings - Fork 58
Expand file tree
/
Copy pathinstall
More file actions
2543 lines (2199 loc) · 89.5 KB
/
Copy pathinstall
File metadata and controls
2543 lines (2199 loc) · 89.5 KB
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/python3
import hashlib
import io
import json
import os
import random
import shutil
import socket
import subprocess
import sys
import tarfile
import time
import urllib.request
import zipfile
if sys.version_info.major != 3:
print("Please run with python3.")
sys.exit(1)
rPath = os.path.dirname(os.path.realpath(__file__))
# Distribuciones soportadas
SUPPORTED_DISTROS = {
"ubuntu": ["18.04", "20.04", "22.04", "24.04"],
"debian": ["11", "12", "13"],
"rocky": ["8", "9"],
"almalinux": ["8", "9"],
"centos": ["7", "8"],
"rhel": ["8", "9"],
}
PACKAGES = {
"debian": [
"iproute2",
"net-tools",
"dirmngr",
"gpg-agent",
"software-properties-common",
"libcurl4",
"libgeoip-dev",
"libxslt1-dev",
"libonig-dev",
"e2fsprogs",
"wget",
"mariadb-server",
"mariadb-client",
"sysstat",
"alsa-utils",
"v4l-utils",
"certbot",
"iptables-persistent",
"libjpeg-dev",
"libpng-dev",
"libharfbuzz-dev",
"libfribidi-dev",
"libogg0",
"libnuma1",
"xz-utils",
"zip",
"unzip",
"libssh2-1",
"libsodium23",
"cpufrequtils",
"mcrypt",
"cron",
"git",
"curl",
],
"debian13": [
"iproute2",
"net-tools",
"dirmngr",
"gpg-agent",
"software-properties-common",
"libcurl4",
"wget",
"unzip",
"zip",
"xz-utils",
"cron",
"git",
"sysstat",
"perl",
"gawk",
"socat",
"libxml2-dev",
"libxslt1-dev",
"libonig5",
"libonig-dev",
"zlib1g-dev",
"libssl-dev",
"pkg-config",
"autoconf",
"automake",
"alsa-utils",
"v4l-utils",
"e2fsprogs",
"certbot",
"iptables-persistent",
"libssh2-1",
"libssh2-1-dev",
"mariadb-server",
"mariadb-client",
"mariadb-common",
"libjpeg-dev",
"libpng-dev",
"libharfbuzz-dev",
"libfribidi-dev",
"libgeoip1",
"geoip-bin",
"libsodium23",
"cpufrequtils",
"mcrypt",
"libnuma1",
],
"ubuntu20": [
"iproute2",
"net-tools",
"dirmngr",
"gpg-agent",
"software-properties-common",
"wget",
"curl",
"unzip",
"zip",
"xz-utils",
"cron",
"git",
"sysstat",
"ca-certificates",
"libcurl4-gnutls-dev",
"libxml2-dev",
"libxslt1-dev",
"libonig5",
"libonig-dev",
"libjpeg-dev",
"libpng-dev",
"zlib1g-dev",
"alsa-utils",
"v4l-utils",
"e2fsprogs",
"iptables-persistent",
"certbot",
"python3-certbot",
"libssh2-1",
"libssh2-1-dev",
"mariadb-server",
"mariadb-client",
"mariadb-common",
"libsodium23",
"cpufrequtils",
"mcrypt",
"libnuma1",
],
"ubuntu22": [
"iproute2",
"net-tools",
"dirmngr",
"gpg-agent",
"software-properties-common",
"libcurl4",
"libgeoip-dev",
"libxslt1-dev",
"libonig-dev",
"e2fsprogs",
"wget",
"curl",
"unzip",
"zip",
"xz-utils",
"cron",
"git",
"sysstat",
"ca-certificates",
"libxml2-dev",
"libonig5",
"zlib1g-dev",
"mariadb-server",
"mariadb-client",
"mariadb-common",
"alsa-utils",
"v4l-utils",
"certbot",
"python3-certbot",
"iptables-persistent",
"libjpeg-dev",
"libpng-dev",
"libharfbuzz-dev",
"libfribidi-dev",
"libogg0",
"libnuma1",
"libssh2-1",
"libssh2-1-dev",
"libsodium23",
"cpufrequtils",
"mcrypt",
],
"ubuntu24": [
"iproute2",
"net-tools",
"dirmngr",
"gpg-agent",
"software-properties-common",
"libcurl4t64",
"wget",
"unzip",
"zip",
"xz-utils",
"cron",
"git",
"sysstat",
"perl",
"gawk",
"socat",
"libxml2-dev",
"libxslt1-dev",
"libonig5",
"libonig-dev",
"zlib1g-dev",
"libssl-dev",
"pkg-config",
"autoconf",
"automake",
"alsa-utils",
"v4l-utils",
"e2fsprogs",
"certbot",
"python3-certbot",
"ufw",
"libssh2-1t64",
"libssh2-1-dev",
"mariadb-server",
"mariadb-client",
"mariadb-common",
"libjpeg-dev",
"libpng-dev",
"libharfbuzz-dev",
"libfribidi-dev",
"libgeoip1t64",
"geoip-bin",
"libsodium23",
"cpufrequtils",
"mcrypt",
"libnuma1",
],
"debian11": [
"iproute2",
"net-tools",
"dirmngr",
"gpg-agent",
"software-properties-common",
"libcurl4",
"libgeoip-dev",
"libxslt1-dev",
"libonig-dev",
"e2fsprogs",
"wget",
"curl",
"unzip",
"zip",
"xz-utils",
"cron",
"git",
"sysstat",
"mariadb-server",
"mariadb-client",
"mariadb-common",
"alsa-utils",
"v4l-utils",
"certbot",
"iptables-persistent",
"libjpeg-dev",
"libpng-dev",
"libharfbuzz-dev",
"libfribidi-dev",
"libogg0",
"libnuma1",
"libssh2-1",
"libssh2-1-dev",
"libsodium23",
"cpufrequtils",
"mcrypt",
],
"redhat": [
"epel-release",
"wget",
"mariadb-server",
"mariadb",
"sysstat",
"alsa-utils",
"v4l-utils",
"libcurl-devel",
"geoip-devel",
"libxslt-devel",
"oniguruma-devel",
"e2fsprogs",
"libjpeg-turbo-devel",
"libpng-devel",
"harfbuzz-devel",
"fribidi-devel",
"libogg",
"xz",
"zip",
"unzip",
"libssh2-devel",
"cronie",
"certbot",
"iptables-services",
"GeoIP-update",
"git",
"curl",
"libsodium",
"numactl",
"kernel-tools",
],
}
rRemove = ["mysql-server"]
rMySQLCnfTemplate = """\
# XC_VM
[client]
port = 3306
[mysqld_safe]
nice = 0
[mysqld]
user = mysql
port = 3306
basedir = /usr
datadir = /var/lib/mysql
tmpdir = /tmp
lc-messages-dir = /usr/share/mysql
skip-external-locking
skip-name-resolve
bind-address = *
# MyISAM
key_buffer_size = {{KEY_BUFFER}}M
myisam_sort_buffer_size = 4M
myisam-recover-options = BACKUP
max_length_for_sort_data = 4096
# Connections
max_connections = {{MAX_CONNECTIONS}}
back_log = {{BACK_LOG}}
max_connect_errors = 1000
# Packet and cache
max_allowed_packet = 16M
open_files_limit = 2048
innodb_open_files = 1024
table_open_cache = 1024
table_definition_cache = 1024
# Temp tables
tmp_table_size = {{TMP_TABLE_SIZE}}M
max_heap_table_size = {{TMP_TABLE_SIZE}}M
# InnoDB
innodb_buffer_pool_size = {{BUFFER_POOL_SIZE}}
innodb_buffer_pool_instances = {{BUFFER_POOL_INSTANCES}}
innodb_read_io_threads = 4
innodb_write_io_threads = 4
innodb_flush_log_at_trx_commit = 1
innodb_flush_method = O_DIRECT
innodb_file_per_table = 1
innodb_io_capacity = 1000
innodb_table_locks = 1
innodb_lock_wait_timeout = 30
# Logging
expire_logs_days = 7
max_binlog_size = 64M
# Query cache - disabled
query_cache_limit = 0
query_cache_size = 0
query_cache_type = 0
performance_schema = 0
sql_mode = "NO_ENGINE_SUBSTITUTION"
[mariadb]
thread_cache_size = {{THREAD_CACHE}}
thread_handling = pool-of-threads
thread_pool_size = 4
thread_pool_idle_timeout = 20
thread_pool_max_threads = {{THREAD_POOL_MAX_THREADS}}
[mysqldump]
quick
quote-names
max_allowed_packet = 16M
[mysql]
[isamchk]
key_buffer_size = 8M"""
rConfig = """\
; XC_VM Configuration
; -----------------
; To change your username or password, modify BOTH
; below and XC_VM will read and re-encrypt them.
[XC_VM]
hostname = "127.0.0.1"
database = "xc_vm"
port = 3306
server_id = 1
[Encrypted]
username = "%s"
password = "%s"
"""
rSysCtl = """\
# XC_VM
net.ipv4.tcp_congestion_control = bbr
net.core.default_qdisc = fq
net.ipv4.tcp_rmem = 8192 87380 134217728
net.ipv4.udp_rmem_min = 16384
net.core.rmem_default = 262144
net.core.rmem_max = 268435456
net.ipv4.tcp_wmem = 8192 65536 134217728
net.ipv4.udp_wmem_min = 16384
net.core.wmem_default = 262144
net.core.wmem_max = 268435456
net.core.somaxconn = 1000000
net.core.netdev_max_backlog = 250000
net.core.optmem_max = 65535
net.ipv4.tcp_max_tw_buckets = 1440000
net.ipv4.tcp_max_orphans = 16384
net.ipv4.ip_local_port_range = 2000 65000
net.ipv4.tcp_no_metrics_save = 1
net.ipv4.tcp_slow_start_after_idle = 0
net.ipv4.tcp_fin_timeout = 15
net.ipv4.tcp_keepalive_time = 300
net.ipv4.tcp_keepalive_probes = 5
net.ipv4.tcp_keepalive_intvl = 15
fs.file-max=20970800
fs.nr_open=20970800
fs.aio-max-nr=20970800
net.ipv4.tcp_timestamps = 1
net.ipv4.tcp_window_scaling = 1
net.ipv4.tcp_mtu_probing = 1
net.ipv4.route.flush = 1
net.ipv6.route.flush = 1"""
rSystemd = """\
[Unit]
SourcePath=/home/xc_vm/service
Description=XC_VM Service
After=network.target
StartLimitIntervalSec=0
[Service]
Type=simple
User=root
Restart=always
RestartSec=1
LimitNOFILE=655350
TimeoutStopSec=30
KillMode=mixed
ExecStart=/bin/bash /home/xc_vm/service start
ExecStop=/bin/bash /home/xc_vm/service stop
ExecReload=/bin/bash /home/xc_vm/service restart
[Install]
WantedBy=multi-user.target"""
rChoice = "23456789abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ"
rConfigPath = "/home/xc_vm/config/config.ini"
class col:
HEADER = "\033[95m"
OKBLUE = "\033[94m"
OKGREEN = "\033[92m"
WARNING = "\033[93m"
FAIL = "\033[91m"
ENDC = "\033[0m"
BOLD = "\033[1m"
UNDERLINE = "\033[4m"
# Check if running as root
def check_root():
"""Check if script is running as root"""
if os.geteuid() != 0:
printc("This script must be run as root.", col.FAIL)
printc("Please use: su -c 'python3 your_script_name.py'", col.OKBLUE)
sys.exit(1)
# Install prerequisites
def install_prerequisites(dist_info):
"""Install prerequisites like sudo and curl if they are missing"""
if dist_info["family"] == "debian":
printc("Checking for prerequisites (sudo, curl)...", col.OKBLUE)
# Check if sudo exists
ret, _, _ = run_command("which sudo", capture_output=True)
sudo_missing = ret != 0
# Check if curl exists
ret, _, _ = run_command("which curl", capture_output=True)
curl_missing = ret != 0
if sudo_missing or curl_missing:
printc("Installing missing prerequisites...", col.WARNING)
printc("Updating package lists...", col.OKBLUE)
run_command("apt-get update -y")
packages_to_install = []
if sudo_missing:
packages_to_install.append("sudo")
if curl_missing:
packages_to_install.append("curl")
if packages_to_install:
packages_str = " ".join(packages_to_install)
printc(f"Installing {packages_str}...", col.OKBLUE)
run_command(f"apt-get install -y {packages_str}")
printc("Prerequisites installed successfully.", col.OKGREEN)
else:
printc("Prerequisites (sudo, curl) are already installed.", col.OKGREEN)
elif dist_info["family"] == "redhat":
printc("Checking for prerequisites (sudo, curl, wget)...", col.OKBLUE)
ret, _, _ = run_command("which sudo", capture_output=True)
sudo_missing = ret != 0
ret, _, _ = run_command("which curl", capture_output=True)
curl_missing = ret != 0
ret, _, _ = run_command("which wget", capture_output=True)
wget_missing = ret != 0
if sudo_missing or curl_missing or wget_missing:
printc("Installing missing prerequisites...", col.WARNING)
packages_to_install = []
if sudo_missing:
packages_to_install.append("sudo")
if curl_missing:
packages_to_install.append("curl")
if wget_missing:
packages_to_install.append("wget")
if packages_to_install:
packages_str = " ".join(packages_to_install)
printc(f"Installing {packages_str}...", col.OKBLUE)
run_command(
f"yum install -y {packages_str} || dnf install -y {packages_str}"
)
printc("Prerequisites installed successfully.", col.OKGREEN)
else:
printc("Prerequisites are already installed.", col.OKGREEN)
def compute_md5(file_path):
"""Compute MD5 hash of a file"""
md5 = hashlib.md5()
with open(file_path, "rb") as f:
for chunk in iter(lambda: f.read(8192), b""):
md5.update(chunk)
return md5.hexdigest()
def download_release_hash(repo, release_tag, file_name):
"""Download hashes.md5 from a GitHub release and return the hash for file_name"""
hash_url = f"https://github.com/Vateron-Media/{repo}/releases/download/{release_tag}/hashes.md5"
try:
req = urllib.request.Request(hash_url)
req.add_header("User-Agent", "XC_VM-Installer/1.0")
with urllib.request.urlopen(req, timeout=15) as response:
content = response.read().decode().strip()
for line in content.split("\n"):
line = line.strip()
if not line:
continue
parts = line.split(None, 1)
if len(parts) == 2 and parts[1] == file_name:
return parts[0]
except Exception as e:
printc(f"Warning: Could not download hash file: {e}", col.WARNING)
return None
def get_latest_binaries_tag():
"""Get the latest release tag from XC_VM_Binaries GitHub repo"""
api_url = (
"https://api.github.com/repos/Vateron-Media/XC_VM_Binaries/releases/latest"
)
try:
req = urllib.request.Request(api_url)
req.add_header("User-Agent", "XC_VM-Installer/1.0")
with urllib.request.urlopen(req, timeout=15) as response:
data = json.loads(response.read().decode())
return data["tag_name"]
except Exception as e:
printc(f"Failed to get latest binaries release tag: {e}", col.WARNING)
return None
def write_bin_version_file(release_tag, asset_name, dist_id, version):
"""Write installed binaries release metadata to /home/xc_vm/bin/bin_version.json"""
version_path = "/home/xc_vm/bin/bin_version.json"
payload = {
"owner": "Vateron-Media",
"repository": "XC_VM_Binaries",
"release": release_tag,
"asset": asset_name,
"distribution": dist_id,
"distribution_version": version,
"updated_at_utc": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
}
try:
with open(version_path, "w", encoding="utf-8") as f:
json.dump(payload, f, indent=4)
f.write("\n")
try:
run_command(f"chown xc_vm:xc_vm {version_path}")
except Exception:
pass
printc(
f"Binaries version file updated: {version_path} ({release_tag})",
col.OKGREEN,
)
return True
except Exception as e:
printc(f"Warning: Failed to update {version_path}: {e}", col.WARNING)
return False
# Install distribution-specific binaries
def install_distribution_binaries(dist_id, version):
"""Download and install distribution-specific binaries from GitHub releases"""
printc(f"Installing {dist_id} {version} specific binaries...", col.OKBLUE)
# Determinar el nombre del archivo en GitHub releases
major = version.split(".")[0]
if dist_id == "ubuntu":
if major in ["18", "20", "22", "24"]:
patch_name = f"ubuntu_{major}.tar.gz"
display_name = f"Ubuntu {major}"
else:
printc(f"Ubuntu version {version} not supported for patches", col.WARNING)
return False
elif dist_id == "debian":
if major in ["11", "12", "13"]:
patch_name = f"debian_{major}.tar.gz"
display_name = f"Debian {major}"
else:
printc(f"Debian version {version} not supported for patches", col.WARNING)
return False
elif dist_id in ["rocky", "almalinux", "rhel", "centos"]:
if major in ["8", "9"]:
patch_name = f"rhel_{major}.tar.gz"
display_name = f"RHEL/Rocky/Alma {major}"
else:
printc(
f"{dist_id} version {version} not supported for patches", col.WARNING
)
return False
else:
printc(f"Distribution {dist_id} not supported for patches", col.WARNING)
return False
# Get latest release tag from GitHub
release_tag = get_latest_binaries_tag()
if not release_tag:
printc("Could not determine latest binaries release, skipping", col.WARNING)
return False
remote_url = f"https://github.com/Vateron-Media/XC_VM_Binaries/releases/download/{release_tag}/{patch_name}"
temp_tar_file = f"/tmp/{patch_name}"
temp_extract_dir = f"/tmp/{patch_name.replace('.tar.gz', '_extract')}"
try:
# Always download fresh binaries from GitHub
printc(
f"Downloading {display_name} binaries from GitHub release {release_tag}...",
col.OKBLUE,
)
printc(f"URL: {remote_url}", col.OKBLUE)
# Remove old file if exists
if os.path.exists(temp_tar_file):
os.remove(temp_tar_file)
# Retry on transient network/DNS failures (e.g. resolver not ready yet).
last_err = None
for attempt in range(1, 5):
try:
urllib.request.urlretrieve(remote_url, temp_tar_file)
last_err = None
break
except Exception as e:
last_err = e
printc(f"Download attempt {attempt}/4 failed: {e}", col.WARNING)
time.sleep(5)
if last_err is not None:
raise last_err
if not (os.path.exists(temp_tar_file) and os.path.getsize(temp_tar_file) > 0):
printc(f"Failed to download {display_name} binaries", col.FAIL)
return False
# MD5 verification
expected_hash = download_release_hash("XC_VM_Binaries", release_tag, patch_name)
if expected_hash:
actual_hash = compute_md5(temp_tar_file)
if actual_hash != expected_hash:
printc(f"MD5 verification failed for {patch_name}: expected {expected_hash}, got {actual_hash}", col.FAIL)
os.remove(temp_tar_file)
return False
printc(f"MD5 verification passed for {patch_name}", col.OKGREEN)
else:
printc(f"Warning: Could not retrieve MD5 hash for {patch_name}, skipping verification", col.WARNING)
file_size_mb = os.path.getsize(temp_tar_file) / (1024 * 1024)
printc(
f"{display_name} binaries downloaded: {file_size_mb:.1f} MB", col.OKGREEN
)
# 2. Clean previous extraction directory if exists
if os.path.exists(temp_extract_dir):
shutil.rmtree(temp_extract_dir)
# 3. Extract to temporary directory
printc(
f"Extracting {display_name} binaries to temporary location...", col.OKBLUE
)
with tarfile.open(temp_tar_file, "r:gz") as tar:
tar.extractall(
path=temp_extract_dir, members=_safe_tar_members(tar, temp_extract_dir)
)
# Auto-detect directory structure
major = version.split(".")[0]
# Variants: debian11, debian_11, ubuntu20, ubuntu_20
distro_variants = [
f"{dist_id}{major}",
f"{dist_id}_{major}",
]
# Possible paths where binaries might be
possible_paths = []
for dname in distro_variants:
possible_paths.append(os.path.join(temp_extract_dir, dname, "bin"))
possible_paths.append(os.path.join(temp_extract_dir, dname))
possible_paths.append(os.path.join(temp_extract_dir, "bin"))
possible_paths.append(temp_extract_dir)
source_bin_dir = None
for path in possible_paths:
if os.path.exists(path):
# Check if it contains binary files or typical directories
contents = os.listdir(path)
has_binaries = any(
item in contents for item in ["php", "nginx", "nginx_rtmp", "bin"]
)
if has_binaries or path.endswith("/bin"):
source_bin_dir = path
printc(f"Structure found: {source_bin_dir}", col.OKGREEN)
break
# If not found in expected paths, search recursively
if not source_bin_dir:
printc("Searching directory structure recursively...", col.OKBLUE)
for root, dirs, files in os.walk(temp_extract_dir):
# Search for directories containing typical binaries
if any(item in dirs for item in ["php", "nginx", "nginx_rtmp", "bin"]):
source_bin_dir = root
printc(
f"Estructura encontrada recursivamente: {source_bin_dir}",
col.OKGREEN,
)
break
target_bin_dir = "/home/xc_vm/bin"
if not source_bin_dir:
printc(
"Error: No se pudo encontrar la estructura de binarios en el parche.",
col.FAIL,
)
printc(
f"Contenido de {temp_extract_dir}: {os.listdir(temp_extract_dir)}",
col.WARNING,
)
# Show full structure for debugging
printc("Full structure of extracted directory:", col.WARNING)
for root, dirs, files in os.walk(temp_extract_dir):
level = root.replace(temp_extract_dir, "").count(os.sep)
indent = " " * 2 * level
printc(f"{indent}{os.path.basename(root)}/", col.WARNING)
subindent = " " * 2 * (level + 1)
for file in files[:10]: # Limit to 10 files to avoid clutter
printc(f"{subindent}{file}", col.WARNING)
if len(files) > 10:
printc(
f"{subindent}... and {len(files) - 10} more files", col.WARNING
)
return False
# 4. Replace specific files, not the entire directory
printc(
f"Replacing specific binaries with {display_name} versions...",
col.OKBLUE,
)
# Recursively walk source directory files
for root, dirs, files in os.walk(source_bin_dir):
# Calculate relative path from source directory
rel_path = os.path.relpath(root, source_bin_dir)
# Create corresponding target directories if they don't exist
if rel_path != ".":
target_dir = os.path.join(target_bin_dir, rel_path)
os.makedirs(target_dir, exist_ok=True)
# Copy files
for file in files:
source_file = os.path.join(root, file)
if rel_path == ".":
target_file = os.path.join(target_bin_dir, file)
else:
target_file = os.path.join(target_bin_dir, rel_path, file)
# Create directories if needed
os.makedirs(os.path.dirname(target_file), exist_ok=True)
# Copy file (overwriting if exists)
shutil.copy2(source_file, target_file)
# printc(f"Updated: {target_file}", col.OKBLUE)
printc(f"{display_name} binaries updated successfully", col.OKGREEN)
# 5. Set permissions on key executables
printc(f"Setting permissions for {display_name} binaries...", col.OKBLUE)
executables_to_chmod = [
"/home/xc_vm/bin/php/bin/php",
"/home/xc_vm/bin/php/sbin/php-fpm",
"/home/xc_vm/bin/nginx/sbin/nginx",
"/home/xc_vm/bin/nginx_rtmp/sbin/nginx_rtmp",
]
for exe_path in executables_to_chmod:
if os.path.exists(exe_path):
run_command(f"chmod +x {exe_path}")
# 6. Clean up temporary files
printc("Cleaning up temporary files...", col.OKBLUE)
if os.path.exists(temp_tar_file):
os.remove(temp_tar_file)
if os.path.exists(temp_extract_dir):
shutil.rmtree(temp_extract_dir)
write_bin_version_file(release_tag, patch_name, dist_id, version)
printc(
f"{display_name} specific binary installation completed",
col.OKGREEN,
)
return True
except Exception as e:
printc(f"Error installing {display_name} binaries: {e}", col.FAIL)
# Clean up archive files on error
if os.path.exists(temp_tar_file):
os.remove(temp_tar_file)
if os.path.exists(temp_extract_dir):
shutil.rmtree(temp_extract_dir)
return False
def detect_distribution():
"""Detect Linux distribution and version without external modules"""
dist_id = "unknown"
version = "unknown"
family = "unknown"
# Try /etc/os-release first (standard method)
if os.path.exists("/etc/os-release"):
try:
with open("/etc/os-release", "r") as f:
lines = f.readlines()
for line in lines:
line = line.strip()
if line.startswith("ID="):
dist_id = line.split("=")[1].strip().strip('"')
elif line.startswith("VERSION_ID="):
version = line.split("=")[1].strip().strip('"')
except Exception:
pass
# Try older methods
if dist_id == "unknown":
if os.path.exists("/etc/redhat-release"):
dist_id = "centos"
try:
with open("/etc/redhat-release", "r") as f:
content = f.read().lower()
if "rocky" in content:
dist_id = "rocky"
elif "alma" in content:
dist_id = "almalinux"
elif "rhel" in content:
dist_id = "rhel"
elif "fedora" in content:
dist_id = "fedora"
except Exception:
pass
elif os.path.exists("/etc/debian_version"):
dist_id = "debian"
try:
with open("/etc/debian_version", "r") as f:
version = f.read().strip()
except Exception:
pass
elif os.path.exists("/etc/lsb-release"):
try:
with open("/etc/lsb-release", "r") as f:
lines = f.readlines()
for line in lines:
if line.startswith("DISTRIB_ID="):
dist_id = line.split("=")[1].strip().lower().strip('"')
elif line.startswith("DISTRIB_RELEASE="):
version = line.split("=")[1].strip().strip('"')
except Exception:
pass
# Determine family
if dist_id in ["centos", "rhel", "rocky", "almalinux", "fedora"]:
family = "redhat"
elif dist_id in ["ubuntu", "debian"]:
family = "debian"
else:
family = dist_id
return {
"id": dist_id,
"family": family,
"version": version,
"full_version": version,
}
def check_supported_distro(dist_info):
"""Check if distribution is supported"""
dist_id = dist_info["id"]
version = dist_info["version"]
if dist_id in SUPPORTED_DISTROS:
if version in SUPPORTED_DISTROS[dist_id]:
return True
else:
# Check if any supported version starts with the same major version
for supported_version in SUPPORTED_DISTROS[dist_id]:
if supported_version.startswith(version.split(".")[0]):
return True
# If not in list but is a known family, we'll try anyway
if dist_info["family"] in ["debian", "redhat"]:
return True
return False
def run_command(cmd, shell=True, capture_output=False):
"""Run shell command with error handling"""
try:
if capture_output:
result = subprocess.run(cmd, shell=shell, capture_output=True, text=True)
return result.returncode, result.stdout, result.stderr
else:
result = subprocess.run(cmd, shell=shell)
return result.returncode, None, None
except Exception as e:
return 1, None, str(e)
def generate_self_signed_cert():
"""Generate a fresh, per-install self-signed TLS certificate for nginx.
The archive ships a placeholder bin/nginx/conf/server.{crt,key}; reusing it
would mean every install shares the same private key. Here we overwrite it
with a freshly generated unique key/cert BEFORE nginx ever starts. Certbot
later replaces this with a real Let's Encrypt certificate (CertbotCronJob),
but until then nginx serves this self-signed pair.
"""
conf_dir = "/home/xc_vm/bin/nginx/conf"
key_path = conf_dir + "/server.key"
crt_path = conf_dir + "/server.crt"
common_name = socket.gethostname() or "xc_vm"
printc("Generating a unique self-signed TLS certificate...", col.OKBLUE)