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
|
Upstream code not released yet that will happen in next major version
---
diff --git a/salt/modules/apk.py b/salt/modules/apk.py
new file mode 100644
index 0000000..4c0efe0
--- /dev/null
+++ b/salt/modules/apk.py
@@ -0,0 +1,619 @@
+# -*- coding: utf-8 -*-
+'''
+Support for apk
+
+.. 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>`.
+
+.. versionadded: Nitrogen
+
+'''
+from __future__ import absolute_import
+
+# Import python libs
+import copy
+import logging
+
+# Import salt libs
+import salt.utils
+import salt.utils.itertools
+
+from salt.exceptions import CommandExecutionError
+
+log = logging.getLogger(__name__)
+
+# Define the module's virtual name
+__virtualname__ = 'pkg'
+
+
+def __virtual__():
+ '''
+ Confirm this module is running on an Alpine Linux distribution
+ '''
+ if __grains__.get('os_family', False) == 'Alpine':
+ return __virtualname__
+ return (False, "Module apk only works on Alpine Linux based systems")
+
+#def autoremove(list_only=False, purge=False):
+# return 'Not available'
+#def hold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
+# return 'Not available'
+#def unhold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613
+# return 'Not available'
+#def upgrade_available(name):
+# return 'Not available'
+#def version_cmp(pkg1, pkg2, ignore_epoch=False):
+# return 'Not available'
+#def list_repos():
+# return 'Not available'
+#def get_repo(repo, **kwargs):
+# return 'Not available'
+#def del_repo(repo, **kwargs):
+# return 'Not available'
+#def del_repo_key(name=None, **kwargs):
+# return 'Not available'
+#def mod_repo(repo, saltenv='base', **kwargs):
+# return 'Not available'
+#def expand_repo_def(**kwargs):
+# return 'Not available'
+#def get_selections(pattern=None, state=None):
+# return 'Not available'
+#def set_selections(path=None, selection=None, clear=False, saltenv='base'):
+# return 'Not available'
+#def info_installed(*names):
+# return 'Not available'
+
+
+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():
+ '''
+ Updates the package list
+
+ - ``True``: Database updated successfully
+ - ``False``: Problem updating database
+
+ CLI Example:
+
+ .. code-block:: bash
+
+ salt '*' pkg.refresh_db
+ '''
+ ret = {}
+ cmd = ['apk', 'update']
+ call = __salt__['cmd.run_all'](cmd,
+ output_loglevel='trace',
+ python_shell=False)
+ if call['retcode'] == 0:
+ errors = []
+ ret = True
+ else:
+ errors = [call['stdout']]
+ ret = False
+
+ if errors:
+ raise CommandExecutionError(
+ 'Problem encountered installing package(s)',
+ info={'errors': errors, 'changes': ret}
+ )
+
+ return ret
+
+
+def list_pkgs(versions_as_list=False, **kwargs):
+ '''
+ List the packages currently installed in a dict::
+
+ {'<package_name>': '<version>'}
+
+ CLI Example:
+
+ .. code-block:: bash
+
+ salt '*' pkg.list_pkgs
+ salt '*' pkg.list_pkgs versions_as_list=True
+ '''
+ versions_as_list = salt.utils.is_true(versions_as_list)
+ # not yet implemented or not applicable
+ if any([salt.utils.is_true(kwargs.get(x))
+ for x in ('removed', 'purge_desired')]):
+ return {}
+
+ if 'pkg.list_pkgs' in __context__:
+ if versions_as_list:
+ return __context__['pkg.list_pkgs']
+ else:
+ ret = copy.deepcopy(__context__['pkg.list_pkgs'])
+ __salt__['pkg_resource.stringify'](ret)
+ return ret
+
+ cmd = ['apk', 'info', '-v']
+ ret = {}
+ out = __salt__['cmd.run'](cmd, output_loglevel='trace', python_shell=False)
+ for line in salt.utils.itertools.split(out, '\n'):
+ pkg_version = '-'.join(line.split('-')[-2:])
+ pkg_name = '-'.join(line.split('-')[:-2])
+ __salt__['pkg_resource.add_pkg'](ret, pkg_name, pkg_version)
+
+ __salt__['pkg_resource.sort_pkglist'](ret)
+ __context__['pkg.list_pkgs'] = copy.deepcopy(ret)
+ if not versions_as_list:
+ __salt__['pkg_resource.stringify'](ret)
+ return 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.
+
+ CLI Example:
+
+ .. code-block:: bash
+
+ salt '*' pkg.latest_version <package name>
+ salt '*' pkg.latest_version <package name>
+ salt '*' pkg.latest_version <package1> <package2> <package3> ...
+ '''
+ refresh = salt.utils.is_true(kwargs.pop('refresh', True))
+
+ if len(names) == 0:
+ return ''
+
+ ret = {}
+ for name in names:
+ ret[name] = ''
+ pkgs = list_pkgs()
+
+ # Refresh before looking for the latest version available
+ if refresh:
+ refresh_db()
+
+ # Upgrade check
+ cmd = ['apk', 'upgrade', '-s']
+ out = __salt__['cmd.run_stdout'](cmd,
+ output_loglevel='trace',
+ python_shell=False)
+ for line in salt.utils.itertools.split(out, '\n'):
+ try:
+ name = line.split(' ')[2]
+ _oldversion = line.split(' ')[3].strip('(')
+ newversion = line.split(' ')[5].strip(')')
+ if name in names:
+ ret[name] = newversion
+ except (ValueError, IndexError):
+ pass
+
+ # If version is empty, package may not be installed
+ for pkg in ret:
+ if not ret[pkg]:
+ installed = pkgs.get(pkg)
+ cmd = ['apk', 'search', pkg]
+ out = __salt__['cmd.run_stdout'](cmd,
+ output_loglevel='trace',
+ python_shell=False)
+ for line in salt.utils.itertools.split(out, '\n'):
+ try:
+ pkg_version = '-'.join(line.split('-')[-2:])
+ pkg_name = '-'.join(line.split('-')[:-2])
+ if pkg == pkg_name:
+ if installed == pkg_version:
+ ret[pkg] = ''
+ else:
+ ret[pkg] = pkg_version
+ except ValueError:
+ pass
+
+ # Return a string if only one package name passed
+ if len(names) == 1:
+ return ret[names[0]]
+ return ret
+
+
+# TODO: Support specific version installation
+def install(name=None,
+ refresh=False,
+ pkgs=None,
+ sources=None,
+ **kwargs):
+ '''
+ Install the passed package, add refresh=True to update the apk 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.
+
+ CLI Example:
+
+ .. code-block:: bash
+
+ salt '*' pkg.install <package name>
+
+ refresh
+ Whether or not to refresh the package database before installing.
+
+
+ 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"]'
+
+ sources
+ A list of IPK 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.
+
+ CLI Example:
+
+ .. code-block:: bash
+
+ salt '*' pkg.install sources='[{"foo": "salt://foo.deb"},{"bar": "salt://bar.deb"}]'
+
+ install_recommends
+ Whether to install the packages marked as recommended. Default is True.
+
+ Returns a dict containing the new package names and versions::
+
+ {'<package>': {'old': '<old-version>',
+ 'new': '<new-version>'}}
+ '''
+ refreshdb = salt.utils.is_true(refresh)
+ pkg_to_install = []
+
+ old = list_pkgs()
+
+ if name and not (pkgs or sources):
+ if ',' in name:
+ pkg_to_install = name.split(',')
+ else:
+ pkg_to_install = [name]
+
+ if pkgs:
+ # We don't support installing specific version for now
+ # so transform the dict in list ignoring version provided
+ pkgs = [
+ p.keys()[0] for p in pkgs
+ if isinstance(p, dict)
+ ]
+ pkg_to_install.extend(pkgs)
+
+ if not pkg_to_install:
+ return {}
+
+ if refreshdb:
+ refresh_db()
+
+ cmd = ['apk', 'add']
+
+ # Switch in update mode if a package is already installed
+ for _pkg in pkg_to_install:
+ if old.get(_pkg):
+ cmd.append('-u')
+ break
+
+ cmd.extend(pkg_to_install)
+
+ out = __salt__['cmd.run_all'](
+ cmd,
+ output_loglevel='trace',
+ python_shell=False
+ )
+
+ if out['retcode'] != 0 and out['stderr']:
+ errors = [out['stderr']]
+ else:
+ errors = []
+
+ __context__.pop('pkg.list_pkgs', None)
+ new = list_pkgs()
+ ret = salt.utils.compare_dicts(old, new)
+
+ if errors:
+ raise CommandExecutionError(
+ 'Problem encountered installing package(s)',
+ info={'errors': errors, 'changes': ret}
+ )
+
+ return ret
+
+
+def purge(name=None, pkgs=None, **kwargs):
+ '''
+ Alias to remove
+ '''
+ return remove(name=name, pkgs=pkgs, purge=True)
+
+
+def remove(name=None, pkgs=None, purge=False, **kwargs): # pylint: disable=unused-argument
+ '''
+ Remove packages using ``apk del``.
+
+ name
+ The name of the package to be deleted.
+
+
+ Multiple Package Options:
+
+ pkgs
+ A list of packages to delete. Must be passed as a python list. The
+ ``name`` parameter will be ignored if this option is passed.
+
+ Returns a dict containing the changes.
+
+ CLI Example:
+
+ .. code-block:: bash
+
+ salt '*' pkg.remove <package name>
+ salt '*' pkg.remove <package1>,<package2>,<package3>
+ salt '*' pkg.remove pkgs='["foo", "bar"]'
+ '''
+ old = list_pkgs()
+ pkg_to_remove = []
+
+ if name:
+ if ',' in name:
+ pkg_to_remove = name.split(',')
+ else:
+ pkg_to_remove = [name]
+
+ if pkgs:
+ pkg_to_remove.extend(pkgs)
+
+ if not pkg_to_remove:
+ return {}
+
+ if purge:
+ cmd = ['apk', 'del', '--purge']
+ else:
+ cmd = ['apk', 'del']
+
+ cmd.extend(pkg_to_remove)
+
+ out = __salt__['cmd.run_all'](
+ cmd,
+ output_loglevel='trace',
+ python_shell=False
+ )
+ if out['retcode'] != 0 and out['stderr']:
+ errors = [out['stderr']]
+ else:
+ errors = []
+
+ __context__.pop('pkg.list_pkgs', None)
+ new = list_pkgs()
+ ret = salt.utils.compare_dicts(old, new)
+
+ if errors:
+ raise CommandExecutionError(
+ 'Problem encountered removing package(s)',
+ info={'errors': errors, 'changes': ret}
+ )
+
+ return ret
+
+
+def upgrade(name=None, pkgs=None, refresh=True):
+ '''
+ Upgrades all packages via ``apk upgrade`` or a specific package if name or
+ pkgs is specified. Name is ignored if pkgs is specified
+
+ Returns a dict containing the changes.
+
+ {'<package>': {'old': '<old-version>',
+ 'new': '<new-version>'}}
+
+ CLI Example:
+
+ .. code-block:: bash
+
+ salt '*' pkg.upgrade
+ '''
+ ret = {'changes': {},
+ 'result': True,
+ 'comment': '',
+ }
+
+ if salt.utils.is_true(refresh):
+ refresh_db()
+
+ old = list_pkgs()
+
+ pkg_to_upgrade = []
+
+ if name and not pkgs:
+ if ',' in name:
+ pkg_to_upgrade = name.split(',')
+ else:
+ pkg_to_upgrade = [name]
+
+ if pkgs:
+ pkg_to_upgrade.extend(pkgs)
+
+ if pkg_to_upgrade:
+ cmd = ['apk', 'add', '-u']
+ cmd.extend(pkg_to_upgrade)
+ else:
+ cmd = ['apk', 'upgrade']
+
+ call = __salt__['cmd.run_all'](cmd,
+ output_loglevel='trace',
+ python_shell=False,
+ redirect_stderr=True)
+
+ if call['retcode'] != 0:
+ ret['result'] = False
+ if call['stdout']:
+ ret['comment'] = call['stdout']
+
+ __context__.pop('pkg.list_pkgs', None)
+ new = list_pkgs()
+ ret['changes'] = salt.utils.compare_dicts(old, new)
+
+ return ret
+
+
+def list_upgrades(refresh=True):
+ '''
+ List all available package upgrades.
+
+ CLI Example:
+
+ .. code-block:: bash
+
+ salt '*' pkg.list_upgrades
+ '''
+ ret = {}
+ if salt.utils.is_true(refresh):
+ refresh_db()
+
+ cmd = ['apk', 'upgrade', '-s']
+ call = __salt__['cmd.run_all'](cmd,
+ output_loglevel='trace',
+ python_shell=False)
+
+ if call['retcode'] != 0:
+ comment = ''
+ if 'stderr' in call:
+ comment += call['stderr']
+ if 'stdout' in call:
+ comment += call['stdout']
+ raise CommandExecutionError(
+ '{0}'.format(comment)
+ )
+ else:
+ out = call['stdout']
+
+ for line in out.splitlines():
+ if 'Upgrading' in line:
+ name = line.split(' ')[2]
+ _oldversion = line.split(' ')[3].strip('(')
+ newversion = line.split(' ')[5].strip(')')
+ ret[name] = newversion
+
+ return ret
+
+
+def file_list(*packages):
+ '''
+ List the files that belong to a package. Not specifying any packages will
+ return a list of _every_ file on the system's package database (not
+ generally recommended).
+
+ CLI Examples:
+
+ .. code-block:: bash
+
+ salt '*' pkg.file_list httpd
+ salt '*' pkg.file_list httpd postfix
+ salt '*' pkg.file_list
+ '''
+ return file_dict(*packages)
+
+
+def file_dict(*packages):
+ '''
+ List the files that belong to a package, grouped by package. Not
+ specifying any packages will return a list of _every_ file on the system's
+ package database (not generally recommended).
+
+ CLI Examples:
+
+ .. code-block:: bash
+
+ salt '*' pkg.file_list httpd
+ salt '*' pkg.file_list httpd postfix
+ salt '*' pkg.file_list
+ '''
+ errors = []
+ ret = {}
+ cmd_files = ['apk', 'info', '-L']
+
+ if not packages:
+ return 'Package name should be provided'
+
+ for package in packages:
+ files = []
+ cmd = cmd_files[:]
+ cmd.append(package)
+ out = __salt__['cmd.run_all'](cmd,
+ output_loglevel='trace',
+ python_shell=False)
+ for line in out['stdout'].splitlines():
+ if line.endswith('contains:'):
+ continue
+ else:
+ files.append(line)
+ if files:
+ ret[package] = files
+
+ return {'errors': errors, 'packages': ret}
+
+
+def owner(*paths):
+ '''
+ Return the name of the package that owns the file. Multiple file paths can
+ be passed. Like :mod:`pkg.version <salt.modules.apk.version`, if a single
+ path is passed, a string will be returned, and if multiple paths are passed,
+ a dictionary of file/package name pairs will be returned.
+
+ If the file is not owned by a package, or is not present on the minion,
+ then an empty string will be returned for that path.
+
+ CLI Example:
+
+ salt '*' pkg.owns /usr/bin/apachectl
+ salt '*' pkg.owns /usr/bin/apachectl /usr/bin/basename
+ '''
+ if not paths:
+ return 'You must provide a path'
+
+ ret = {}
+ cmd_search = ['apk', 'info', '-W']
+ for path in paths:
+ cmd = cmd_search[:]
+ cmd.append(path)
+ output = __salt__['cmd.run_stdout'](cmd,
+ output_loglevel='trace',
+ python_shell=False)
+ if output:
+ if 'ERROR:' in output:
+ ret[path] = 'Could not find owner package'
+ else:
+ ret[path] = output.split('by ')[1].strip()
+ else:
+ ret[path] = 'Error running {0}'.format(cmd)
+
+ return ret
diff --git a/salt/modules/gentoo_service.py b/salt/modules/gentoo_service.py
index 228a3fe..32dfcde 100644
--- a/salt/modules/gentoo_service.py
+++ b/salt/modules/gentoo_service.py
@@ -12,9 +12,14 @@ to the correct service manager
# Import Python libs
from __future__ import absolute_import
+import logging
-# Import Salt modules
+# Import salt libs
import salt.utils.systemd
+import salt.utils.odict as odict
+
+# Set up logging
+log = logging.getLogger(__name__)
# Define the module's virtual name
__virtualname__ = 'service'
@@ -22,13 +27,65 @@ __virtualname__ = 'service'
def __virtual__():
'''
- Only work on systems which default to systemd
+ Only work on systems which default to OpenRC
'''
- if __grains__['os'] == 'Gentoo' \
- and not salt.utils.systemd.booted(__context__):
+ if __grains__['os'] == 'Gentoo' and not salt.utils.systemd.booted(__context__):
+ return __virtualname__
+ if __grains__['os'] == 'Alpine':
return __virtualname__
return (False, 'The gentoo_service execution module cannot be loaded: '
- 'only available on Gentoo systems.')
+ 'only available on Gentoo/Open-RC systems.')
+
+
+def _ret_code(cmd):
+ log.debug('executing [{0}]'.format(cmd))
+ sts = __salt__['cmd.retcode'](cmd, python_shell=False)
+ return sts
+
+
+def _list_services():
+ return __salt__['cmd.run']('rc-update -v show').splitlines()
+
+
+def _get_service_list(include_enabled=True, include_disabled=False):
+ enabled_services = dict()
+ disabled_services = set()
+ lines = _list_services()
+ for line in lines:
+ if '|' not in line:
+ continue
+ service = [l.strip() for l in line.split('|')]
+ # enabled service should have runlevels
+ if service[1]:
+ if include_enabled:
+ enabled_services.update({service[0]: sorted(service[1].split())})
+ continue
+ # in any other case service is disabled
+ if include_disabled:
+ disabled_services.update({service[0]: []})
+ return enabled_services, disabled_services
+
+
+def _enable_delta(name, requested_runlevels):
+ all_enabled = get_enabled()
+ current_levels = set(all_enabled[name] if name in all_enabled else [])
+ enabled_levels = requested_runlevels - current_levels
+ disabled_levels = current_levels - requested_runlevels
+ return enabled_levels, disabled_levels
+
+
+def _disable_delta(name, requested_runlevels):
+ all_enabled = get_enabled()
+ current_levels = set(all_enabled[name] if name in all_enabled else [])
+ return current_levels & requested_runlevels
+
+
+def _service_cmd(*args):
+ return '/etc/init.d/{0} {1}'.format(args[0], ' '.join(args[1:]))
+
+
+def _enable_disable_cmd(name, command, runlevels=()):
+ return 'rc-update {0} {1} {2}'.format(command, name, ' '.join(sorted(runlevels))).strip()
def get_enabled():
@@ -41,15 +98,8 @@ def get_enabled():
salt '*' service.get_enabled
'''
- ret = set()
- lines = __salt__['cmd.run']('rc-update show').splitlines()
- for line in lines:
- if '|' not in line:
- continue
- if 'shutdown' in line:
- continue
- ret.add(line.split('|')[0].strip())
- return sorted(ret)
+ (enabled_services, disabled_services) = _get_service_list()
+ return odict.OrderedDict(enabled_services)
def get_disabled():
@@ -62,17 +112,9 @@ def get_disabled():
salt '*' service.get_disabled
'''
- ret = set()
- lines = __salt__['cmd.run']('rc-update -v show').splitlines()
- for line in lines:
- if '|' not in line:
- continue
- elif 'shutdown' in line:
- continue
- comps = line.split()
- if len(comps) < 3:
- ret.add(comps[0])
- return sorted(ret)
+ (enabled_services, disabled_services) = _get_service_list(include_enabled=False,
+ include_disabled=True)
+ return sorted(disabled_services)
def available(name):
@@ -86,7 +128,9 @@ def available(name):
salt '*' service.available sshd
'''
- return name in get_all()
+ (enabled_services, disabled_services) = _get_service_list(include_enabled=True,
+ include_disabled=True)
+ return name in enabled_services or name in disabled_services
def missing(name):
@@ -101,7 +145,7 @@ def missing(name):
salt '*' service.missing sshd
'''
- return name not in get_all()
+ return not available(name)
def get_all():
@@ -114,7 +158,10 @@ def get_all():
salt '*' service.get_all
'''
- return sorted(get_enabled() + get_disabled())
+ (enabled_services, disabled_services) = _get_service_list(include_enabled=True,
+ include_disabled=True)
+ enabled_services.update(dict([(s, []) for s in disabled_services]))
+ return odict.OrderedDict(enabled_services)
def start(name):
@@ -127,8 +174,8 @@ def start(name):
salt '*' service.start <service name>
'''
- cmd = '/etc/init.d/{0} start'.format(name)
- return not __salt__['cmd.retcode'](cmd, python_shell=False)
+ cmd = _service_cmd(name, 'start')
+ return not _ret_code(cmd)
def stop(name):
@@ -141,8 +188,8 @@ def stop(name):
salt '*' service.stop <service name>
'''
- cmd = '/etc/init.d/{0} stop'.format(name)
- return not __salt__['cmd.retcode'](cmd, python_shell=False)
+ cmd = _service_cmd(name, 'stop')
+ return not _ret_code(cmd)
def restart(name):
@@ -155,8 +202,36 @@ def restart(name):
salt '*' service.restart <service name>
'''
- cmd = '/etc/init.d/{0} restart'.format(name)
- return not __salt__['cmd.retcode'](cmd, python_shell=False)
+ cmd = _service_cmd(name, 'restart')
+ return not _ret_code(cmd)
+
+
+def reload_(name):
+ '''
+ Reload the named service
+
+ CLI Example:
+
+ .. code-block:: bash
+
+ salt '*' service.reload <service name>
+ '''
+ cmd = _service_cmd(name, 'reload')
+ return not _ret_code(cmd)
+
+
+def zap(name):
+ '''
+ Resets service state
+
+ CLI Example:
+
+ .. code-block:: bash
+
+ salt '*' service.zap <service name>
+ '''
+ cmd = _service_cmd(name, 'zap')
+ return not _ret_code(cmd)
def status(name, sig=None):
@@ -171,7 +246,10 @@ def status(name, sig=None):
salt '*' service.status <service name> [service signature]
'''
- return __salt__['status.pid'](sig if sig else name)
+ if sig:
+ return bool(__salt__['status.pid'](sig))
+ cmd = _service_cmd(name, 'status')
+ return not _ret_code(cmd)
def enable(name, **kwargs):
@@ -182,10 +260,26 @@ def enable(name, **kwargs):
.. code-block:: bash
- salt '*' service.enable <service name>
+ salt '*' service.enable <service name> <runlevels=single-runlevel>
+ salt '*' service.enable <service name> <runlevels=[runlevel1,runlevel2]>
'''
- cmd = 'rc-update add {0} default'.format(name)
- return not __salt__['cmd.retcode'](cmd, python_shell=False)
+ if 'runlevels' in kwargs:
+ requested_levels = set(kwargs['runlevels'] if isinstance(kwargs['runlevels'],
+ list) else [kwargs['runlevels']])
+ enabled_levels, disabled_levels = _enable_delta(name, requested_levels)
+ commands = []
+ if disabled_levels:
+ commands.append(_enable_disable_cmd(name, 'delete', disabled_levels))
+ if enabled_levels:
+ commands.append(_enable_disable_cmd(name, 'add', enabled_levels))
+ if not commands:
+ return True
+ else:
+ commands = [_enable_disable_cmd(name, 'add')]
+ for cmd in commands:
+ if _ret_code(cmd):
+ return False
+ return True
def disable(name, **kwargs):
@@ -196,10 +290,18 @@ def disable(name, **kwargs):
.. code-block:: bash
- salt '*' service.disable <service name>
+ salt '*' service.disable <service name> <runlevels=single-runlevel>
+ salt '*' service.disable <service name> <runlevels=[runlevel1,runlevel2]>
'''
- cmd = 'rc-update delete {0} default'.format(name)
- return not __salt__['cmd.retcode'](cmd, python_shell=False)
+ levels = []
+ if 'runlevels' in kwargs:
+ requested_levels = set(kwargs['runlevels'] if isinstance(kwargs['runlevels'],
+ list) else [kwargs['runlevels']])
+ levels = _disable_delta(name, requested_levels)
+ if not levels:
+ return True
+ cmd = _enable_disable_cmd(name, 'delete', levels)
+ return not _ret_code(cmd)
def enabled(name, **kwargs):
@@ -210,9 +312,17 @@ def enabled(name, **kwargs):
.. code-block:: bash
- salt '*' service.enabled <service name>
+ salt '*' service.enabled <service name> <runlevels=single-runlevel>
+ salt '*' service.enabled <service name> <runlevels=[runlevel1,runlevel2]>
'''
- return name in get_enabled()
+ enabled_services = get_enabled()
+ if name not in enabled_services:
+ return False
+ if 'runlevels' not in kwargs:
+ return True
+ requested_levels = set(kwargs['runlevels'] if isinstance(kwargs['runlevels'],
+ list) else [kwargs['runlevels']])
+ return len(requested_levels - set(enabled_services[name])) == 0
def disabled(name):
@@ -223,6 +333,6 @@ def disabled(name):
.. code-block:: bash
- salt '*' service.disabled <service name>
+ salt '*' service.disabled <service name> <runlevels=[runlevel]>
'''
return name in get_disabled()
--
2.10.0
|