-
Notifications
You must be signed in to change notification settings - Fork 5.5k
/
file.py
8152 lines (6848 loc) · 286 KB
/
file.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
# -*- coding: utf-8 -*-
'''
Operations on regular files, special files, directories, and symlinks
=====================================================================
Salt States can aggressively manipulate files on a system. There are a number
of ways in which files can be managed.
Regular files can be enforced with the :mod:`file.managed
<salt.states.file.managed>` state. This state downloads files from the salt
master and places them on the target system. Managed files can be rendered as a
jinja, mako, or wempy template, adding a dynamic component to file management.
An example of :mod:`file.managed <salt.states.file.managed>` which makes use of
the jinja templating system would look like this:
.. code-block:: jinja
/etc/http/conf/http.conf:
file.managed:
- source: salt://apache/http.conf
- user: root
- group: root
- mode: 644
- attrs: ai
- template: jinja
- defaults:
custom_var: "default value"
other_var: 123
{% if grains['os'] == 'Ubuntu' %}
- context:
custom_var: "override"
{% endif %}
It is also possible to use the :mod:`py renderer <salt.renderers.py>` as a
templating option. The template would be a Python script which would need to
contain a function called ``run()``, which returns a string. All arguments
to the state will be made available to the Python script as globals. The
returned string will be the contents of the managed file. For example:
.. code-block:: python
def run():
lines = ['foo', 'bar', 'baz']
lines.extend([source, name, user, context]) # Arguments as globals
return '\\n\\n'.join(lines)
.. note::
The ``defaults`` and ``context`` arguments require extra indentation (four
spaces instead of the normal two) in order to create a nested dictionary.
:ref:`More information <nested-dict-indentation>`.
If using a template, any user-defined template variables in the file defined in
``source`` must be passed in using the ``defaults`` and/or ``context``
arguments. The general best practice is to place default values in
``defaults``, with conditional overrides going into ``context``, as seen above.
The template will receive a variable ``custom_var``, which would be accessed in
the template using ``{{ custom_var }}``. If the operating system is Ubuntu, the
value of the variable ``custom_var`` would be *override*, otherwise it is the
default *default value*
The ``source`` parameter can be specified as a list. If this is done, then the
first file to be matched will be the one that is used. This allows you to have
a default file on which to fall back if the desired file does not exist on the
salt fileserver. Here's an example:
.. code-block:: jinja
/etc/foo.conf:
file.managed:
- source:
- salt://foo.conf.{{ grains['fqdn'] }}
- salt://foo.conf.fallback
- user: foo
- group: users
- mode: 644
- attrs: i
- backup: minion
.. note::
Salt supports backing up managed files via the backup option. For more
details on this functionality please review the
:ref:`backup_mode documentation <file-state-backups>`.
The ``source`` parameter can also specify a file in another Salt environment.
In this example ``foo.conf`` in the ``dev`` environment will be used instead.
.. code-block:: yaml
/etc/foo.conf:
file.managed:
- source:
- 'salt://foo.conf?saltenv=dev'
- user: foo
- group: users
- mode: '0644'
- attrs: i
.. warning::
When using a mode that includes a leading zero you must wrap the
value in single quotes. If the value is not wrapped in quotes it
will be read by YAML as an integer and evaluated as an octal.
The ``names`` parameter, which is part of the state compiler, can be used to
expand the contents of a single state declaration into multiple, single state
declarations. Each item in the ``names`` list receives its own individual state
``name`` and is converted into its own low-data structure. This is a convenient
way to manage several files with similar attributes.
.. code-block:: yaml
salt_master_conf:
file.managed:
- user: root
- group: root
- mode: '0644'
- names:
- /etc/salt/master.d/master.conf:
- source: salt://saltmaster/master.conf
- /etc/salt/minion.d/minion-99.conf:
- source: salt://saltmaster/minion.conf
.. note::
There is more documentation about this feature in the :ref:`Names declaration
<names-declaration>` section of the :ref:`Highstate docs <states-highstate>`.
Special files can be managed via the ``mknod`` function. This function will
create and enforce the permissions on a special file. The function supports the
creation of character devices, block devices, and FIFO pipes. The function will
create the directory structure up to the special file if it is needed on the
minion. The function will not overwrite or operate on (change major/minor
numbers) existing special files with the exception of user, group, and
permissions. In most cases the creation of some special files require root
permissions on the minion. This would require that the minion to be run as the
root user. Here is an example of a character device:
.. code-block:: yaml
/var/named/chroot/dev/random:
file.mknod:
- ntype: c
- major: 1
- minor: 8
- user: named
- group: named
- mode: 660
Here is an example of a block device:
.. code-block:: yaml
/var/named/chroot/dev/loop0:
file.mknod:
- ntype: b
- major: 7
- minor: 0
- user: named
- group: named
- mode: 660
Here is an example of a fifo pipe:
.. code-block:: yaml
/var/named/chroot/var/log/logfifo:
file.mknod:
- ntype: p
- user: named
- group: named
- mode: 660
Directories can be managed via the ``directory`` function. This function can
create and enforce the permissions on a directory. A directory statement will
look like this:
.. code-block:: yaml
/srv/stuff/substuf:
file.directory:
- user: fred
- group: users
- mode: 755
- makedirs: True
If you need to enforce user and/or group ownership or permissions recursively
on the directory's contents, you can do so by adding a ``recurse`` directive:
.. code-block:: yaml
/srv/stuff/substuf:
file.directory:
- user: fred
- group: users
- mode: 755
- makedirs: True
- recurse:
- user
- group
- mode
As a default, ``mode`` will resolve to ``dir_mode`` and ``file_mode``, to
specify both directory and file permissions, use this form:
.. code-block:: yaml
/srv/stuff/substuf:
file.directory:
- user: fred
- group: users
- file_mode: 744
- dir_mode: 755
- makedirs: True
- recurse:
- user
- group
- mode
Symlinks can be easily created; the symlink function is very simple and only
takes a few arguments:
.. code-block:: yaml
/etc/grub.conf:
file.symlink:
- target: /boot/grub/grub.conf
Recursive directory management can also be set via the ``recurse``
function. Recursive directory management allows for a directory on the salt
master to be recursively copied down to the minion. This is a great tool for
deploying large code and configuration systems. A state using ``recurse``
would look something like this:
.. code-block:: yaml
/opt/code/flask:
file.recurse:
- source: salt://code/flask
- include_empty: True
A more complex ``recurse`` example:
.. code-block:: jinja
{% set site_user = 'testuser' %}
{% set site_name = 'test_site' %}
{% set project_name = 'test_proj' %}
{% set sites_dir = 'test_dir' %}
django-project:
file.recurse:
- name: {{ sites_dir }}/{{ site_name }}/{{ project_name }}
- user: {{ site_user }}
- dir_mode: 2775
- file_mode: '0644'
- template: jinja
- source: salt://project/templates_dir
- include_empty: True
Retention scheduling can be applied to manage contents of backup directories.
For example:
.. code-block:: yaml
/var/backups/example_directory:
file.retention_schedule:
- strptime_format: example_name_%Y%m%dT%H%M%S.tar.bz2
- retain:
most_recent: 5
first_of_hour: 4
first_of_day: 14
first_of_week: 6
first_of_month: 6
first_of_year: all
'''
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import copy
import difflib
import itertools
import logging
import os
import posixpath
import re
import shutil
import sys
import time
import traceback
from collections import Iterable, Mapping, defaultdict
from datetime import datetime, date # python3 problem in the making?
# Import salt libs
import salt.loader
import salt.payload
import salt.utils.data
import salt.utils.dateutils
import salt.utils.dictupdate
import salt.utils.files
import salt.utils.hashutils
import salt.utils.path
import salt.utils.platform
import salt.utils.stringutils
import salt.utils.templates
import salt.utils.url
import salt.utils.versions
from salt.exceptions import CommandExecutionError
from salt.serializers import DeserializationError
from salt.state import get_accumulator_dir as _get_accumulator_dir
if salt.utils.platform.is_windows():
import salt.utils.win_dacl
import salt.utils.win_functions
import salt.utils.winapi
# Import 3rd-party libs
from salt.ext import six
from salt.ext.six.moves import zip_longest
from salt.ext.six.moves.urllib.parse import urlparse as _urlparse # pylint: disable=no-name-in-module
if salt.utils.platform.is_windows():
import pywintypes
import win32com.client
log = logging.getLogger(__name__)
COMMENT_REGEX = r'^([[:space:]]*){0}[[:space:]]?'
__NOT_FOUND = object()
__func_alias__ = {
'copy_': 'copy',
}
def _get_accumulator_filepath():
'''
Return accumulator data path.
'''
return os.path.join(
_get_accumulator_dir(__opts__['cachedir']),
__instance_id__
)
def _load_accumulators():
def _deserialize(path):
serial = salt.payload.Serial(__opts__)
ret = {'accumulators': {}, 'accumulators_deps': {}}
try:
with salt.utils.files.fopen(path, 'rb') as f:
loaded = serial.load(f)
return loaded if loaded else ret
except (IOError, NameError):
# NameError is a msgpack error from salt-ssh
return ret
loaded = _deserialize(_get_accumulator_filepath())
return loaded['accumulators'], loaded['accumulators_deps']
def _persist_accummulators(accumulators, accumulators_deps):
accumm_data = {'accumulators': accumulators,
'accumulators_deps': accumulators_deps}
serial = salt.payload.Serial(__opts__)
try:
with salt.utils.files.fopen(_get_accumulator_filepath(), 'w+b') as f:
serial.dump(accumm_data, f)
except NameError:
# msgpack error from salt-ssh
pass
def _check_user(user, group):
'''
Checks if the named user and group are present on the minion
'''
err = ''
if user:
uid = __salt__['file.user_to_uid'](user)
if uid == '':
err += 'User {0} is not available '.format(user)
if group:
gid = __salt__['file.group_to_gid'](group)
if gid == '':
err += 'Group {0} is not available'.format(group)
return err
def _is_valid_relpath(
relpath,
maxdepth=None):
'''
Performs basic sanity checks on a relative path.
Requires POSIX-compatible paths (i.e. the kind obtained through
cp.list_master or other such calls).
Ensures that the path does not contain directory transversal, and
that it does not exceed a stated maximum depth (if specified).
'''
# Check relpath surrounded by slashes, so that `..` can be caught as
# a path component at the start, end, and in the middle of the path.
sep, pardir = posixpath.sep, posixpath.pardir
if sep + pardir + sep in sep + relpath + sep:
return False
# Check that the relative path's depth does not exceed maxdepth
if maxdepth is not None:
path_depth = relpath.strip(sep).count(sep)
if path_depth > maxdepth:
return False
return True
def _salt_to_os_path(path):
'''
Converts a path from the form received via salt master to the OS's native
path format.
'''
return os.path.normpath(path.replace(posixpath.sep, os.path.sep))
def _gen_recurse_managed_files(
name,
source,
keep_symlinks=False,
include_pat=None,
exclude_pat=None,
maxdepth=None,
include_empty=False,
**kwargs):
'''
Generate the list of files managed by a recurse state
'''
# Convert a relative path generated from salt master paths to an OS path
# using "name" as the base directory
def full_path(master_relpath):
return os.path.join(name, _salt_to_os_path(master_relpath))
# Process symlinks and return the updated filenames list
def process_symlinks(filenames, symlinks):
for lname, ltarget in six.iteritems(symlinks):
srelpath = posixpath.relpath(lname, srcpath)
if not _is_valid_relpath(srelpath, maxdepth=maxdepth):
continue
if not salt.utils.stringutils.check_include_exclude(
srelpath, include_pat, exclude_pat):
continue
# Check for all paths that begin with the symlink
# and axe it leaving only the dirs/files below it.
# This needs to use list() otherwise they reference
# the same list.
_filenames = list(filenames)
for filename in _filenames:
if filename.startswith(lname):
log.debug('** skipping file ** {0}, it intersects a '
'symlink'.format(filename))
filenames.remove(filename)
# Create the symlink along with the necessary dirs.
# The dir perms/ownership will be adjusted later
# if needed
managed_symlinks.add((srelpath, ltarget))
# Add the path to the keep set in case clean is set to True
keep.add(full_path(srelpath))
vdir.update(keep)
return filenames
managed_files = set()
managed_directories = set()
managed_symlinks = set()
keep = set()
vdir = set()
srcpath, senv = salt.utils.url.parse(source)
if senv is None:
senv = __env__
if not srcpath.endswith(posixpath.sep):
# we're searching for things that start with this *directory*.
srcpath = srcpath + posixpath.sep
fns_ = __salt__['cp.list_master'](senv, srcpath)
# If we are instructed to keep symlinks, then process them.
if keep_symlinks:
# Make this global so that emptydirs can use it if needed.
symlinks = __salt__['cp.list_master_symlinks'](senv, srcpath)
fns_ = process_symlinks(fns_, symlinks)
for fn_ in fns_:
if not fn_.strip():
continue
# fn_ here is the absolute (from file_roots) source path of
# the file to copy from; it is either a normal file or an
# empty dir(if include_empty==true).
relname = salt.utils.data.decode(posixpath.relpath(fn_, srcpath))
if not _is_valid_relpath(relname, maxdepth=maxdepth):
continue
# Check if it is to be excluded. Match only part of the path
# relative to the target directory
if not salt.utils.stringutils.check_include_exclude(
relname, include_pat, exclude_pat):
continue
dest = full_path(relname)
dirname = os.path.dirname(dest)
keep.add(dest)
if dirname not in vdir:
# verify the directory perms if they are set
managed_directories.add(dirname)
vdir.add(dirname)
src = salt.utils.url.create(fn_, saltenv=senv)
managed_files.add((dest, src))
if include_empty:
mdirs = __salt__['cp.list_master_dirs'](senv, srcpath)
for mdir in mdirs:
relname = posixpath.relpath(mdir, srcpath)
if not _is_valid_relpath(relname, maxdepth=maxdepth):
continue
if not salt.utils.stringutils.check_include_exclude(
relname, include_pat, exclude_pat):
continue
mdest = full_path(relname)
# Check for symlinks that happen to point to an empty dir.
if keep_symlinks:
islink = False
for link in symlinks:
if mdir.startswith(link, 0):
log.debug('** skipping empty dir ** {0}, it intersects'
' a symlink'.format(mdir))
islink = True
break
if islink:
continue
managed_directories.add(mdest)
keep.add(mdest)
return managed_files, managed_directories, managed_symlinks, keep
def _gen_keep_files(name, require, walk_d=None):
'''
Generate the list of files that need to be kept when a dir based function
like directory or recurse has a clean.
'''
def _is_child(path, directory):
'''
Check whether ``path`` is child of ``directory``
'''
path = os.path.abspath(path)
directory = os.path.abspath(directory)
relative = os.path.relpath(path, directory)
return not relative.startswith(os.pardir)
def _add_current_path(path):
_ret = set()
if os.path.isdir(path):
dirs, files = walk_d.get(path, ((), ()))
_ret.add(path)
for _name in files:
_ret.add(os.path.join(path, _name))
for _name in dirs:
_ret.add(os.path.join(path, _name))
return _ret
def _process_by_walk_d(name, ret):
if os.path.isdir(name):
walk_ret.update(_add_current_path(name))
dirs, _ = walk_d.get(name, ((), ()))
for _d in dirs:
p = os.path.join(name, _d)
walk_ret.update(_add_current_path(p))
_process_by_walk_d(p, ret)
def _process(name):
ret = set()
if os.path.isdir(name):
for root, dirs, files in salt.utils.path.os_walk(name):
ret.add(name)
for name in files:
ret.add(os.path.join(root, name))
for name in dirs:
ret.add(os.path.join(root, name))
return ret
keep = set()
if isinstance(require, list):
required_files = [comp for comp in require if 'file' in comp]
for comp in required_files:
for low in __lowstate__:
# A requirement should match either the ID and the name of
# another state.
if low['name'] == comp['file'] or low['__id__'] == comp['file']:
fn = low['name']
fun = low['fun']
if os.path.isdir(fn):
if _is_child(fn, name):
if fun == 'recurse':
fkeep = _gen_recurse_managed_files(**low)[3]
log.debug('Keep from {0}: {1}'.format(fn, fkeep))
keep.update(fkeep)
elif walk_d:
walk_ret = set()
_process_by_walk_d(fn, walk_ret)
keep.update(walk_ret)
else:
keep.update(_process(fn))
else:
keep.add(fn)
log.debug('Files to keep from required states: {0}'.format(list(keep)))
return list(keep)
def _check_file(name):
ret = True
msg = ''
if not os.path.isabs(name):
ret = False
msg = 'Specified file {0} is not an absolute path'.format(name)
elif not os.path.exists(name):
ret = False
msg = '{0}: file not found'.format(name)
return ret, msg
def _find_keep_files(root, keep):
'''
Compile a list of valid keep files (and directories).
Used by _clean_dir()
'''
real_keep = set()
real_keep.add(root)
if isinstance(keep, list):
for fn_ in keep:
if not os.path.isabs(fn_):
continue
fn_ = os.path.normcase(os.path.abspath(fn_))
real_keep.add(fn_)
while True:
fn_ = os.path.abspath(os.path.dirname(fn_))
real_keep.add(fn_)
drive, path = os.path.splitdrive(fn_)
if not path.lstrip(os.sep):
break
return real_keep
def _clean_dir(root, keep, exclude_pat):
'''
Clean out all of the files and directories in a directory (root) while
preserving the files in a list (keep) and part of exclude_pat
'''
root = os.path.normcase(root)
real_keep = _find_keep_files(root, keep)
removed = set()
def _delete_not_kept(nfn):
if nfn not in real_keep:
# -- check if this is a part of exclude_pat(only). No need to
# check include_pat
if not salt.utils.stringutils.check_include_exclude(
os.path.relpath(nfn, root), None, exclude_pat):
return
removed.add(nfn)
if not __opts__['test']:
try:
os.remove(nfn)
except OSError:
__salt__['file.remove'](nfn)
for roots, dirs, files in salt.utils.path.os_walk(root):
for name in itertools.chain(dirs, files):
_delete_not_kept(os.path.join(roots, name))
return list(removed)
def _error(ret, err_msg):
ret['result'] = False
ret['comment'] = err_msg
return ret
def _check_directory(name,
user=None,
group=None,
recurse=False,
dir_mode=None,
file_mode=None,
clean=False,
require=False,
exclude_pat=None,
max_depth=None,
follow_symlinks=False):
'''
Check what changes need to be made on a directory
'''
changes = {}
if recurse or clean:
assert max_depth is None or not clean
# walk path only once and store the result
walk_l = list(_depth_limited_walk(name, max_depth))
# root: (dirs, files) structure, compatible for python2.6
walk_d = {}
for i in walk_l:
walk_d[i[0]] = (i[1], i[2])
if recurse:
try:
recurse_set = _get_recurse_set(recurse)
except (TypeError, ValueError) as exc:
return False, '{0}'.format(exc), changes
if 'user' not in recurse_set:
user = None
if 'group' not in recurse_set:
group = None
if 'mode' not in recurse_set:
dir_mode = None
file_mode = None
check_files = 'ignore_files' not in recurse_set
check_dirs = 'ignore_dirs' not in recurse_set
for root, dirs, files in walk_l:
if check_files:
for fname in files:
fchange = {}
path = os.path.join(root, fname)
stats = __salt__['file.stats'](
path, None, follow_symlinks
)
if user is not None and user != stats.get('user'):
fchange['user'] = user
if group is not None and group != stats.get('group'):
fchange['group'] = group
if file_mode is not None and salt.utils.files.normalize_mode(file_mode) != salt.utils.files.normalize_mode(stats.get('mode')):
fchange['mode'] = file_mode
if fchange:
changes[path] = fchange
if check_dirs:
for name_ in dirs:
path = os.path.join(root, name_)
fchange = _check_dir_meta(path, user, group, dir_mode, follow_symlinks)
if fchange:
changes[path] = fchange
# Recurse skips root (we always do dirs, not root), so always check root:
fchange = _check_dir_meta(name, user, group, dir_mode, follow_symlinks)
if fchange:
changes[name] = fchange
if clean:
keep = _gen_keep_files(name, require, walk_d)
def _check_changes(fname):
path = os.path.join(root, fname)
if path in keep:
return {}
else:
if not salt.utils.stringutils.check_include_exclude(
os.path.relpath(path, name), None, exclude_pat):
return {}
else:
return {path: {'removed': 'Removed due to clean'}}
for root, dirs, files in walk_l:
for fname in files:
changes.update(_check_changes(fname))
for name_ in dirs:
changes.update(_check_changes(name_))
if not os.path.isdir(name):
changes[name] = {'directory': 'new'}
if changes:
comments = ['The following files will be changed:\n']
for fn_ in changes:
for key, val in six.iteritems(changes[fn_]):
comments.append('{0}: {1} - {2}\n'.format(fn_, key, val))
return None, ''.join(comments), changes
return True, 'The directory {0} is in the correct state'.format(name), changes
def _check_directory_win(name,
win_owner=None,
win_perms=None,
win_deny_perms=None,
win_inheritance=None,
win_perms_reset=None):
'''
Check what changes need to be made on a directory
'''
changes = {}
if not os.path.isdir(name):
changes = {name: {'directory': 'new'}}
else:
# Check owner by SID
if win_owner is not None:
current_owner = salt.utils.win_dacl.get_owner(name)
current_owner_sid = salt.utils.win_functions.get_sid_from_name(current_owner)
expected_owner_sid = salt.utils.win_functions.get_sid_from_name(win_owner)
if not current_owner_sid == expected_owner_sid:
changes['owner'] = win_owner
# Check perms
perms = salt.utils.win_dacl.get_permissions(name)
# Verify Permissions
if win_perms is not None:
for user in win_perms:
# Check that user exists:
try:
salt.utils.win_dacl.get_name(user)
except CommandExecutionError:
continue
grant_perms = []
# Check for permissions
if isinstance(win_perms[user]['perms'], six.string_types):
if not salt.utils.win_dacl.has_permission(
name, user, win_perms[user]['perms']):
grant_perms = win_perms[user]['perms']
else:
for perm in win_perms[user]['perms']:
if not salt.utils.win_dacl.has_permission(
name, user, perm, exact=False):
grant_perms.append(win_perms[user]['perms'])
if grant_perms:
if 'grant_perms' not in changes:
changes['grant_perms'] = {}
if user not in changes['grant_perms']:
changes['grant_perms'][user] = {}
changes['grant_perms'][user]['perms'] = grant_perms
# Check Applies to
if 'applies_to' not in win_perms[user]:
applies_to = 'this_folder_subfolders_files'
else:
applies_to = win_perms[user]['applies_to']
if user in perms:
user = salt.utils.win_dacl.get_name(user)
# Get the proper applies_to text
at_flag = salt.utils.win_dacl.flags().ace_prop['file'][applies_to]
applies_to_text = salt.utils.win_dacl.flags().ace_prop['file'][at_flag]
if 'grant' in perms[user]:
if not perms[user]['grant']['applies to'] == applies_to_text:
if 'grant_perms' not in changes:
changes['grant_perms'] = {}
if user not in changes['grant_perms']:
changes['grant_perms'][user] = {}
changes['grant_perms'][user]['applies_to'] = applies_to
# Verify Deny Permissions
if win_deny_perms is not None:
for user in win_deny_perms:
# Check that user exists:
try:
salt.utils.win_dacl.get_name(user)
except CommandExecutionError:
continue
deny_perms = []
# Check for permissions
if isinstance(win_deny_perms[user]['perms'], six.string_types):
if not salt.utils.win_dacl.has_permission(
name, user, win_deny_perms[user]['perms'], 'deny'):
deny_perms = win_deny_perms[user]['perms']
else:
for perm in win_deny_perms[user]['perms']:
if not salt.utils.win_dacl.has_permission(
name, user, perm, 'deny', exact=False):
deny_perms.append(win_deny_perms[user]['perms'])
if deny_perms:
if 'deny_perms' not in changes:
changes['deny_perms'] = {}
if user not in changes['deny_perms']:
changes['deny_perms'][user] = {}
changes['deny_perms'][user]['perms'] = deny_perms
# Check Applies to
if 'applies_to' not in win_deny_perms[user]:
applies_to = 'this_folder_subfolders_files'
else:
applies_to = win_deny_perms[user]['applies_to']
if user in perms:
user = salt.utils.win_dacl.get_name(user)
# Get the proper applies_to text
at_flag = salt.utils.win_dacl.flags().ace_prop['file'][applies_to]
applies_to_text = salt.utils.win_dacl.flags().ace_prop['file'][at_flag]
if 'deny' in perms[user]:
if not perms[user]['deny']['applies to'] == applies_to_text:
if 'deny_perms' not in changes:
changes['deny_perms'] = {}
if user not in changes['deny_perms']:
changes['deny_perms'][user] = {}
changes['deny_perms'][user]['applies_to'] = applies_to
# Check inheritance
if win_inheritance is not None:
if not win_inheritance == salt.utils.win_dacl.get_inheritance(name):
changes['inheritance'] = win_inheritance
# Check reset
if win_perms_reset:
for user_name in perms:
if user_name not in win_perms:
if 'grant' in perms[user_name] and not perms[user_name]['grant']['inherited']:
if 'remove_perms' not in changes:
changes['remove_perms'] = {}
changes['remove_perms'].update({user_name: perms[user_name]})
if user_name not in win_deny_perms:
if 'deny' in perms[user_name] and not perms[user_name]['deny']['inherited']:
if 'remove_perms' not in changes:
changes['remove_perms'] = {}
changes['remove_perms'].update({user_name: perms[user_name]})
if changes:
return None, 'The directory "{0}" will be changed'.format(name), changes
return True, 'The directory {0} is in the correct state'.format(name), changes
def _check_dir_meta(name,
user,
group,
mode,
follow_symlinks=False):
'''
Check the changes in directory metadata
'''
try:
stats = __salt__['file.stats'](name, None, follow_symlinks)
except CommandExecutionError:
stats = {}
changes = {}
if not stats:
changes['directory'] = 'new'
return changes
if (user is not None
and user != stats['user']
and user != stats.get('uid')):
changes['user'] = user
if (group is not None
and group != stats['group']
and group != stats.get('gid')):
changes['group'] = group
# Normalize the dir mode
smode = salt.utils.files.normalize_mode(stats['mode'])
mode = salt.utils.files.normalize_mode(mode)
if mode is not None and mode != smode:
changes['mode'] = mode
return changes
def _check_touch(name, atime, mtime):
'''
Check to see if a file needs to be updated or created
'''
ret = {
'result': None,
'comment': '',
'changes': {'new': name},
}
if not os.path.exists(name):
ret['comment'] = 'File {0} is set to be created'.format(name)
else:
stats = __salt__['file.stats'](name, follow_symlinks=False)
if ((atime is not None
and six.text_type(atime) != six.text_type(stats['atime'])) or
(mtime is not None
and six.text_type(mtime) != six.text_type(stats['mtime']))):
ret['comment'] = 'Times set to be updated on file {0}'.format(name)
ret['changes'] = {'touched': name}
else:
ret['result'] = True
ret['comment'] = 'File {0} exists and has the correct times'.format(name)
return ret
def _get_symlink_ownership(path):
if salt.utils.platform.is_windows():