-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathaltpkg.py
2114 lines (1689 loc) · 64.8 KB
/
altpkg.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
"""
Support for APT (Advanced Packaging Tool)/RPM for ALT Linux
.. important::
If you feel that Salt should be using this module to manage packages on a
minion, and it is using a different module (or gives an error similar to
*'pkg.install' is not available*), see :ref:`here
<module-provider-override>`.
For repository management, the ``apt-repo`` package must be installed.
Because of APT/RPM package management system in ALT Linux this module
was combined from two package management salt modules :
- aptpkg.py
- yumpkg.py
"""
import copy
import datetime
import fnmatch
import logging
import os
import pathlib
import re
import shutil
import tempfile
import time
from distutils.version import LooseVersion as _LooseVersion
import salt.config
import salt.syspaths
import salt.utils.args
import salt.utils.data
import salt.utils.environment
import salt.utils.files
import salt.utils.functools
import salt.utils.itertools
import salt.utils.json
import salt.utils.path
import salt.utils.pkg
import salt.utils.pkg.deb
import salt.utils.stringutils
import salt.utils.systemd
import salt.utils.versions
import salt.utils.yaml
from salt.exceptions import (
CommandExecutionError,
CommandNotFoundError,
MinionError,
SaltInvocationError,
)
from salt.modules.cmdmod import _parse_env
log = logging.getLogger(__name__)
PKG_ARCH_SEPARATOR = "."
APT_LISTS_PATH = "/var/lib/apt/lists"
DPKG_ENV_VARS = {
"APT_LISTBUGS_FRONTEND": "none",
"APT_LISTCHANGES_FRONTEND": "none",
"DEBIAN_FRONTEND": "noninteractive",
"UCF_FORCE_CONFFOLD": "1",
}
# Define the module's virtual name
__virtualname__ = "pkg"
def __virtual__():
"""
Confirm this module is on a ALT Linux based system
"""
if __grains__.get("os").lower() == "alt":
return __virtualname__
return False, "The pkg module could not be loaded: unsupported OS family"
def __init__(opts):
"""
For APT-GET systems, set up
a few env variables to keep apt happy and
non-interactive.
"""
if __virtual__() == __virtualname__:
# Export these puppies so they persist
os.environ.update(DPKG_ENV_VARS)
class SourceEntry: # pylint: disable=function-redefined
def __init__(self, line, file=None):
self.invalid = False
self.comps = []
self.disabled = False
self.comment = ""
self.dist = ""
self.type = ""
self.uri = ""
self.line = line
self.architectures = []
self.file = file
if not self.file:
self.file = str(pathlib.Path(os.sep, "etc", "apt", "sources.list"))
self._parse_sources(line)
def repo_line(self):
"""
Return the repo line for the sources file
"""
repo_line = []
if self.invalid:
return self.line
if self.disabled:
repo_line.append("#")
repo_line.append(self.type)
if self.architectures:
repo_line.append("[arch={}]".format(" ".join(self.architectures)))
repo_line = repo_line + [self.uri, self.dist, " ".join(self.comps)]
if self.comment:
repo_line.append("#{}".format(self.comment))
return " ".join(repo_line) + "\n"
def _parse_sources(self, line):
"""
Parse lines from sources files
"""
self.disabled = False
repo_line = self.line.strip().split()
if not repo_line:
self.invalid = True
return False
if repo_line[0].startswith("#"):
repo_line.pop(0)
self.disabled = True
if repo_line[0] not in ["deb", "deb-src", "rpm", "rpm-src"]:
self.invalid = True
return False
if repo_line[1].startswith("["):
opts = re.search(r"\[.*\]", self.line).group(0).strip("[]")
repo_line = [x for x in (line.strip("[]") for line in repo_line) if x]
for opt in opts.split():
if opt.startswith("arch"):
self.architectures.extend(opt.split("=", 1)[1].split(","))
try:
repo_line.pop(repo_line.index(opt))
except ValueError:
repo_line.pop(repo_line.index("[" + opt + "]"))
self.type = repo_line[0]
self.uri = repo_line[1]
self.dist = repo_line[2]
self.comps = repo_line[3:]
class SourcesList: # pylint: disable=function-redefined
def __init__(self):
self.list = []
self.files = [
pathlib.Path(os.sep, "etc", "apt", "sources.list"),
pathlib.Path(os.sep, "etc", "apt", "sources.list.d"),
]
for file in self.files:
if file.is_dir():
for fp in file.glob("**/*.list"):
self.add_file(file=fp)
else:
self.add_file(file)
def __iter__(self):
yield from self.list
def add_file(self, file):
"""
Add the lines of a file to self.list
"""
if file.is_file():
with salt.utils.files.fopen(file) as source:
for line in source:
self.list.append(SourceEntry(line, file=str(file)))
else:
log.debug("The apt sources file %s does not exist", file)
def add(self, type, uri, dist, orig_comps, architectures):
repo_line = [
type,
" [arch={}] ".format(" ".join(architectures)) if architectures else "",
uri,
dist,
" ".join(orig_comps),
]
return SourceEntry(" ".join(repo_line))
def remove(self, source):
"""
remove a source from the list of sources
"""
self.list.remove(source)
def save(self):
"""
write all of the sources from the list of sources
to the file.
"""
filemap = {}
with tempfile.TemporaryDirectory() as tmpdir:
for source in self.list:
fname = pathlib.Path(tmpdir, pathlib.Path(source.file).name)
with salt.utils.files.fopen(fname, "a") as fp:
fp.write(source.repo_line())
if source.file not in filemap:
filemap[source.file] = {"tmp": fname}
for fp in filemap:
shutil.copy(filemap[fp]["tmp"], fp)
#os.remove(filemap[fp]["tmp"]) ### not working - could not found temp file
def _call_apt(args, scope=True, **kwargs):
"""
Call apt* utilities.
"""
cmd = []
if (
scope
and salt.utils.systemd.has_scope(__context__)
and __salt__["config.get"]("systemd.scope", True)
):
cmd.extend(["systemd-run", "--scope", "--description", '"{}"'.format(__name__)])
cmd.extend(args)
params = {
"output_loglevel": "trace",
"python_shell": False,
"env": salt.utils.environment.get_module_environment(globals()),
}
params.update(kwargs)
log.debug(cmd)
log.debug(params)
cmd_ret = __salt__["cmd.run_all"](cmd, **params)
count = 0
while "Could not get lock" in cmd_ret.get("stderr", "") and count < 10:
count += 1
log.warning("Waiting for dpkg lock release: retrying... %s/100", count)
time.sleep(2 ** count)
cmd_ret = __salt__["cmd.run_all"](cmd, **params)
return cmd_ret
def latest_version(*names, **kwargs):
"""
Return the latest version of the named package available for upgrade or
installation. If more than one package name is specified, a dict of
name/version pairs is returned.
If the latest version of a given package is already installed, an empty
string will be returned for that package.
A specific repo can be requested using the ``fromrepo`` keyword argument.
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
CLI Example:
.. code-block:: bash
salt '*' pkg.latest_version <package name>
salt '*' pkg.latest_version <package name> fromrepo=unstable
salt '*' pkg.latest_version <package1> <package2> <package3> ...
"""
refresh = salt.utils.data.is_true(kwargs.pop("refresh", True))
show_installed = salt.utils.data.is_true(kwargs.pop("show_installed", False))
if "repo" in kwargs:
raise SaltInvocationError(
"The 'repo' argument is invalid, use 'fromrepo' instead"
)
fromrepo = kwargs.pop("fromrepo", None)
cache_valid_time = kwargs.pop("cache_valid_time", 0)
if not names:
return ""
ret = {}
# Initialize the dict with empty strings
for name in names:
ret[name] = ""
pkgs = list_pkgs(versions_as_list=True)
repo = ["-o", "APT::Default-Release={}".format(fromrepo)] if fromrepo else None
# Refresh before looking for the latest version available
if refresh:
refresh_db(cache_valid_time)
for name in names:
cmd = ["apt-cache", "-q", "policy", name]
if repo is not None:
cmd.extend(repo)
out = _call_apt(cmd, scope=False)
candidate = ""
for line in salt.utils.itertools.split(out["stdout"], "\n"):
if "Candidate" in line:
comps = line.split()
if len(comps) >= 2:
candidate = comps[-1]
if candidate.lower() == "(none)":
candidate = ""
break
# cut right part after semicolon in versions like
# 4:8.2.5019-alt1:p10+300891.100.2.1@1654002425
# to normalize version
semicolon_pos = candidate.rfind(":")
if semicolon_pos != -1 and semicolon_pos > 2:
candidate = candidate[0:candidate.rfind(":",1)]
installed = pkgs.get(name, [])
if not installed:
ret[name] = candidate
elif installed and show_installed:
ret[name] = candidate
elif candidate:
# If there are no installed versions that are greater than or equal
# to the install candidate, then the candidate is an upgrade, so
# add it to the return dict
if not any(
salt.utils.versions.compare(
ver1=x, oper=">=", ver2=candidate, cmp_func=version_cmp
)
for x in installed
):
ret[name] = candidate
# Return a string if only one package name passed
if len(names) == 1:
return ret[names[0]]
return ret
# available_version is being deprecated
available_version = salt.utils.functools.alias_function(
latest_version, "available_version"
)
def version(*names, **kwargs):
"""
Returns a string representing the package version or an empty string if not
installed. If more than one package name is specified, a dict of
name/version pairs is returned.
CLI Example:
.. code-block:: bash
salt '*' pkg.version <package name>
salt '*' pkg.version <package1> <package2> <package3> ...
"""
return __salt__["pkg_resource.version"](*names, **kwargs)
def refresh_db(cache_valid_time=0, failhard=False, **kwargs):
"""
Updates the APT database to latest packages based upon repositories
Returns a dict, with the keys being package databases and the values being
the result of the update attempt. Values can be one of the following:
- ``True``: Database updated successfully
- ``False``: Problem updating database
- ``None``: Database already up-to-date
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
failhard
If False, return results of Err lines as ``False`` for the package database that
encountered the error.
If True, raise an error with a list of the package databases that encountered
errors.
CLI Example:
.. code-block:: bash
salt '*' pkg.refresh_db
"""
# Remove rtag file to keep multiple refreshes from happening in pkg states
salt.utils.pkg.clear_rtag(__opts__)
failhard = salt.utils.data.is_true(failhard)
ret = {}
error_repos = list()
if cache_valid_time:
try:
latest_update = os.stat(APT_LISTS_PATH).st_mtime
now = time.time()
log.debug(
"now: %s, last update time: %s, expire after: %s seconds",
now,
latest_update,
cache_valid_time,
)
if latest_update + cache_valid_time > now:
return ret
except TypeError as exp:
log.warning(
"expected integer for cache_valid_time parameter, failed with: %s", exp
)
except OSError as exp:
log.warning("could not stat cache directory due to: %s", exp)
call = _call_apt(["apt-get", "-q", "update"], scope=False)
if call["retcode"] != 0:
comment = ""
if "stderr" in call:
comment += call["stderr"]
raise CommandExecutionError(comment)
else:
out = call["stdout"]
for line in out.splitlines():
cols = line.split()
if not cols:
continue
ident = " ".join(cols[1:])
if "Get" in cols[0]:
# Strip filesize from end of line
ident = re.sub(r" \[.+B\]$", "", ident)
ret[ident] = True
elif "Ign" in cols[0]:
ret[ident] = False
elif "Hit" in cols[0]:
ret[ident] = None
elif "Err" in cols[0]:
ret[ident] = False
error_repos.append(ident)
if failhard and error_repos:
raise CommandExecutionError(
"Error getting repos: {}".format(", ".join(error_repos))
)
return ret
# update is an alias to refresh_db
update = salt.utils.functools.alias_function(
refresh_db, "update"
)
def install(
name=None,
refresh=False,
fromrepo=None,
skip_verify=False,
debconf=None,
pkgs=None,
sources=None,
reinstall=False,
downloadonly=False,
ignore_epoch=False,
**kwargs
):
"""
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Install the passed package, add refresh=True to update the dpkg database.
name
The name of the package to be installed. Note that this parameter is
ignored if either "pkgs" or "sources" is passed. Additionally, please
note that this option can only be used to install packages from a
software repository. To install a package file manually, use the
"sources" option.
32-bit packages can be installed on 64-bit systems by appending the
architecture designation (``:i386``, etc.) to the end of the package
name.
CLI Example:
.. code-block:: bash
salt '*' pkg.install <package name>
refresh
Whether or not to refresh the package database before installing.
cache_valid_time
.. versionadded:: 2016.11.0
Skip refreshing the package database if refresh has already occurred within
<value> seconds
fromrepo
Specify a package repository to install from
(e.g., ``apt-get -t unstable install somepackage``)
skip_verify
Skip the GPG verification check (e.g., ``--allow-unauthenticated``, or
``--force-bad-verify`` for install from package file).
debconf
Provide the path to a debconf answers file, processed before
installation.
version
Install a specific version of the package, e.g. 0.7.4-alt2.noarch. Ignored
if "pkgs" or "sources" is passed.
.. versionchanged:: 2018.3.0
version can now contain comparison operators (e.g. ``>1.2.3``,
``<=2.0``, etc.)
reinstall : False
Specifying reinstall=True will use ``apt-get install --reinstall``
rather than simply ``apt-get install`` for requested packages that are
already installed.
If a version is specified with the requested package, then ``apt-get
install --reinstall`` will only be used if the installed version
matches the requested version.
.. versionadded:: 2015.8.0
ignore_epoch : False
Only used when the version of a package is specified using a comparison
operator (e.g. ``>4.1``). If set to ``True``, then the epoch will be
ignored when comparing the currently-installed version to the desired
version.
.. versionadded:: 2018.3.0
Multiple Package Installation Options:
pkgs
A list of packages to install from a software repository. Must be
passed as a python list.
CLI Example:
.. code-block:: bash
salt '*' pkg.install pkgs='["foo", "bar"]'
salt '*' pkg.install pkgs='["foo", {"bar": "0.7.4-alt2.noarch"}]'
sources
A list of RPM packages to install. Must be passed as a list of dicts,
with the keys being package names, and the values being the source URI
or local path to the package. Dependencies are automatically resolved
and marked as auto-installed.
32-bit packages can be installed on 64-bit systems by appending the
architecture designation (``:i386``, etc.) to the end of the package
name.
.. versionchanged:: 2014.7.0
CLI Example:
.. code-block:: bash
salt '*' pkg.install sources='[{"foo": "salt://foo.rpm"},{"bar": "salt://bar.rpm"}]'
force_yes
Passes ``--force-yes`` to the apt-get command. Don't use this unless
you know what you're doing.
.. versionadded:: 0.17.4
install_recommends
Whether to install the packages marked as recommended. Default is True.
.. versionadded:: 2015.5.0
only_upgrade
Only upgrade the packages, if they are already installed. Default is False.
.. versionadded:: 2015.5.0
force_conf_new
Always install the new version of any configuration files.
.. versionadded:: 2015.8.0
Returns a dict containing the new package names and versions::
{'<package>': {'old': '<old-version>',
'new': '<new-version>'}}
"""
_refresh_db = False
if salt.utils.data.is_true(refresh):
_refresh_db = True
if "version" in kwargs and kwargs["version"]:
_refresh_db = False
_latest_version = latest_version(name, refresh=False, show_installed=True)
_version = kwargs.get("version")
# If the versions don't match, refresh is True, otherwise no need
# to refresh
if not _latest_version == _version:
_refresh_db = True
if pkgs:
_refresh_db = False
for pkg in pkgs:
if isinstance(pkg, dict):
_name = next(iter(pkg.keys()))
_latest_version = latest_version(
_name, refresh=False, show_installed=True
)
_version = pkg[_name]
# If the versions don't match, refresh is True, otherwise
# no need to refresh
if not _latest_version == _version:
_refresh_db = True
else:
# No version specified, so refresh should be True
_refresh_db = True
if debconf:
__salt__["debconf.set_file"](debconf)
try:
pkg_params, pkg_type = __salt__["pkg_resource.parse_targets"](
name, pkgs, sources, **kwargs
)
except MinionError as exc:
raise CommandExecutionError(exc)
# Support old "repo" argument
repo = kwargs.get("repo", "")
if not fromrepo and repo:
fromrepo = repo
if not pkg_params:
return {}
cmd_prefix = []
old = list_pkgs()
targets = []
downgrade = []
to_reinstall = {}
errors = []
if pkg_type == "repository":
pkg_params_items = list(pkg_params.items())
has_comparison = [
x
for x, y in pkg_params_items
if y is not None and (y.startswith("<") or y.startswith(">"))
]
_available = (
list_repo_pkgs(*has_comparison, byrepo=False, **kwargs)
if has_comparison
else {}
)
# Build command prefix
cmd_prefix.extend(["apt-get", "-q", "-y"])
if kwargs.get("force_yes", False):
cmd_prefix.append("--force-yes")
if "force_conf_new" in kwargs and kwargs["force_conf_new"]:
cmd_prefix.extend(["-o", "DPkg::Options::=--force-confnew"])
else:
cmd_prefix.extend(["-o", "DPkg::Options::=--force-confold"])
cmd_prefix += ["-o", "DPkg::Options::=--force-confdef"]
if "install_recommends" in kwargs:
if not kwargs["install_recommends"]:
cmd_prefix.append("--no-install-recommends")
else:
cmd_prefix.append("--install-recommends")
if "only_upgrade" in kwargs and kwargs["only_upgrade"]:
cmd_prefix.append("--only-upgrade")
if skip_verify:
cmd_prefix.append("--allow-unauthenticated")
if fromrepo:
cmd_prefix.extend(["-t", fromrepo])
cmd_prefix.append("install")
else:
pkg_params_items = []
for pkg_source in pkg_params:
if "lowpkg.bin_pkg_info" in __salt__:
deb_info = __salt__["lowpkg.bin_pkg_info"](pkg_source)
else:
deb_info = None
if deb_info is None:
log.error(
"pkg.install: Unable to get deb information for %s. "
"Version comparisons will be unavailable.",
pkg_source,
)
pkg_params_items.append([pkg_source])
else:
pkg_params_items.append(
[deb_info["name"], pkg_source, deb_info["version"]]
)
# Build command prefix
if "force_conf_new" in kwargs and kwargs["force_conf_new"]:
cmd_prefix.extend(["dpkg", "-i", "--force-confnew"])
else:
cmd_prefix.extend(["dpkg", "-i", "--force-confold"])
if skip_verify:
cmd_prefix.append("--force-bad-verify")
for pkg_item_list in pkg_params_items:
if pkg_type == "repository":
pkgname, version_num = pkg_item_list
if name and pkgs is None and kwargs.get("version") and len(pkg_params) == 1:
# Only use the 'version' param if 'name' was not specified as a
# comma-separated list
version_num = kwargs["version"]
else:
try:
pkgname, pkgpath, version_num = pkg_item_list
except ValueError:
pkgname = None
pkgpath = pkg_item_list[0]
version_num = None
if version_num is None:
if pkg_type == "repository":
if reinstall and pkgname in old:
to_reinstall[pkgname] = pkgname
else:
targets.append(pkgname)
else:
targets.append(pkgpath)
else:
# If we are installing a package file and not one from the repo,
# and version_num is not None, then we can assume that pkgname is
# not None, since the only way version_num is not None is if DEB
# metadata parsing was successful.
if pkg_type == "repository":
# Remove leading equals sign(s) to keep from building a pkgstr
# with multiple equals (which would be invalid)
version_num = version_num.lstrip("=")
if pkgname in has_comparison:
candidates = _available.get(pkgname, [])
target = salt.utils.pkg.match_version(
version_num,
candidates,
cmp_func=version_cmp,
ignore_epoch=ignore_epoch,
)
if target is None:
errors.append(
"No version matching '{}{}' could be found "
"(available: {})".format(
pkgname,
version_num,
", ".join(candidates) if candidates else None,
)
)
continue
else:
version_num = target
pkgstr = "{}={}".format(pkgname, version_num)
else:
pkgstr = pkgpath
cver = old.get(pkgname, "")
if (
reinstall
and cver
and salt.utils.versions.compare(
ver1=version_num, oper="==", ver2=cver, cmp_func=version_cmp
)
):
to_reinstall[pkgname] = pkgstr
elif not cver or salt.utils.versions.compare(
ver1=version_num, oper=">=", ver2=cver, cmp_func=version_cmp
):
targets.append(pkgstr)
else:
downgrade.append(pkgstr)
if fromrepo and not sources:
log.info("Targeting repo '%s'", fromrepo)
cmds = []
all_pkgs = []
if targets:
all_pkgs.extend(targets)
cmd = copy.deepcopy(cmd_prefix)
cmd.extend(targets)
cmds.append(cmd)
if downgrade:
cmd = copy.deepcopy(cmd_prefix)
if pkg_type == "repository" and "--force-yes" not in cmd:
# Downgrading requires --force-yes. Insert this before 'install'
cmd.insert(-1, "--force-yes")
cmd.extend(downgrade)
cmds.append(cmd)
if downloadonly:
cmd.append("--download-only")
if to_reinstall:
all_pkgs.extend(to_reinstall)
cmd = copy.deepcopy(cmd_prefix)
if not sources:
cmd.append("--reinstall")
cmd.extend([x for x in to_reinstall.values()])
cmds.append(cmd)
if not cmds:
ret = {}
else:
cache_valid_time = kwargs.pop("cache_valid_time", 0)
if _refresh_db:
refresh_db(cache_valid_time)
env = _parse_env(kwargs.get("env"))
env.update(DPKG_ENV_VARS.copy())
#hold_pkgs = get_selections(state="hold").get("hold", [])
# all_pkgs contains the argument to be passed to apt-get install, which
# when a specific version is requested will be in the format
# name=version. Strip off the '=' if present so we can compare the
# held package names against the packages we are trying to install.
#targeted_names = [x.split("=")[0] for x in all_pkgs]
#to_unhold = [x for x in hold_pkgs if x in targeted_names]
#if to_unhold:
# unhold(pkgs=to_unhold)
for cmd in cmds:
out = _call_apt(cmd)
if out["retcode"] != 0 and out["stderr"]:
errors.append(out["stderr"])
__context__.pop("pkg.list_pkgs", None)
new = list_pkgs()
ret = salt.utils.data.compare_dicts(old, new)
for pkgname in to_reinstall:
if pkgname not in ret or pkgname in old:
ret.update(
{
pkgname: {
"old": old.get(pkgname, ""),
"new": new.get(pkgname, ""),
}
}
)
#if to_unhold:
# hold(pkgs=to_unhold)
if errors:
raise CommandExecutionError(
"Problem encountered installing package(s)",
info={"errors": errors, "changes": ret},
)
return ret
def _uninstall(action="remove", name=None, pkgs=None, **kwargs):
"""
remove and purge do identical things but with different apt-get commands,
this function performs the common logic.
"""
try:
pkg_params = __salt__["pkg_resource.parse_targets"](name, pkgs)[0]
except MinionError as exc:
raise CommandExecutionError(exc)
old = list_pkgs()
old_removed = list_pkgs(removed=True)
targets = [x for x in pkg_params if x in old]
if action == "purge":
targets.extend([x for x in pkg_params if x in old_removed])
cmd = ["apt-get", "-q", "-y", "--purge", "remove"]
else:
cmd = ["apt-get", "-q", "-y", action]
if not targets:
return {}
cmd.extend(targets)
env = _parse_env(kwargs.get("env"))
env.update(DPKG_ENV_VARS.copy())
out = _call_apt(cmd, env=env)
if out["retcode"] != 0 and out["stderr"]:
errors = [out["stderr"]]
else:
errors = []
__context__.pop("pkg.list_pkgs", None)
new = list_pkgs()
changes = salt.utils.data.compare_dicts(old, new)
ret = changes
if errors:
raise CommandExecutionError(
"Problem encountered removing package(s)",
info={"errors": errors, "changes": ret},
)
return ret
def autoremove(list_only=False, purge=False):
"""
.. versionadded:: 2015.5.0
Remove packages not required by another package using ``apt-get
autoremove``.
list_only : False
Only retrieve the list of packages to be auto-removed, do not actually
perform the auto-removal.
purge : False
Also remove package config data when autoremoving packages.
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' pkg.autoremove
salt '*' pkg.autoremove list_only=True
salt '*' pkg.autoremove purge=True
"""
cmd = []
if list_only:
ret = []
cmd.extend(["apt-get", "--no-remove"])
if purge:
cmd.append("--purge")
cmd.append("autoremove")
out = _call_apt(cmd, ignore_retcode=True)["stdout"]
found = False
for line in out.splitlines():
if found is True:
if line.startswith(" "):
ret.extend(line.split())
else:
found = False
elif "The following packages will be REMOVED:" in line:
found = True
ret.sort()
return ret
else:
old = list_pkgs()
cmd.extend(["apt-get", "--assume-yes"])
if purge:
cmd.append("--purge")
cmd.append("autoremove")
_call_apt(cmd, ignore_retcode=True)
__context__.pop("pkg.list_pkgs", None)
new = list_pkgs()
return salt.utils.data.compare_dicts(old, new)
def remove(name=None, pkgs=None, **kwargs):
"""
.. versionchanged:: 2015.8.12,2016.3.3,2016.11.0
On minions running systemd>=205, `systemd-run(1)`_ is now used to
isolate commands which modify installed packages from the
``salt-minion`` daemon's control group. This is done to keep systemd
from killing any apt-get/dpkg commands spawned by Salt when the
``salt-minion`` service is restarted. (see ``KillMode`` in the
`systemd.kill(5)`_ manpage for more information). If desired, usage of
`systemd-run(1)`_ can be suppressed by setting a :mod:`config option
<salt.modules.config.get>` called ``systemd.scope``, with a value of
``False`` (no quotes).
.. _`systemd-run(1)`: https://www.freedesktop.org/software/systemd/man/systemd-run.html
.. _`systemd.kill(5)`: https://www.freedesktop.org/software/systemd/man/systemd.kill.html
Remove packages using ``apt-get remove``.
name