azvyagintsev | e5c4e83 | 2018-01-25 20:02:46 +0200 | [diff] [blame] | 1 | #!/usr/bin/env python |
| 2 | """ |
| 3 | Management of debmirror |
| 4 | ======================= |
| 5 | |
| 6 | Create debian mirrors, using debmirror |
| 7 | -------------------------------------- |
| 8 | |
| 9 | .. code-block:: yaml |
| 10 | debmirror_test1_present: |
| 11 | debmirror.mirror_present: |
| 12 | - name: test1 |
| 13 | |
| 14 | """ |
| 15 | import logging |
| 16 | import os |
| 17 | from functools import wraps |
| 18 | from salt.exceptions import CommandExecutionError, SaltInvocationError |
| 19 | log = logging.getLogger(__name__) |
| 20 | |
| 21 | def __virtual__(): |
| 22 | ''' |
| 23 | Only load this module if debmirror is installed with deps. |
| 24 | ''' |
| 25 | return 'debmirror' |
| 26 | |
| 27 | def _test_call(method): |
| 28 | (resource, functionality) = method.func_name.split('_') |
| 29 | if functionality == 'present': |
| 30 | functionality = 'updated' |
| 31 | else: |
| 32 | functionality = 'removed' |
| 33 | |
| 34 | @wraps(method) |
| 35 | def check_for_testing(name, *args, **kwargs): |
| 36 | if __opts__.get('test', None): |
| 37 | return _no_change(name, resource, test=functionality) |
| 38 | return method(name, *args, **kwargs) |
| 39 | return check_for_testing |
| 40 | |
| 41 | def _created(name, resource, resource_definition={}): |
| 42 | changes_dict = {'name': name, |
| 43 | 'changes': resource_definition, |
| 44 | 'result': True, |
| 45 | 'comment': '{0} {1} created'.format(resource, name)} |
| 46 | return changes_dict |
| 47 | |
| 48 | def _failed(name, resource, resource_definition={}): |
| 49 | changes_dict = {'name': name, |
| 50 | 'changes': resource_definition, |
| 51 | 'result': False, |
| 52 | 'comment': '{0} {1} failed to create'.format(resource, name)} |
| 53 | return changes_dict |
| 54 | |
| 55 | def _no_change(name, resource, test=False): |
| 56 | changes_dict = {'name': name, |
| 57 | 'changes': {}, |
| 58 | 'result': True} |
| 59 | if test: |
| 60 | changes_dict['comment'] = \ |
| 61 | '{0} {1} will be {2}'.format(resource, name, test) |
| 62 | else: |
| 63 | changes_dict['comment'] = \ |
| 64 | '{0} {1} is in correct state'.format(resource, name) |
| 65 | return changes_dict |
| 66 | |
| 67 | def _check_state(name, tgt): |
| 68 | lock_file = _get_target_path(name,tgt)['lock_file'] |
| 69 | if os.path.isfile(lock_file) and not tgt.get('force', False) : |
azvyagintsev | b80d622 | 2018-02-19 15:53:40 +0200 | [diff] [blame^] | 70 | return _no_change(name, '{} exist=>repo locked.'.format(lock_file)) |
azvyagintsev | e5c4e83 | 2018-01-25 20:02:46 +0200 | [diff] [blame] | 71 | return False |
| 72 | |
| 73 | def _get_target_path(name,tgt): |
| 74 | if not tgt.get('target_dir',False): |
| 75 | raise SaltInvocationError('Argument "target_dir" is mandatory! ') |
| 76 | return {'target_dir': tgt.get('target_dir'), |
| 77 | 'lock_file': tgt.get('lock_file', os.path.join(tgt.get('target_dir'), '.lockmirror')), |
| 78 | 'log_file': tgt.get('log_file', '/var/log/debmirror_'.join(name)) } |
| 79 | |
| 80 | def _get_cmdline(name,tgt): |
| 81 | cmdline = " debmirror " |
| 82 | if tgt.get('extra_flags'): |
| 83 | cmdline += ' '.join(tgt['extra_flags']) |
| 84 | if tgt.get('dist'): |
| 85 | cmdline += ' --dist=' + ",".join(tgt['dist']) |
| 86 | if tgt.get('section'): |
| 87 | cmdline += ' --section=' + ",".join(tgt['section']) |
| 88 | if tgt.get('method'): |
| 89 | cmdline += ' --method=' + tgt.get('method') |
| 90 | if tgt.get('mirror_host'): |
| 91 | cmdline += ' --host="{}"'.format(tgt.get('mirror_host')) |
| 92 | if tgt.get('mirror_root'): |
| 93 | cmdline += ' --root="{}"'.format(tgt.get('mirror_root')) |
| 94 | if tgt.get('arch', 'amd64'): |
| 95 | cmdline += ' --arch=' + ','.join(tgt.get('arch')) |
| 96 | if tgt.get('filter'): |
| 97 | for key, value in enumerate(sorted(tgt['filter'])): |
| 98 | cmdline += " " + tgt['filter'][value] |
| 99 | if tgt.get('target_dir',False): |
| 100 | cmdline += ' ' + _get_target_path(name,tgt)['target_dir'] |
| 101 | return cmdline |
| 102 | |
| 103 | def _update_mirror(name,tgt): |
| 104 | # Remove old lock file, is was. |
| 105 | lock_file = _get_target_path(name,tgt)['lock_file'] |
| 106 | if os.path.isfile(lock_file): |
| 107 | log.debug("Removing lockfile:{} for mirror{}".format(lock_file,name)) |
| 108 | __states__['file.absent'](lock_file) |
| 109 | cmdline = _get_cmdline(name,tgt) |
| 110 | # init file logger |
| 111 | l_dir = os.path.dirname(tgt['log_file']) |
| 112 | if not os.path.isdir(l_dir): |
| 113 | __salt__['file.makedirs'](l_dir) |
| 114 | fh = logging.FileHandler("{0}".format(_get_target_path(name,tgt)['log_file'])) |
| 115 | fh.setLevel(logging.DEBUG) |
| 116 | fh_format = logging.Formatter('%(asctime)s - %(lineno)d - %(levelname)-8s - %(message)s') |
| 117 | fh.setFormatter(fh_format) |
| 118 | log2file = logging.getLogger("debmirror") |
| 119 | log2file.addHandler(fh) |
| 120 | result = __salt__['cmd.run_all'](cmdline, redirect_stderr=True) |
| 121 | log2file.debug(result['stdout']) |
| 122 | # destroy file logger |
| 123 | for i in list(log2file.handlers): |
| 124 | log2file.removeHandler(i) |
| 125 | i.flush() |
| 126 | i.close() |
| 127 | if result['retcode'] != 0: |
| 128 | #raise CommandExecutionError(result['stderr']) |
| 129 | return _failed(name, "debmirror failed.Reason {0}".format(result['stderr'])) |
| 130 | if tgt.get('lock_target',None): |
| 131 | __states__['file.touch'](lock_file) |
| 132 | return _created(name, "Mirror {0} created.".format(name) ) |
| 133 | |
| 134 | @_test_call |
| 135 | def mirror_present(name, **kwargs): |
| 136 | ''' |
| 137 | |
| 138 | :param name: mirror key name |
| 139 | ''' |
| 140 | try: |
| 141 | tgt = __salt__['config.get']('debmirror')['client']['mirrors'][name] |
| 142 | except KeyError: |
| 143 | comment ='Mirror "{0}" not exist in configurathion,skipping..'.format(name) |
| 144 | return _no_change(name, comment) |
| 145 | |
| 146 | current_state = _check_state(name,tgt) |
| 147 | if not current_state: |
| 148 | return _update_mirror(name,tgt) |
| 149 | return current_state |