blob: 2c0bb8ab0437ea5aef4d44eaa509abe5b6cc8f90 [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
Denis Egorenko964ba9a2018-10-31 17:22:05 +0400104def _check_mirror_cache(cache_dir):
105 cacheReadinessKeyFile = os.path.join(cache_dir, '.ready')
106 return os.path.isfile(cacheReadinessKeyFile)
107
108
azvyagintsev73720db2018-06-20 17:28:09 +0300109def _get_cmdline(name, tgt):
azvyagintseve5c4e832018-01-25 20:02:46 +0200110 cmdline = " debmirror "
111 if tgt.get('extra_flags'):
azvyagintsev73720db2018-06-20 17:28:09 +0300112 cmdline += ' '.join(tgt['extra_flags'])
Denis Egorenko39db2a62018-10-30 14:37:17 +0400113 if tgt.get('rsync_options'):
114 rsync_options = tgt.get('rsync_options')
115 if tgt.get('rsync_options_defaults', True):
116 rsync_options = ['-aL', '--partial'] + rsync_options
117 cmdline += " --rsync-options='" + ' '.join(rsync_options) + "'"
azvyagintseve5c4e832018-01-25 20:02:46 +0200118 if tgt.get('dist'):
azvyagintsev73720db2018-06-20 17:28:09 +0300119 cmdline += ' --dist=' + ",".join(tgt['dist'])
azvyagintseve5c4e832018-01-25 20:02:46 +0200120 if tgt.get('section'):
azvyagintsev73720db2018-06-20 17:28:09 +0300121 cmdline += ' --section=' + ",".join(tgt['section'])
azvyagintseve5c4e832018-01-25 20:02:46 +0200122 if tgt.get('method'):
azvyagintsev73720db2018-06-20 17:28:09 +0300123 cmdline += ' --method=' + tgt.get('method')
azvyagintseve5c4e832018-01-25 20:02:46 +0200124 if tgt.get('mirror_host'):
azvyagintsev73720db2018-06-20 17:28:09 +0300125 cmdline += ' --host="{}"'.format(tgt.get('mirror_host'))
azvyagintseve5c4e832018-01-25 20:02:46 +0200126 if tgt.get('mirror_root'):
azvyagintsev73720db2018-06-20 17:28:09 +0300127 cmdline += ' --root="{}"'.format(tgt.get('mirror_root'))
azvyagintseve5c4e832018-01-25 20:02:46 +0200128 if tgt.get('arch', 'amd64'):
azvyagintsev73720db2018-06-20 17:28:09 +0300129 cmdline += ' --arch=' + ','.join(tgt.get('arch'))
azvyagintsev6e410f92018-03-07 23:35:05 +0200130 if tgt.get('exclude_deb_section'):
azvyagintsev73720db2018-06-20 17:28:09 +0300131 for section in tgt['exclude_deb_section']:
132 cmdline += " --exclude-deb-section='" + section + "'"
azvyagintseve5c4e832018-01-25 20:02:46 +0200133 if tgt.get('filter'):
azvyagintsev73720db2018-06-20 17:28:09 +0300134 for key, value in enumerate(sorted(tgt['filter'])):
135 cmdline += " " + tgt['filter'][value]
136 if tgt.get('target_dir', False):
Denis Egorenko964ba9a2018-10-31 17:22:05 +0400137 target_dir = _get_target_path(name, tgt)['target_dir']
138 if tgt.get('cache_dir'):
139 cache_dir = tgt.get('cache_dir')
140 if _check_mirror_cache(cache_dir):
141 cmdline += ' ' + target_dir
142 else:
143 cmdline += ' ' + cache_dir
144 else:
145 cmdline += ' ' + target_dir
azvyagintseve5c4e832018-01-25 20:02:46 +0200146 return cmdline
147
azvyagintsev73720db2018-06-20 17:28:09 +0300148
149def _update_mirror(name, tgt):
azvyagintseve5c4e832018-01-25 20:02:46 +0200150 # Remove old lock file, is was.
azvyagintsev73720db2018-06-20 17:28:09 +0300151 lock_file = _get_target_path(name, tgt)['lock_file']
azvyagintseve5c4e832018-01-25 20:02:46 +0200152 if os.path.isfile(lock_file):
azvyagintsev73720db2018-06-20 17:28:09 +0300153 log.debug("Removing lockfile:{} for mirror{}".format(lock_file, name))
azvyagintseve5c4e832018-01-25 20:02:46 +0200154 __states__['file.absent'](lock_file)
azvyagintsev73720db2018-06-20 17:28:09 +0300155 cmdline = _get_cmdline(name, tgt)
156 # fetch ENV params for proxy
157 env_vars = _get_env(tgt)
azvyagintseve5c4e832018-01-25 20:02:46 +0200158 # init file logger
159 l_dir = os.path.dirname(tgt['log_file'])
160 if not os.path.isdir(l_dir):
azvyagintsevf5fc6532018-02-21 22:17:02 +0200161 __salt__['file.makedirs'](l_dir + '/')
azvyagintsev73720db2018-06-20 17:28:09 +0300162 fh = logging.FileHandler(
163 "{0}".format(_get_target_path(name, tgt)['log_file']))
azvyagintseve5c4e832018-01-25 20:02:46 +0200164 fh.setLevel(logging.DEBUG)
azvyagintsev73720db2018-06-20 17:28:09 +0300165 fh_format = logging.Formatter(
166 '%(asctime)s - %(lineno)d - %(levelname)-8s - %(message)s')
azvyagintseve5c4e832018-01-25 20:02:46 +0200167 fh.setFormatter(fh_format)
168 log2file = logging.getLogger("debmirror")
169 log2file.addHandler(fh)
Denis Egorenko964ba9a2018-10-31 17:22:05 +0400170 # check cache usage
171 if tgt.get('cache_dir'):
172 cache_dir = tgt.get('cache_dir')
173 target_dir = _get_target_path(name, tgt)['target_dir']
174 cpline = "find . -name *.deb -exec cp -rlf --parent {} %s \\;" % (
175 target_dir)
176 if _check_mirror_cache(cache_dir):
177 result = __salt__['cmd.run_all'](cpline, redirect_stderr=True,
178 cwd=cache_dir, env=env_vars)
179 if result['retcode'] == 0:
180 log2file.debug(result['stdout'])
181 result = __salt__['cmd.run_all'](cmdline, redirect_stderr=True,
182 env=env_vars)
183 else:
184 result = __salt__['cmd.run_all'](cmdline, redirect_stderr=True,
185 env=env_vars)
186 if result['retcode'] == 0:
187 log2file.debug(result['stdout'])
188 result = __salt__['cmd.run_all'](cpline, redirect_stderr=True,
189 cwd=cache_dir, env=env_vars)
190 else:
191 result = __salt__['cmd.run_all'](cmdline, redirect_stderr=True,
192 env=env_vars)
azvyagintseve5c4e832018-01-25 20:02:46 +0200193 log2file.debug(result['stdout'])
194 # destroy file logger
195 for i in list(log2file.handlers):
196 log2file.removeHandler(i)
197 i.flush()
198 i.close()
199 if result['retcode'] != 0:
azvyagintsev73720db2018-06-20 17:28:09 +0300200 # raise CommandExecutionError(result['stderr'])
201 return _failed(name,
202 "debmirror failed.Reason {0}".format(result['stderr']))
203 if tgt.get('lock_target', None):
azvyagintseve5c4e832018-01-25 20:02:46 +0200204 __states__['file.touch'](lock_file)
azvyagintsev73720db2018-06-20 17:28:09 +0300205 return _created(name, "Mirror {0} created.".format(name))
206
azvyagintseve5c4e832018-01-25 20:02:46 +0200207
208@_test_call
209def mirror_present(name, **kwargs):
210 '''
211
212 :param name: mirror key name
213 '''
214 try:
215 tgt = __salt__['config.get']('debmirror')['client']['mirrors'][name]
216 except KeyError:
azvyagintsev73720db2018-06-20 17:28:09 +0300217 comment = 'Mirror "{0}" not exist in configurathion,skipping..'.format(
218 name)
azvyagintseve5c4e832018-01-25 20:02:46 +0200219 return _no_change(name, comment)
220
azvyagintsev73720db2018-06-20 17:28:09 +0300221 current_state = _check_state(name, tgt)
azvyagintseve5c4e832018-01-25 20:02:46 +0200222 if not current_state:
azvyagintsev73720db2018-06-20 17:28:09 +0300223 return _update_mirror(name, tgt)
azvyagintseve5c4e832018-01-25 20:02:46 +0200224 return current_state