Michael Polenchuk | 75ea11e | 2018-08-22 14:34:11 +0400 | [diff] [blame] | 1 | # -*- coding: utf-8 -*- |
| 2 | ''' |
| 3 | Support for Open vSwitch database configuration. |
| 4 | |
| 5 | ''' |
| 6 | from __future__ import absolute_import |
| 7 | |
| 8 | import logging |
| 9 | import salt.utils |
| 10 | |
| 11 | log = logging.getLogger(__name__) |
| 12 | |
| 13 | |
| 14 | def __virtual__(): |
| 15 | ''' |
| 16 | Only load the module if Open vSwitch is installed |
| 17 | ''' |
| 18 | if salt.utils.which('ovs-vsctl'): |
| 19 | return 'ovs_config' |
| 20 | return False |
| 21 | |
| 22 | |
| 23 | def _retcode_to_bool(retcode): |
| 24 | ''' |
| 25 | Evaulates ovs-vsctl command`s retcode value. |
| 26 | |
| 27 | Args: |
| 28 | retcode: Value of retcode field from response. |
| 29 | ''' |
| 30 | return True if retcode == 0 else False |
| 31 | |
| 32 | |
| 33 | def set(cfg, value, wait=True): |
| 34 | ''' |
| 35 | Updates a specified configuration entry. |
| 36 | |
| 37 | Args: |
| 38 | cfg/value: a config entry to update |
| 39 | wait: wait or not for ovs-vswitchd to reconfigure itself before it exits. |
| 40 | |
| 41 | CLI Example: |
| 42 | .. code-block:: bash |
| 43 | |
| 44 | salt '*' ovs_config.set other_config:dpdk-init true |
| 45 | ''' |
| 46 | wait = '' if wait else '--no-wait ' |
| 47 | |
| 48 | cmd = 'ovs-vsctl {0}set Open_vSwitch . {1}="{2}"'.format(wait, cfg, str(value).lower()) |
| 49 | result = __salt__['cmd.run_all'](cmd) |
| 50 | return _retcode_to_bool(result['retcode']) |
| 51 | |
| 52 | |
| 53 | def remove(cfg): |
| 54 | ''' |
| 55 | Removes a specified configuration entry. |
| 56 | |
| 57 | Args: |
| 58 | cfg: a config entry to remove |
| 59 | |
| 60 | CLI Example: |
| 61 | .. code-block:: bash |
| 62 | |
| 63 | salt '*' ovs_config.remove other_config |
| 64 | ''' |
| 65 | if ':' in cfg: |
| 66 | section, key = cfg.split(':') |
| 67 | cmd = 'ovs-vsctl remove Open_vSwitch . {} {}'.format(section, key) |
| 68 | else: |
| 69 | cmd = 'ovs-vsctl clear Open_vSwitch . ' + cfg |
| 70 | |
| 71 | result = __salt__['cmd.run_all'](cmd) |
| 72 | return _retcode_to_bool(result['retcode']) |
| 73 | |
| 74 | |
| 75 | def list(): |
| 76 | ''' |
| 77 | Return a current config of Open vSwitch |
| 78 | |
| 79 | CLI Example: |
| 80 | |
| 81 | .. code-block:: bash |
| 82 | |
| 83 | salt '*' ovs_config.list |
| 84 | ''' |
| 85 | cmd = 'ovs-vsctl list Open_vSwitch .' |
| 86 | result = __salt__['cmd.run_all'](cmd) |
| 87 | |
| 88 | if result['retcode'] == 0: |
| 89 | config = {} |
| 90 | for l in result['stdout'].splitlines(): |
| 91 | cfg, value = map((lambda x: x.strip()), l.split(' : ')) |
| 92 | if value.startswith('{') and len(value) > 2: |
| 93 | for i in value[1:-1].replace('"', '').split(', '): |
| 94 | _k, _v = i.split('=') |
| 95 | config['{}:{}'.format(cfg,_k)] = _v |
| 96 | else: |
| 97 | config[cfg] = value |
| 98 | |
| 99 | return config |
| 100 | else: |
| 101 | return False |