forked from saltstack/salt
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpkg.py
More file actions
1631 lines (1445 loc) · 59.5 KB
/
pkg.py
File metadata and controls
1631 lines (1445 loc) · 59.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
import atexit
import contextlib
import logging
import os
import pathlib
import pprint
import re
import shutil
import subprocess
import textwrap
import time
from typing import TYPE_CHECKING
import attr
import distro
import packaging.version
import psutil
import pytest
import requests
import saltfactories.cli
from pytestshellutils.shell import DaemonImpl, Subprocess
from pytestshellutils.utils.processes import (
ProcessResult,
_get_cmdline,
terminate_process,
terminate_process_list,
)
from pytestskipmarkers.utils import platform
from saltfactories.bases import SystemdSaltDaemonImpl
from saltfactories.cli import call, key
from saltfactories.daemons import api, master, minion
from saltfactories.utils import cli_scripts
import salt.utils.files
from tests.conftest import CODE_DIR
from tests.support.pytest.helpers import TestAccount
ARTIFACTS_DIR = CODE_DIR / "artifacts" / "pkg"
log = logging.getLogger(__name__)
@attr.s(kw_only=True, slots=True)
class SaltPkgInstall:
pkg_system_service: bool = attr.ib(default=False)
proc: Subprocess = attr.ib(init=False, repr=False)
# Paths
root: pathlib.Path = attr.ib(default=None)
run_root: pathlib.Path = attr.ib(default=None)
ssm_bin: pathlib.Path = attr.ib(default=None)
bin_dir: pathlib.Path = attr.ib(default=None)
install_dir: pathlib.Path = attr.ib(init=False)
binary_paths: dict[str, list[pathlib.Path]] = attr.ib(init=False)
config_path: str = attr.ib(init=False)
conf_dir: pathlib.Path = attr.ib()
# Test selection flags
upgrade: bool = attr.ib(default=False)
downgrade: bool = attr.ib(default=False)
classic: bool = attr.ib(default=False)
# Installing flags
no_install: bool = attr.ib(default=False)
no_uninstall: bool = attr.ib(default=False)
# Distribution/system information
distro_id: str = attr.ib(init=False)
distro_codename: str = attr.ib(init=False)
distro_name: str = attr.ib(init=False)
distro_version: str = attr.ib(init=False)
# Version information
prev_version: str = attr.ib()
use_prev_version: str = attr.ib()
artifact_version: str = attr.ib(init=False)
version: str = attr.ib(init=False)
# Package (and management) metadata
pkg_mngr: str = attr.ib(init=False)
rm_pkg: str = attr.ib(init=False)
dbg_pkg: str = attr.ib(init=False)
salt_pkgs: list[str] = attr.ib(init=False)
pkgs: list[str] = attr.ib(factory=list)
file_ext: bool = attr.ib(default=None)
relenv: bool = attr.ib(default=True)
@proc.default
def _default_proc(self):
return Subprocess(timeout=240)
@distro_id.default
def _default_distro_id(self):
return distro.id().lower()
@distro_codename.default
def _default_distro_codename(self):
return distro.codename().lower()
@distro_name.default
def _default_distro_name(self):
name = distro.name()
if name:
if "vmware" in name.lower():
return name.split()[1].lower()
return name.split()[0].lower()
@distro_version.default
def _default_distro_version(self):
if self.distro_name in ("photon", "rocky"):
return distro.version().split(".")[0]
return distro.version().lower()
@pkg_mngr.default
def _default_pkg_mngr(self):
if self.distro_id in (
"almalinux",
"rocky",
"centos",
"redhat",
"amzn",
"fedora",
"photon",
):
return "yum"
elif self.distro_id in ("ubuntu", "debian"):
ret = self.proc.run("apt-get", "update")
self._check_retcode(ret)
return "apt-get"
@rm_pkg.default
def _default_rm_pkg(self):
if self.distro_id in (
"almalinux",
"rocky",
"centos",
"redhat",
"amzn",
"fedora",
"photon",
):
return "remove"
elif self.distro_id in ("ubuntu", "debian"):
return "purge"
@dbg_pkg.default
def _default_dbg_pkg(self):
dbg_pkg = None
if self.distro_id in (
"almalinux",
"rocky",
"centos",
"redhat",
"amzn",
"fedora",
"photon",
):
dbg_pkg = "salt-debuginfo"
elif self.distro_id in ("ubuntu", "debian"):
dbg_pkg = "salt-dbg"
return dbg_pkg
@salt_pkgs.default
def _default_salt_pkgs(self):
salt_pkgs = [
"salt-api",
"salt-syndic",
"salt-ssh",
"salt-master",
"salt-cloud",
"salt-minion",
]
if self.distro_id in (
"almalinux",
"rocky",
"centos",
"redhat",
"amzn",
"fedora",
"photon",
):
salt_pkgs.append("salt")
elif self.distro_id in ("ubuntu", "debian"):
salt_pkgs.append("salt-common")
if packaging.version.parse(self.version) >= packaging.version.parse("3006.3"):
if self.dbg_pkg:
salt_pkgs.append(self.dbg_pkg)
return salt_pkgs
@install_dir.default
def _default_install_dir(self):
if platform.is_windows():
install_dir = pathlib.Path(
os.getenv("ProgramFiles"), "Salt Project", "Salt"
).resolve()
elif platform.is_darwin():
install_dir = pathlib.Path("/opt", "salt")
else:
install_dir = pathlib.Path("/opt", "saltstack", "salt")
return install_dir
@config_path.default
def _default_config_path(self):
"""
Default location for salt configurations
"""
if platform.is_windows():
config_path = pathlib.Path("C:\\salt", "etc", "salt")
else:
config_path = pathlib.Path("/etc", "salt")
return config_path
@version.default
def _default_version(self):
"""
The version to be installed at the start
"""
if not self.upgrade and not self.use_prev_version:
version = self.artifact_version
else:
version = self.prev_version
parsed = packaging.version.parse(version)
version = f"{parsed.major}.{parsed.minor}"
# ensure services stopped on Debian/Ubuntu (minic install for RedHat - non-starting)
if self.distro_id in ("ubuntu", "debian"):
self.stop_services()
return version
@artifact_version.default
def _default_artifact_version(self):
"""
The version of the local salt artifacts being tested, based on regex matching
"""
version = ""
artifacts = list(ARTIFACTS_DIR.glob("**/*.*"))
for artifact in artifacts:
version = re.search(
r"([0-9].*)(\-[0-9].fc|\-[0-9].el|\+ds|\_all|\_any|\_amd64|\_arm64|\-[0-9].am|(\-[0-9]-[a-z]*-[a-z]*[0-9_]*.|\-[0-9]*.*)(exe|msi|pkg|rpm|deb))",
artifact.name,
)
if version:
version = version.groups()[0].replace("_", "-").replace("~", "")
version = version.split("-")[0]
break
if not version:
pytest.fail(
f"Failed to find package artifacts in '{ARTIFACTS_DIR}'. "
f"Directory Contents:\n{pprint.pformat(artifacts)}"
)
return version
def update_process_path(self):
# The installer updates the path for the system, but that doesn't
# make it to this python session, so we need to update that
os.environ["PATH"] = ";".join([str(self.install_dir), os.getenv("path")])
def __attrs_post_init__(self):
self.relenv = packaging.version.parse(self.version) >= packaging.version.parse(
"3006.0"
)
file_ext_re = "rpm|deb"
if platform.is_darwin():
file_ext_re = "pkg"
if platform.is_windows():
file_ext_re = "exe|msi"
for f_path in ARTIFACTS_DIR.glob("**/*.*"):
f_path = str(f_path)
if re.search(f"salt-(.*).({file_ext_re})$", f_path, re.IGNORECASE):
self.file_ext = os.path.splitext(f_path)[1].strip(".")
self.pkgs.append(f_path)
if platform.is_windows():
self.root = pathlib.Path(os.getenv("LocalAppData")).resolve()
if self.file_ext in ["exe", "msi"]:
self.root = self.install_dir.parent
self.bin_dir = self.install_dir
self.ssm_bin = self.install_dir / "ssm.exe"
self.run_root = self.bin_dir / "bin" / "salt.exe"
if not self.relenv and not self.classic:
self.ssm_bin = self.bin_dir / "bin" / "ssm.exe"
else:
log.error("Unexpected file extension: %s", self.file_ext)
if self.use_prev_version:
self.bin_dir = self.install_dir / "bin"
self.run_root = self.bin_dir / "salt.exe"
self.ssm_bin = self.bin_dir / "ssm.exe"
if self.file_ext == "msi" or self.relenv:
self.ssm_bin = self.install_dir / "ssm.exe"
if (
self.install_dir / "salt-minion.exe"
).exists() and not self.relenv:
log.debug(
"Removing %s", self.install_dir / "salt-minion.exe"
)
(self.install_dir / "salt-minion.exe").unlink()
elif platform.is_darwin():
self.root = pathlib.Path("/opt")
if self.file_ext == "pkg":
self.bin_dir = self.root / "salt" / "bin"
self.run_root = self.bin_dir / "run"
else:
log.error("Unexpected file extension: %s", self.file_ext)
log.debug("root: %s", self.root)
log.debug("bin_dir: %s", self.bin_dir)
log.debug("ssm_bin: %s", self.ssm_bin)
log.debug("run_root: %s", self.run_root)
if not self.pkgs:
pytest.fail("Could not find Salt Artifacts")
python_bin = self.install_dir / "bin" / "python3"
if platform.is_windows():
python_bin = self.install_dir / "Scripts" / "python.exe"
if self.relenv:
self.binary_paths = {
"call": ["salt-call.exe"],
"cp": ["salt-cp.exe"],
"minion": ["salt-minion.exe"],
"pip": ["salt-pip.exe"],
"python": [python_bin],
}
elif self.classic:
self.binary_paths = {
"call": [self.install_dir / "salt-call.bat"],
"cp": [self.install_dir / "salt-cp.bat"],
"minion": [self.install_dir / "salt-minion.bat"],
"python": [self.bin_dir / "python.exe"],
}
self.binary_paths["pip"] = self.binary_paths["python"] + ["-m", "pip"]
else:
self.binary_paths = {
"call": [str(self.run_root), "call"],
"cp": [str(self.run_root), "cp"],
"minion": [str(self.run_root), "minion"],
"pip": [str(self.run_root), "pip"],
"python": [str(self.run_root), "shell"],
}
else:
if os.path.exists(self.install_dir / "bin" / "salt"):
install_dir = self.install_dir / "bin"
else:
install_dir = self.install_dir
if self.relenv:
self.binary_paths = {
"salt": [install_dir / "salt"],
"api": [install_dir / "salt-api"],
"call": [install_dir / "salt-call"],
"cloud": [install_dir / "salt-cloud"],
"cp": [install_dir / "salt-cp"],
"key": [install_dir / "salt-key"],
"master": [install_dir / "salt-master"],
"minion": [install_dir / "salt-minion"],
"proxy": [install_dir / "salt-proxy"],
"run": [install_dir / "salt-run"],
"ssh": [install_dir / "salt-ssh"],
"syndic": [install_dir / "salt-syndic"],
"spm": [install_dir / "spm"],
"pip": [install_dir / "salt-pip"],
"python": [python_bin],
}
else:
self.binary_paths = {
"salt": [shutil.which("salt")],
"api": [shutil.which("salt-api")],
"call": [shutil.which("salt-call")],
"cloud": [shutil.which("salt-cloud")],
"cp": [shutil.which("salt-cp")],
"key": [shutil.which("salt-key")],
"master": [shutil.which("salt-master")],
"minion": [shutil.which("salt-minion")],
"proxy": [shutil.which("salt-proxy")],
"run": [shutil.which("salt-run")],
"ssh": [shutil.which("salt-ssh")],
"syndic": [shutil.which("salt-syndic")],
"spm": [shutil.which("spm")],
"python": [str(pathlib.Path("/usr/bin/python3"))],
}
if self.classic:
if platform.is_darwin():
# `which` is not catching the right paths on downgrades, explicitly defining them here
self.binary_paths = {
"salt": [self.bin_dir / "salt"],
"api": [self.bin_dir / "salt-api"],
"call": [self.bin_dir / "salt-call"],
"cloud": [self.bin_dir / "salt-cloud"],
"cp": [self.bin_dir / "salt-cp"],
"key": [self.bin_dir / "salt-key"],
"master": [self.bin_dir / "salt-master"],
"minion": [self.bin_dir / "salt-minion"],
"proxy": [self.bin_dir / "salt-proxy"],
"run": [self.bin_dir / "salt-run"],
"ssh": [self.bin_dir / "salt-ssh"],
"syndic": [self.bin_dir / "salt-syndic"],
"spm": [self.bin_dir / "spm"],
"python": [str(self.bin_dir / "python3")],
"pip": [str(self.bin_dir / "pip3")],
}
else:
self.binary_paths["pip"] = [str(pathlib.Path("/usr/bin/pip3"))]
self.proc.run(*self.binary_paths["pip"], "install", "-U", "pip")
self.proc.run(
*self.binary_paths["pip"], "install", "-U", "pyopenssl"
)
else:
self.binary_paths["python"] = [shutil.which("salt"), "shell"]
if platform.is_darwin():
self.binary_paths["pip"] = [self.run_root, "pip"]
self.binary_paths["spm"] = [shutil.which("salt-spm")]
else:
self.binary_paths["pip"] = [shutil.which("salt-pip")]
log.debug("python_bin: %s", python_bin)
log.debug("binary_paths: %s", self.binary_paths)
log.debug("install_dir: %s", self.install_dir)
@staticmethod
def salt_factories_root_dir(system_service: bool = False) -> pathlib.Path:
if system_service is False:
return None
if platform.is_windows():
return pathlib.Path("C:\\salt")
if platform.is_darwin():
return pathlib.Path("/opt/salt")
return pathlib.Path("/")
def _check_retcode(self, ret):
"""
Helper function to check subprocess.run returncode equals 0
If not raise AssertionError
"""
if ret.returncode != 0:
log.error(ret)
assert ret.returncode == 0
return True
def _install_pkgs(self, upgrade=False, downgrade=False):
if downgrade:
self.install_previous(downgrade=downgrade)
return True
pkg = str(pathlib.Path(self.pkgs[0]).resolve())
if platform.is_windows():
if upgrade:
self.root = self.install_dir.parent
self.bin_dir = self.install_dir
self.ssm_bin = self.install_dir / "ssm.exe"
if pkg.endswith("exe"):
# Install the package
log.info("Installing: %s", str(pkg))
ret = self.proc.run(str(pkg), "/start-minion=0", "/S")
self._check_retcode(ret)
elif pkg.endswith("msi"):
# Install the package
log.info("Installing: %s", str(pkg))
# self.proc.run always makes the command a list even when shell
# is true, meaning shell being true will never work correctly.
ret = subprocess.run(
f'msiexec.exe /qn /i {pkg} /norestart START_MINION=""',
shell=True, # nosec
check=False,
)
assert ret.returncode in [0, 3010]
else:
log.error("Invalid package: %s", pkg)
return False
# Remove the service installed by the installer
log.debug("Removing installed salt-minion service")
self.proc.run(str(self.ssm_bin), "remove", "salt-minion", "confirm")
# Add installation to the path
self.update_process_path()
# Install the service using our config
if self.pkg_system_service:
self._install_ssm_service()
elif platform.is_darwin():
daemons_dir = pathlib.Path("/Library", "LaunchDaemons")
service_name = "com.saltstack.salt.minion"
plist_file = daemons_dir / f"{service_name}.plist"
log.debug("Installing: %s", str(pkg))
ret = self.proc.run("installer", "-pkg", str(pkg), "-target", "/")
self._check_retcode(ret)
# Stop the service installed by the installer
self.proc.run("launchctl", "disable", f"system/{service_name}")
self.proc.run("launchctl", "bootout", "system", str(plist_file))
elif upgrade:
env = os.environ.copy()
extra_args = []
if self.distro_id in ("ubuntu", "debian"):
env["DEBIAN_FRONTEND"] = "noninteractive"
extra_args = [
"-o",
"DPkg::Options::=--force-confdef",
"-o",
"DPkg::Options::=--force-confold",
]
log.info("Installing packages:\n%s", pprint.pformat(self.pkgs))
args = extra_args + self.pkgs
upgrade_cmd = "upgrade"
if self.distro_id == "photon":
# tdnf does not detect nightly build versions to be higher version
# than release versions
upgrade_cmd = "install"
ret = self.proc.run(
self.pkg_mngr,
upgrade_cmd,
"-y",
*args,
env=env,
)
else:
log.info("Installing packages:\n%s", pprint.pformat(self.pkgs))
ret = self.proc.run(self.pkg_mngr, "install", "-y", *self.pkgs)
if not platform.is_darwin() and not platform.is_windows():
# Make sure we don't have any trailing references to old package file locations
assert ret.returncode == 0
assert "/saltstack/salt/run" not in ret.stdout
log.info(ret)
self._check_retcode(ret)
def _install_ssm_service(self, service="minion"):
"""
This function installs the service on Windows using SSM but does not
start it.
Args:
service (str):
The name of the service. Default is ``minion``
"""
service_name = f"salt-{service}"
binary = self.install_dir / f"{service_name}.exe"
ret = self.proc.run(
str(self.ssm_bin),
"install",
service_name,
binary,
"-c",
f'"{str(self.conf_dir)}"',
)
self._check_retcode(ret)
ret = self.proc.run(
str(self.ssm_bin),
"set",
service_name,
"Description",
"Salt Minion for testing",
)
self._check_retcode(ret)
# This doesn't start the service. It will start automatically on reboot
# It is set here to make it the same as what the installer does
ret = self.proc.run(
str(self.ssm_bin), "set", service_name, "Start", "SERVICE_AUTO_START"
)
self._check_retcode(ret)
ret = self.proc.run(
str(self.ssm_bin), "set", service_name, "AppStopMethodConsole", "24000"
)
self._check_retcode(ret)
ret = self.proc.run(
str(self.ssm_bin), "set", service_name, "AppStopMethodWindow", "2000"
)
self._check_retcode(ret)
ret = self.proc.run(
str(self.ssm_bin), "set", service_name, "AppRestartDelay", "60000"
)
self._check_retcode(ret)
def package_python_version(self):
return self.proc.run(
str(self.binary_paths["python"][0]),
"-c",
"import sys; print('{}.{}'.format(*sys.version_info))",
).stdout.strip()
def install(self, upgrade=False, downgrade=False):
self._install_pkgs(upgrade=upgrade, downgrade=downgrade)
if self.distro_id in ("ubuntu", "debian"):
self.stop_services()
def stop_services(self):
"""
Debian/Ubuntu distros automatically start the services on install
We want to ensure our tests start with the config settings we have set.
This will also verify the expected services are up and running.
"""
retval = True
for service in ["salt-syndic", "salt-master", "salt-minion"]:
check_run = self.proc.run("systemctl", "status", service)
if check_run.returncode != 0:
# The system was not started automatically and
# we are expecting it to be on install on Debian/Ubuntu systems
log.debug("The service %s was not started on install.", service)
retval = False
else:
stop_service = self.proc.run("systemctl", "stop", service)
self._check_retcode(stop_service)
return retval
def restart_services(self):
"""
Debian/Ubuntu distros automatically start the services
We want to ensure our tests start with the config settings we have set,
for example: after install the services are stopped (similar to RedHat not starting services on install)
This will also verify the expected services are up and running.
"""
for service in ["salt-minion", "salt-master", "salt-syndic"]:
check_run = self.proc.run("systemctl", "status", service)
log.debug(
"The restart_services status, before restart, for service %s is %s.",
service,
check_run,
)
restart_service = self.proc.run("systemctl", "restart", service)
self._check_retcode(restart_service)
def install_previous(self, downgrade=False):
"""
Install previous version. This is used for upgrade tests.
"""
major_ver = packaging.version.parse(self.prev_version).major
relenv = packaging.version.parse(self.prev_version) >= packaging.version.parse(
"3006.0"
)
distro_name = self.distro_name
if distro_name in ("almalinux", "rocky", "centos", "fedora"):
distro_name = "redhat"
root_url = "https://packages.broadcom.com/artifactory"
if self.distro_name in [
"almalinux",
"rocky",
"redhat",
"centos",
"amazon",
"fedora",
"vmware",
"photon",
]:
# Removing EPEL repo files
for fp in pathlib.Path("/etc", "yum.repos.d").glob("epel*"):
fp.unlink()
if platform.is_aarch64():
arch = "arm64"
# Starting with 3006.5, we prioritize the aarch64 repo paths for rpm-based distros
if packaging.version.parse(
self.prev_version
) >= packaging.version.parse("3006.5"):
arch = "aarch64"
else:
arch = "x86_64"
ret = self.proc.run(
"rpm",
"--import",
"https://packages.broadcom.com/artifactory/api/security/keypair/SaltProjectKey/public",
)
self._check_retcode(ret)
download_file(
"https://github.com/saltstack/salt-install-guide/releases/latest/download/salt.repo",
f"/etc/yum.repos.d/salt-{distro_name}.repo",
)
if self.distro_name == "photon":
# yum version on photon doesn't support expire-cache
ret = self.proc.run(self.pkg_mngr, "clean", "all")
else:
ret = self.proc.run(self.pkg_mngr, "clean", "expire-cache")
self._check_retcode(ret)
cmd_action = "downgrade" if downgrade else "install"
pkgs_to_install = self.salt_pkgs.copy()
if self.distro_version == "8" and self.classic:
# centosstream 8 doesn't downgrade properly using the downgrade command for some reason
# So we explicitly install the correct version here
list_ret = self.proc.run(
self.pkg_mngr, "list", "--available", "salt"
).stdout.split("\n")
list_ret = [_.strip() for _ in list_ret]
idx = list_ret.index("Available Packages")
old_ver = list_ret[idx + 1].split()[1]
pkgs_to_install = [f"{pkg}-{old_ver}" for pkg in pkgs_to_install]
if self.dbg_pkg:
# self.dbg_pkg does not exist on classic packages
dbg_exists = [x for x in pkgs_to_install if self.dbg_pkg in x]
if dbg_exists:
pkgs_to_install.remove(dbg_exists[0])
cmd_action = "install"
ret = self.proc.run(
self.pkg_mngr,
cmd_action,
*pkgs_to_install,
"-y",
)
self._check_retcode(ret)
elif distro_name in ["debian", "ubuntu"]:
ret = self.proc.run(self.pkg_mngr, "install", "curl", "-y")
self._check_retcode(ret)
ret = self.proc.run(self.pkg_mngr, "install", "apt-transport-https", "-y")
self._check_retcode(ret)
## only classic 3005 has arm64 support
if relenv and platform.is_aarch64():
arch = "arm64"
elif platform.is_aarch64() and self.classic:
arch = "arm64"
else:
arch = "amd64"
pathlib.Path("/etc/apt/keyrings").mkdir(parents=True, exist_ok=True)
gpg_full_path = "/etc/apt/keyrings/salt-archive-keyring.pgp"
# download the gpg pub key
download_file(
f"{root_url}/api/security/keypair/SaltProjectKey/public",
f"{gpg_full_path}",
)
with salt.utils.files.fopen(
pathlib.Path("/etc", "apt", "sources.list.d", "salt.list"), "w"
) as fp:
fp.write(
f"deb [signed-by={gpg_full_path} arch={arch}] "
f"{root_url}/saltproject-deb/ stable main"
)
self._check_retcode(ret)
pref_file = pathlib.Path("/etc", "apt", "preferences.d", "salt-pin-1001")
pref_file.parent.mkdir(exist_ok=True)
pin = f"{self.prev_version.rsplit('.', 1)[0]}.*"
if downgrade:
pin = self.prev_version
with salt.utils.files.fopen(pref_file, "w") as fp:
fp.write(
f"Package: salt-*\n" f"Pin: version {pin}\n" f"Pin-Priority: 1001"
)
cmd = [self.pkg_mngr, "install", *self.salt_pkgs, "-y"]
# if downgrade:
# pref_file = pathlib.Path("/etc", "apt", "preferences.d", "salt-pin-1001")
# pref_file.parent.mkdir(exist_ok=True)
# # TODO: There's probably something I should put in here to say what version
# # TODO: But maybe that's done elsewhere, hopefully in self.salt_pkgs
# pref_file.write_text(
# textwrap.dedent(
# f"""\
# Package: salt*
# Pin: origin "{root_url}/saltproject-deb"
# Pin-Priority: 1001
# """
# ),
# encoding="utf-8",
# )
cmd.append("--allow-downgrades")
env = os.environ.copy()
env["DEBIAN_FRONTEND"] = "noninteractive"
extra_args = [
"-o",
"DPkg::Options::=--force-confdef",
"-o",
"DPkg::Options::=--force-confold",
]
self.proc.run(self.pkg_mngr, "update", *extra_args, env=env)
cmd.extend(extra_args)
log.error("Run cmd %s", cmd)
ret = self.proc.run(*cmd, env=env)
log.error("cmd return %r", ret)
# Pre-relenv packages down get downgraded to cleanly programmatically
# They work manually, and the install tests after downgrades will catch problems with the install
self._check_retcode(ret)
# Let's not check the returncode if this is the case
# if not (
# downgrade
# and packaging.version.parse(self.prev_version)
# < packaging.version.parse("3006.0")
# ):
# self._check_retcode(ret)
if downgrade and not self.no_uninstall:
pref_file.unlink()
self.stop_services()
elif platform.is_windows():
self.bin_dir = self.install_dir / "bin"
self.run_root = self.bin_dir / "salt.exe"
self.ssm_bin = self.install_dir / "ssm.exe"
pkg = str(pathlib.Path(self.pkgs[0]).resolve())
if self.file_ext == "exe":
win_pkg = (
f"Salt-Minion-{self.prev_version}-Py3-AMD64-Setup.{self.file_ext}"
)
elif self.file_ext == "msi":
win_pkg = f"Salt-Minion-{self.prev_version}-Py3-AMD64.{self.file_ext}"
else:
log.debug("Unknown windows file extension: %s", self.file_ext)
win_pkg_url = (
f"{root_url}/saltproject-generic/windows/{self.prev_version}/{win_pkg}"
)
pkg_path = pathlib.Path(r"C:\TEMP", win_pkg)
pkg_path.parent.mkdir(exist_ok=True)
download_file(win_pkg_url, pkg_path)
if self.file_ext == "msi":
if downgrade:
# MSI can not be downgraded, we must remove the newer version
# before installing the old one.
ret = subprocess.run(
f"msiexec.exe /qn /x {pkg} /norestart",
shell=True, # nosec
check=False,
)
assert ret.returncode == 0
# self.proc.run always makes the command a list even when shell
# is true, meaning shell being true will never work correctly.
ret = subprocess.run(
f'msiexec.exe /qn /i {pkg_path} /norestart START_MINION=""',
shell=True, # nosec
check=False,
)
assert ret.returncode in [0, 3010]
else:
ret = self.proc.run(pkg_path, "/start-minion=0", "/S")
self._check_retcode(ret)
log.debug("Removing installed salt-minion service")
ret = self.proc.run(str(self.ssm_bin), "remove", "salt-minion", "confirm")
self._check_retcode(ret)
# Add installation to the path
self.update_process_path()
if self.pkg_system_service:
self._install_ssm_service()
elif platform.is_darwin():
if relenv and platform.is_aarch64():
arch = "arm64"
elif platform.is_aarch64() and self.classic:
arch = "arm64"
else:
arch = "x86_64"
mac_pkg = f"salt-{self.prev_version}-py3-{arch}.pkg"
mac_pkg_url = (
f"{root_url}/saltproject-generic/macos/{self.prev_version}/{mac_pkg}"
)
mac_pkg_path = f"/tmp/{mac_pkg}"
if not os.path.exists(mac_pkg_path):
download_file(
f"{mac_pkg_url}",
f"/tmp/{mac_pkg}",
)
ret = self.proc.run("installer", "-pkg", mac_pkg_path, "-target", "/")
self._check_retcode(ret)
def uninstall(self):
pkg = self.pkgs[0]
if platform.is_windows():
log.info("Uninstalling %s", pkg)
if pkg.endswith("exe"):
uninst = self.install_dir / "uninst.exe"
ret = self.proc.run(uninst, "/S")
self._check_retcode(ret)
elif pkg.endswith("msi"):
ret = self.proc.run("msiexec.exe", "/qn", "/x", pkg)
self._check_retcode(ret)
elif platform.is_darwin():
# From here: https://stackoverflow.com/a/46118276/4581998
daemons_dir = pathlib.Path("/Library", "LaunchDaemons")
for service in ("minion", "master", "api", "syndic"):
service_name = f"com.saltstack.salt.{service}"
plist_file = daemons_dir / f"{service_name}.plist"
# Stop the services
self.proc.run("launchctl", "disable", f"system/{service_name}")
self.proc.run("launchctl", "bootout", "system", str(plist_file))
# Remove Symlink to salt-config
if os.path.exists("/usr/local/sbin/salt-config"):
os.unlink("/usr/local/sbin/salt-config")
# Remove supporting files
self.proc.run(
"pkgutil",
"--only-files",
"--files",
"com.saltstack.salt",
"|",
"grep",
"-v",
"opt",
"|",
"tr",
"'\n'",
"' '",
"|",
"xargs",
"-0",
"rm",
"-f",
)
# Remove directories
if os.path.exists("/etc/salt"):
shutil.rmtree("/etc/salt")
# Remove path
if os.path.exists("/etc/paths.d/salt"):
os.remove("/etc/paths.d/salt")
# Remove receipt
self.proc.run("pkgutil", "--forget", "com.saltstack.salt")
log.debug("Deleting the onedir directory: %s", self.root / "salt")
shutil.rmtree(str(self.root / "salt"))
else:
log.debug("Un-Installing packages:\n%s", pprint.pformat(self.salt_pkgs))
ret = self.proc.run(self.pkg_mngr, self.rm_pkg, "-y", *self.salt_pkgs)
self._check_retcode(ret)
def write_launchd_conf(self, service):
service_name = f"com.saltstack.salt.{service}"
ret = self.proc.run("launchctl", "list", service_name)
# 113 means it couldn't find a service with that name
if ret.returncode == 113:
daemons_dir = pathlib.Path("/Library", "LaunchDaemons")
plist_file = daemons_dir / f"{service_name}.plist"
# Make sure we're using this plist file
if plist_file.exists():
log.warning("Removing existing plist file for service: %s", service)
plist_file.unlink()
log.debug("Creating plist file for service: %s", service)
contents = f"""\
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>{service_name}</string>
<key>RunAtLoad</key>
<true/>
<key>KeepAlive</key>
<true/>
<key>ProgramArguments</key>
<array>"""
for part in self.binary_paths[service]:
contents += (
f"""\n <string>{part}</string>\n"""
)
contents += f"""\
<string>-c</string>
<string>{self.conf_dir}</string>
</array>
<key>SoftResourceLimits</key>
<dict>
<key>NumberOfFiles</key>
<integer>100000</integer>
</dict>
<key>HardResourceLimits</key>
<dict>
<key>NumberOfFiles</key>
<integer>100000</integer>
</dict>
</dict>
</plist>
"""
plist_file.write_text(textwrap.dedent(contents), encoding="utf-8")
contents = plist_file.read_text()
log.debug("Created '%s'. Contents:\n%s", plist_file, contents)
# Delete the plist file upon completion
atexit.register(plist_file.unlink)
def write_systemd_conf(self, service, binary):
ret = self.proc.run("systemctl", "daemon-reload")
self._check_retcode(ret)
ret = self.proc.run("systemctl", "status", service)
if ret.returncode == 4:
log.warning(
"No systemd unit file was found for service %s. Creating one.", service
)
contents = textwrap.dedent(
"""\
[Unit]
Description={service}
[Service]
KillMode=process
Type=notify
NotifyAccess=all
LimitNOFILE=8192