blob: 83c51a621c66ab8ef3a84fed49d81606d001b0e0 [file] [log] [blame]
azvyagintseve5c4e832018-01-25 20:02:46 +02001#!/usr/bin/env python
2"""
3Management of debmirror
4=======================
5
6Create debian mirrors, using debmirror
7--------------------------------------
8
9.. code-block:: yaml
10 debmirror_test1_present:
11 debmirror.mirror_present:
12 - name: test1
13
14"""
15import logging
16import os
17from functools import wraps
18from salt.exceptions import CommandExecutionError, SaltInvocationError
19log = logging.getLogger(__name__)
20
azvyagintsev73720db2018-06-20 17:28:09 +030021
azvyagintseve5c4e832018-01-25 20:02:46 +020022def __virtual__():
23 '''
24 Only load this module if debmirror is installed with deps.
25 '''
26 return 'debmirror'
27
azvyagintsev73720db2018-06-20 17:28:09 +030028
azvyagintseve5c4e832018-01-25 20:02:46 +020029def _test_call(method):
30 (resource, functionality) = method.func_name.split('_')
31 if functionality == 'present':
32 functionality = 'updated'
33 else:
34 functionality = 'removed'
35
36 @wraps(method)
37 def check_for_testing(name, *args, **kwargs):
38 if __opts__.get('test', None):
39 return _no_change(name, resource, test=functionality)
40 return method(name, *args, **kwargs)
azvyagintsev73720db2018-06-20 17:28:09 +030041
azvyagintseve5c4e832018-01-25 20:02:46 +020042 return check_for_testing
43
azvyagintsev73720db2018-06-20 17:28:09 +030044
azvyagintseve5c4e832018-01-25 20:02:46 +020045def _created(name, resource, resource_definition={}):
46 changes_dict = {'name': name,
47 'changes': resource_definition,
48 'result': True,
49 'comment': '{0} {1} created'.format(resource, name)}
50 return changes_dict
51
azvyagintsev73720db2018-06-20 17:28:09 +030052
azvyagintseve5c4e832018-01-25 20:02:46 +020053def _failed(name, resource, resource_definition={}):
54 changes_dict = {'name': name,
55 'changes': resource_definition,
56 'result': False,
azvyagintsev73720db2018-06-20 17:28:09 +030057 'comment': '{0} {1} failed to create'.format(resource,
58 name)}
azvyagintseve5c4e832018-01-25 20:02:46 +020059 return changes_dict
60
azvyagintsev73720db2018-06-20 17:28:09 +030061
azvyagintseve5c4e832018-01-25 20:02:46 +020062def _no_change(name, resource, test=False):
63 changes_dict = {'name': name,
64 'changes': {},
65 'result': True}
66 if test:
67 changes_dict['comment'] = \
68 '{0} {1} will be {2}'.format(resource, name, test)
69 else:
70 changes_dict['comment'] = \
71 '{0} {1} is in correct state'.format(resource, name)
72 return changes_dict
73
azvyagintsev73720db2018-06-20 17:28:09 +030074
azvyagintseve5c4e832018-01-25 20:02:46 +020075def _check_state(name, tgt):
azvyagintsev73720db2018-06-20 17:28:09 +030076 lock_file = _get_target_path(name, tgt)['lock_file']
77 if os.path.isfile(lock_file) and not tgt.get('force', False):
azvyagintsevb80d6222018-02-19 15:53:40 +020078 return _no_change(name, '{} exist=>repo locked.'.format(lock_file))
azvyagintseve5c4e832018-01-25 20:02:46 +020079 return False
80
azvyagintsev73720db2018-06-20 17:28:09 +030081
82def _get_target_path(name, tgt):
83 if not tgt.get('target_dir', False):
azvyagintseve5c4e832018-01-25 20:02:46 +020084 raise SaltInvocationError('Argument "target_dir" is mandatory! ')
85 return {'target_dir': tgt.get('target_dir'),
azvyagintsev73720db2018-06-20 17:28:09 +030086 'lock_file': tgt.get('lock_file',
87 os.path.join(tgt.get('target_dir'),
88 '.lockmirror')),
89 'log_file': tgt.get('log_file', '/var/log/debmirror_'.join(name))}
azvyagintseve5c4e832018-01-25 20:02:46 +020090
azvyagintsev73720db2018-06-20 17:28:09 +030091
92def _get_env(tgt):
93 env = {}
94 for k in ['http_proxy', 'https_proxy', 'ftp_proxy', 'rsync_proxy']:
95 if tgt.get(k, False):
96 env[k] = tgt[k]
97 env[k.upper()] = env[k]
98 if tgt.get('no_proxy', False):
99 env['no_proxy'] = ','.join(str(x) for x in tgt['no_proxy'])
100 env['no_proxy'.upper()] = env['no_proxy']
101 return env
102
103
104def _get_cmdline(name, tgt):
azvyagintseve5c4e832018-01-25 20:02:46 +0200105 cmdline = " debmirror "
106 if tgt.get('extra_flags'):
azvyagintsev73720db2018-06-20 17:28:09 +0300107 cmdline += ' '.join(tgt['extra_flags'])
Denis Egorenko39db2a62018-10-30 14:37:17 +0400108 if tgt.get('rsync_options'):
109 rsync_options = tgt.get('rsync_options')
110 if tgt.get('rsync_options_defaults', True):
111 rsync_options = ['-aL', '--partial'] + rsync_options
112 cmdline += " --rsync-options='" + ' '.join(rsync_options) + "'"
azvyagintseve5c4e832018-01-25 20:02:46 +0200113 if tgt.get('dist'):
azvyagintsev73720db2018-06-20 17:28:09 +0300114 cmdline += ' --dist=' + ",".join(tgt['dist'])
azvyagintseve5c4e832018-01-25 20:02:46 +0200115 if tgt.get('section'):
azvyagintsev73720db2018-06-20 17:28:09 +0300116 cmdline += ' --section=' + ",".join(tgt['section'])
azvyagintseve5c4e832018-01-25 20:02:46 +0200117 if tgt.get('method'):
azvyagintsev73720db2018-06-20 17:28:09 +0300118 cmdline += ' --method=' + tgt.get('method')
azvyagintseve5c4e832018-01-25 20:02:46 +0200119 if tgt.get('mirror_host'):
azvyagintsev73720db2018-06-20 17:28:09 +0300120 cmdline += ' --host="{}"'.format(tgt.get('mirror_host'))
azvyagintseve5c4e832018-01-25 20:02:46 +0200121 if tgt.get('mirror_root'):
azvyagintsev73720db2018-06-20 17:28:09 +0300122 cmdline += ' --root="{}"'.format(tgt.get('mirror_root'))
azvyagintseve5c4e832018-01-25 20:02:46 +0200123 if tgt.get('arch', 'amd64'):
azvyagintsev73720db2018-06-20 17:28:09 +0300124 cmdline += ' --arch=' + ','.join(tgt.get('arch'))
azvyagintsev6e410f92018-03-07 23:35:05 +0200125 if tgt.get('exclude_deb_section'):
azvyagintsev73720db2018-06-20 17:28:09 +0300126 for section in tgt['exclude_deb_section']:
127 cmdline += " --exclude-deb-section='" + section + "'"
azvyagintseve5c4e832018-01-25 20:02:46 +0200128 if tgt.get('filter'):
azvyagintsev73720db2018-06-20 17:28:09 +0300129 for key, value in enumerate(sorted(tgt['filter'])):
130 cmdline += " " + tgt['filter'][value]
131 if tgt.get('target_dir', False):
132 cmdline += ' ' + _get_target_path(name, tgt)['target_dir']
azvyagintseve5c4e832018-01-25 20:02:46 +0200133 return cmdline
134
azvyagintsev73720db2018-06-20 17:28:09 +0300135
136def _update_mirror(name, tgt):
azvyagintseve5c4e832018-01-25 20:02:46 +0200137 # Remove old lock file, is was.
azvyagintsev73720db2018-06-20 17:28:09 +0300138 lock_file = _get_target_path(name, tgt)['lock_file']
azvyagintseve5c4e832018-01-25 20:02:46 +0200139 if os.path.isfile(lock_file):
azvyagintsev73720db2018-06-20 17:28:09 +0300140 log.debug("Removing lockfile:{} for mirror{}".format(lock_file, name))
azvyagintseve5c4e832018-01-25 20:02:46 +0200141 __states__['file.absent'](lock_file)
azvyagintsev73720db2018-06-20 17:28:09 +0300142 cmdline = _get_cmdline(name, tgt)
143 # fetch ENV params for proxy
144 env_vars = _get_env(tgt)
azvyagintseve5c4e832018-01-25 20:02:46 +0200145 # init file logger
146 l_dir = os.path.dirname(tgt['log_file'])
147 if not os.path.isdir(l_dir):
azvyagintsevf5fc6532018-02-21 22:17:02 +0200148 __salt__['file.makedirs'](l_dir + '/')
azvyagintsev73720db2018-06-20 17:28:09 +0300149 fh = logging.FileHandler(
150 "{0}".format(_get_target_path(name, tgt)['log_file']))
azvyagintseve5c4e832018-01-25 20:02:46 +0200151 fh.setLevel(logging.DEBUG)
azvyagintsev73720db2018-06-20 17:28:09 +0300152 fh_format = logging.Formatter(
153 '%(asctime)s - %(lineno)d - %(levelname)-8s - %(message)s')
azvyagintseve5c4e832018-01-25 20:02:46 +0200154 fh.setFormatter(fh_format)
155 log2file = logging.getLogger("debmirror")
156 log2file.addHandler(fh)
azvyagintsev73720db2018-06-20 17:28:09 +0300157 result = __salt__['cmd.run_all'](cmdline, redirect_stderr=True,
158 env=env_vars)
azvyagintseve5c4e832018-01-25 20:02:46 +0200159 log2file.debug(result['stdout'])
160 # destroy file logger
161 for i in list(log2file.handlers):
162 log2file.removeHandler(i)
163 i.flush()
164 i.close()
165 if result['retcode'] != 0:
azvyagintsev73720db2018-06-20 17:28:09 +0300166 # raise CommandExecutionError(result['stderr'])
167 return _failed(name,
168 "debmirror failed.Reason {0}".format(result['stderr']))
169 if tgt.get('lock_target', None):
azvyagintseve5c4e832018-01-25 20:02:46 +0200170 __states__['file.touch'](lock_file)
azvyagintsev73720db2018-06-20 17:28:09 +0300171 return _created(name, "Mirror {0} created.".format(name))
172
azvyagintseve5c4e832018-01-25 20:02:46 +0200173
174@_test_call
175def mirror_present(name, **kwargs):
176 '''
177
178 :param name: mirror key name
179 '''
180 try:
181 tgt = __salt__['config.get']('debmirror')['client']['mirrors'][name]
182 except KeyError:
azvyagintsev73720db2018-06-20 17:28:09 +0300183 comment = 'Mirror "{0}" not exist in configurathion,skipping..'.format(
184 name)
azvyagintseve5c4e832018-01-25 20:02:46 +0200185 return _no_change(name, comment)
186
azvyagintsev73720db2018-06-20 17:28:09 +0300187 current_state = _check_state(name, tgt)
azvyagintseve5c4e832018-01-25 20:02:46 +0200188 if not current_state:
azvyagintsev73720db2018-06-20 17:28:09 +0300189 return _update_mirror(name, tgt)
azvyagintseve5c4e832018-01-25 20:02:46 +0200190 return current_state